<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../app/classes/BalanceHistory.php';
require_once __DIR__ . '/../../app/classes/NotificationManager.php';
use App\classes\BalanceHistory;

// Initialize response variables
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Validate input
        $agent_id = isset($_POST['agent_id']) ? intval($_POST['agent_id']) : 0;
        $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;

        // Validate required fields
        if ($agent_id <= 0) {
            throw new Exception('Invalid agent ID provided.');
        }

        if ($amount == 0) {
            throw new Exception('Payment amount cannot be zero.');
        }

        if (abs($amount) > 50000) {
            throw new Exception('Payment amount cannot exceed GHS 50,000.');
        }

        // Check if agent exists
        $stmt = $conn->prepare("SELECT id, username, balance FROM agents WHERE id = ?");
        $stmt->bind_param("i", $agent_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            throw new Exception('Agent not found.');
        }
        
        $agent = $result->fetch_assoc();
        $currentBalance = $agent['balance'];
        $stmt->close();

        // Check if debit would result in negative balance
        if ($amount < 0 && ($currentBalance + $amount) < 0) {
            throw new Exception('Insufficient balance. Cannot debit GHS ' . number_format(abs($amount), 2) . '. Current balance: GHS ' . number_format($currentBalance, 2));
        }

        // Start transaction
        $conn->begin_transaction();

        try {
            // Add payment record to the orders_payments table
            $stmt = $conn->prepare("INSERT INTO orders_payments (user_id, total_amount, payment_method, payment_status, created_at) VALUES (?, ?, 'manual', 'completed', NOW())");
            if (!$stmt) {
                throw new Exception('Database error: Failed to prepare payment record statement.');
            }
            $stmt->bind_param('id', $agent_id, $amount);
            if (!$stmt->execute()) {
                throw new Exception('Database error: Failed to insert payment record.');
            }
            $stmt->close();

            // Update the agent's balance
            $stmt = $conn->prepare("UPDATE agents SET balance = balance + ? WHERE id = ?");
            if (!$stmt) {
                throw new Exception('Database error: Failed to prepare balance update statement.');
            }
            $stmt->bind_param('di', $amount, $agent_id);
            if (!$stmt->execute()) {
                throw new Exception('Database error: Failed to update agent balance.');
            }
            $stmt->close();

            // Log balance change for payment credit
            $balanceLogResult = BalanceHistory::log($conn, $agent_id, $amount, 'payment', null, null);
            if (!$balanceLogResult) {
                // Log warning but don't fail the transaction
                error_log("Warning: Failed to log balance history for agent $agent_id, amount $amount");
            }

            // Send notification (don't fail transaction if this fails)
            try {
                $notificationManager = new NotificationManager($conn);
                $notificationData = [
                    'amount' => number_format(abs($amount), 2),
                    'balance' => number_format($currentBalance + $amount, 2)
                ];
                $notificationType = $amount > 0 ? 'admin_topup' : 'admin_debit';
                $notificationManager->sendNotification($agent_id, $notificationType, $notificationData);
            } catch (Exception $e) {
                // Log notification error but don't fail the transaction
                error_log("Notification error: " . $e->getMessage());
            }

            // Send in-app notification (don't fail transaction if this fails)
            try {
                require_once '../../app/classes/AdminNotificationManager.php';
                $adminNotificationManager = new AdminNotificationManager($conn);
                
                if ($amount > 0) {
                    $title = "Account Credited";
                    $message = "Your account has been credited with GHS " . number_format($amount, 2) . ". New balance: GHS " . number_format($currentBalance + $amount, 2);
                } else {
                    $title = "Account Debited";
                    $message = "GHS " . number_format(abs($amount), 2) . " has been debited from your account. New balance: GHS " . number_format($currentBalance + $amount, 2);
                }
                
                $adminNotificationManager->sendNotification(
                    $title,
                    $message,
                    1, // Admin ID (assuming admin ID is 1)
                    'specific',
                    [$agent_id],
                    'normal'
                );
            } catch (Exception $e) {
                // Log notification error but don't fail the transaction
                error_log("In-app notification error: " . $e->getMessage());
            }

            // Commit transaction
            $conn->commit();

            if ($amount > 0) {
                $message = "GHS " . number_format($amount, 2) . " has been successfully credited to " . htmlspecialchars($agent['username']) . "'s account!";
            } else {
                $message = "GHS " . number_format(abs($amount), 2) . " has been successfully debited from " . htmlspecialchars($agent['username']) . "'s account!";
            }
            $message_type = "success";
            // Close the modal after successful submission
            echo "<script>setTimeout(() => { if (typeof closePaymentModal === 'function') closePaymentModal(); }, 1000);</script>";

        } catch (Exception $e) {
            // Rollback transaction
            $conn->rollback();
            throw $e;
        }

    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
        $message_type = "error";
        error_log("Add Payment Error: " . $e->getMessage());
    }
} else {
    $message = "Invalid request method.";
    $message_type = "error";
}

// Redirect back to admin dashboard with message
$redirect_url = '../index.php?page=dashboard';
if (!empty($message)) {
    $redirect_url .= '&message=' . urlencode($message) . '&message_type=' . urlencode($message_type);
}

header('Location: ' . $redirect_url);
exit();
?>
