<?php
require_once '../connection.php';

// Check if user is admin
if (!isAdmin()) {
    header('Location: ../login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $client_id = $_POST['client_id'] ?? 0;
    $amount = floatval($_POST['amount'] ?? 0);
    $reason = trim($_POST['reason'] ?? '');
    
    if ($client_id && $amount > 0) {
        try {
            $pdo->beginTransaction();
            
            // Get client information
            $stmt = $pdo->prepare("SELECT full_name, wallet_balance FROM clients WHERE id = ?");
            $stmt->execute([$client_id]);
            $client = $stmt->fetch();
            
            if (!$client) {
                throw new Exception("Client not found!");
            }
            
            if ($client['wallet_balance'] < $amount) {
                throw new Exception("Insufficient wallet balance!");
            }
            
            $old_balance = $client['wallet_balance'];
            $new_balance = $old_balance - $amount;
            
            // Update wallet balance
            $stmt = $pdo->prepare("UPDATE clients SET wallet_balance = wallet_balance - ? WHERE id = ?");
            $stmt->execute([$amount, $client_id]);
            
            // Generate unique reference
            $reference = 'ADMIN_DEDUCT_' . time() . '_' . uniqid();
            
            // Record transaction (negative amount for deduction)
            $stmt = $pdo->prepare("
                INSERT INTO transactions (client_id, amount, type, reference, description, status) 
                VALUES (?, ?, 'admin_deduction', ?, ?, 'completed')
            ");
            $description = "Manual fund deduction by admin. Reason: {$reason}. " .
                           "Old balance: $" . number_format($old_balance, 2) . 
                           ", Deducted: $" . number_format($amount, 2) . 
                           ", New balance: $" . number_format($new_balance, 2);
            
            $stmt->execute([$client_id, -$amount, $reference, $description]);
            
            // Log the admin action
            $stmt = $pdo->prepare("
                INSERT INTO payment_logs (client_id, amount, payment_method, status, description) 
                VALUES (?, ?, 'admin_manual', 'completed', ?)
            ");
            $stmt->execute([$client_id, -$amount, "Admin deducted funds: $" . number_format($amount, 2) . " - Reason: {$reason}"]);
            
            $pdo->commit();
            
            $_SESSION['success'] = "Successfully deducted $" . number_format($amount, 2) . " from {$client['full_name']}'s wallet!<br>
                                    Reason: {$reason}<br>
                                    Old balance: $" . number_format($old_balance, 2) . "<br>
                                    New balance: $" . number_format($new_balance, 2);
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = "Error deducting funds: " . $e->getMessage();
        }
    } else {
        $_SESSION['error'] = "Invalid amount or client ID";
    }
    
    header('Location: view_client.php?id=' . $client_id);
    exit();
} else {
    header('Location: dashboard.php');
    exit();
}
?>