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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$client_id = $_GET['id'] ?? 0;
$amount = $_GET['amount'] ?? 0;

// Debug: Log the received values
error_log("Admin Add Funds - Client ID: $client_id, Amount: $amount");

if ($client_id && $amount > 0) {
    try {
        // Start transaction
        $pdo->beginTransaction();
        
        // First, check if client exists and get current balance
        $stmt = $pdo->prepare("SELECT full_name, wallet_balance FROM clients WHERE id = ?");
        $stmt->execute([$client_id]);
        $client = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Debug: Check if client was found
        error_log("Client found: " . print_r($client, true));
        
        if (!$client) {
            throw new Exception("Client not found with ID: $client_id");
        }
        
        $old_balance = floatval($client['wallet_balance']);
        $amount = floatval($amount);
        $new_balance = $old_balance + $amount;
        
        // Debug: Log balance calculation
        error_log("Old balance: $old_balance, Amount: $amount, New balance: $new_balance");
        
        // Update wallet balance - Check if column exists
        $stmt = $pdo->prepare("UPDATE clients SET wallet_balance = ? WHERE id = ?");
        $result = $stmt->execute([$new_balance, $client_id]);
        
        // Debug: Check if update was successful
        if (!$result) {
            throw new Exception("Failed to update wallet balance. Error: " . print_r($stmt->errorInfo(), true));
        }
        
        // Verify the update worked
        $stmt = $pdo->prepare("SELECT wallet_balance FROM clients WHERE id = ?");
        $stmt->execute([$client_id]);
        $updated = $stmt->fetch(PDO::FETCH_ASSOC);
        error_log("Updated balance in DB: " . print_r($updated, true));
        
        // Generate unique reference
        $reference = 'ADMIN_' . time() . '_' . uniqid();
        
        // Check if transactions table has correct structure
        $stmt = $pdo->prepare("DESCRIBE transactions");
        $stmt->execute();
        $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
        error_log("Transactions table columns: " . print_r($columns, true));
        
        // Record transaction - adjust column names based on your table
        $description = "Manual fund addition by admin. Old balance: $" . number_format($old_balance, 2) . 
                       ", Added: $" . number_format($amount, 2) . 
                       ", New balance: $" . number_format($new_balance, 2);
        
        // Try different SQL variations based on your table structure
        $sql = "INSERT INTO transactions (client_id, amount, type, reference, description, status, created_at) 
                VALUES (?, ?, 'wallet_deposit', ?, ?, 'completed', NOW())";
        
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([$client_id, $amount, $reference, $description]);
        
        if (!$result) {
            error_log("Transaction insert error: " . print_r($stmt->errorInfo(), true));
            throw new Exception("Failed to record transaction");
        }
        
        // Log the admin action if payment_logs table exists
        try {
            $stmt = $pdo->prepare("
                INSERT INTO payment_logs (client_id, amount, payment_method, status, description, created_at) 
                VALUES (?, ?, 'admin_manual', 'completed', ?, NOW())
            ");
            $stmt->execute([$client_id, $amount, "Admin added funds to wallet: $" . number_format($amount, 2)]);
            error_log("Payment log inserted successfully");
        } catch (Exception $e) {
            // Payment logs table might not exist or have different structure
            error_log("Payment log error (non-critical): " . $e->getMessage());
        }
        
        $pdo->commit();
        
        $_SESSION['success'] = "Successfully added $" . number_format($amount, 2) . " to {$client['full_name']}'s wallet!<br>
                                Old balance: $" . number_format($old_balance, 2) . "<br>
                                New balance: $" . number_format($new_balance, 2);
        
        error_log("Transaction completed successfully");
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("Error in admin_add_funds.php: " . $e->getMessage());
        $_SESSION['error'] = "Error adding funds: " . $e->getMessage();
    }
} else {
    $_SESSION['error'] = "Invalid amount or client ID. Amount: $amount, Client ID: $client_id";
    error_log("Invalid parameters - Client ID: $client_id, Amount: $amount");
}

header('Location: view_client.php?id=' . $client_id);
exit();
?>