<?php
// Enable error reporting for debugging (turn off in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require 'config.php';
require 'includes/mailer.php';

// Super-Admin only access check
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'super-admin') {
    header("Location: login.php");
    exit();
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $sender_id = $_SESSION['user_id'];
    $recipient_id = intval($_POST['recipient_id']);
    $amount = floatval($_POST['amount']);

    if ($amount <= 0) {
        showMessageAndRedirect("Invalid amount entered.", false);
    }

    // Fetch Super-Admin details (sender)
    $stmt = $conn->prepare("SELECT username, email, balance FROM users WHERE id = ?");
    $stmt->bind_param("i", $sender_id);
    $stmt->execute();
    $stmt->bind_result($sender_name, $sender_email, $sender_balance);
    if (!$stmt->fetch()) {
        $stmt->close();
        showMessageAndRedirect("Sender not found.", false);
    }
    $stmt->close();

    // Check if Super-Admin has enough balance
    if ($sender_balance < $amount) {
        showMessageAndRedirect("Insufficient balance.", false);
    }

    // Fetch recipient details
    $stmt = $conn->prepare("SELECT username, email, balance FROM users WHERE id = ?");
    $stmt->bind_param("i", $recipient_id);
    $stmt->execute();
    $stmt->bind_result($recipient_name, $recipient_email, $recipient_balance);
    if (!$stmt->fetch()) {
        $stmt->close();
        showMessageAndRedirect("Recipient not found.", false);
    }
    $stmt->close();

    // Begin DB transaction
    $conn->begin_transaction();
    try {
        // Deduct from Super-Admin
        $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
        $stmt->bind_param("di", $amount, $sender_id);
        $stmt->execute();
        $stmt->close();

        // Credit recipient
        $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $stmt->bind_param("di", $amount, $recipient_id);
        $stmt->execute();
        $stmt->close();

        // Log the transfer
        $stmt = $conn->prepare("INSERT INTO tbl_transfers (sender_id, recipient_id, amount, status, created_at) VALUES (?, ?, ?, 'success', NOW())");
        $stmt->bind_param("iid", $sender_id, $recipient_id, $amount);
        $stmt->execute();
        $stmt->close();

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

        // Send emails
        $subject = "Money Transfer Notification";
        $msg_sender = "Hi $sender_name,<br><br>You sent GHS " . number_format($amount, 2) . " to $recipient_name.";
        $msg_recipient = "Hi $recipient_name,<br><br>You received GHS " . number_format($amount, 2) . " from $sender_name.";

        sendEmail($sender_email, $subject, $msg_sender);
        sendEmail($recipient_email, $subject, $msg_recipient);

        // Update session balance
        $_SESSION['balance'] = $sender_balance - $amount;

        // Redirect
        showMessageAndRedirect("Money sent successfully!", true);
    } catch (Exception $e) {
        $conn->rollback();
        showMessageAndRedirect("Transfer failed. Please try again.", false);
    }
}

// Function to display message and redirect
function showMessageAndRedirect($message, $success)
{
    // Force redirection to Super-Admin dashboard
    $redirect_url = "super-admin.php";
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Transfer Status</title>
        <meta http-equiv="refresh" content="3;url=<?php echo $redirect_url; ?>">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-light d-flex align-items-center justify-content-center vh-100">
        <div class="text-center">
            <div class="alert alert-<?php echo $success ? 'success' : 'danger'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
            <p>Redirecting to Super-Admin dashboard...</p>
        </div>
    </body>
    </html>
    <?php
    exit();
}
?>
