<?php
require_once '../includes/session.php';
require_once '../includes/db.php';
require_once '../includes/mailer.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) session_start();

$transfer_id = $_GET['transfer_id'] ?? null;
$user_id     = $_SESSION['user_id'] ?? null;

if (!$transfer_id || !$user_id) {
    header("Location: /user/dashboard.php");
    exit;
}

$conn = db();

// -----------------------------
// Fetch transfer
// -----------------------------
$stmt = $conn->prepare("SELECT * FROM transfers WHERE id=? AND user_id=? LIMIT 1");
$stmt->bind_param("ii", $transfer_id, $user_id);
$stmt->execute();
$transfer = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$transfer) {
    die("Transfer not found.");
}

// -----------------------------
// Ensure all tokens are used
// -----------------------------
$stmt = $conn->prepare("SELECT COUNT(*) AS cnt FROM user_tokens WHERE user_id=? AND used=0");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$remaining_tokens = $stmt->get_result()->fetch_assoc()['cnt'];
$stmt->close();

if ($remaining_tokens > 0) {
    die("Not all tokens verified!");
}

// -----------------------------
// Fetch user & account info
// -----------------------------
$stmt = $conn->prepare("
    SELECT u.id, u.first_name, u.last_name, u.email,
           a.id AS account_id, a.balance, a.currency
    FROM users u
    LEFT JOIN accounts a ON a.user_id = u.id
    WHERE u.id=? LIMIT 1
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user || empty($user['email']) || !$user['account_id']) {
    die("User or account information missing.");
}

// Combine first + last name
$user_name = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
if ($user_name === '') $user_name = 'User';

$account_id = $user['account_id'];
$from_balance = floatval($user['balance']);
$total = floatval($transfer['total']);
$amount = floatval($transfer['amount']);
$currency = $user['currency'] ?? 'USD';

// -----------------------------
// Currency symbols
// -----------------------------
$symbols = [
    'USD'=>'$', 'EUR'=>'€', 'GBP'=>'£', 'JPY'=>'¥', 'CNY'=>'¥',
    'NGN'=>'₦', 'GHS'=>'₵', 'INR'=>'₹', 'CAD'=>'C$', 'AUD'=>'A$'
];
$symbol = $symbols[$currency] ?? $currency;

// Prevent overdraft
if ($from_balance < $total) {
    die("Insufficient balance.");
}

$new_balance = $from_balance - $total;

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

try {
    // ✅ Update user balance
    $stmt = $conn->prepare("UPDATE users SET balance=? WHERE id=?");
    $stmt->bind_param("di", $new_balance, $user_id);
    if (!$stmt->execute()) throw new Exception("Balance update failed.");
    $stmt->close();

    // ✅ ALSO update account balance (important for dashboard)
    $stmt = $conn->prepare("UPDATE accounts SET balance=? WHERE user_id=?");
    $stmt->bind_param("di", $new_balance, $user_id);
    if (!$stmt->execute()) throw new Exception("Account balance update failed.");
    $stmt->close();

    // ✅ Get user's account ID
    $stmt = $conn->prepare("SELECT id FROM accounts WHERE user_id=? LIMIT 1");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $account = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$account) {
        throw new Exception("User account not found.");
    }

    $account_id = $account['id'];

   // ✅ Insert debit transaction with reference
$txn_type = 'debit';
$reference = 'TRF-' . strtoupper(bin2hex(random_bytes(4))); // generates a unique transfer reference

$stmt = $conn->prepare("
    INSERT INTO transactions (account_id, type, amount, reference, created_at)
    VALUES (?, ?, ?, ?, NOW())
");
$stmt->bind_param("isds", $account_id, $txn_type, $total, $reference);

if (!$stmt->execute()) {
    throw new Exception("Transaction insert failed.");
}
$stmt->close();
    
 // ================================
    // ✅ 5. ADD NOTIFICATION HERE 👇
    // ================================
    $notification_message = "Debit Alert: {$symbol}" . number_format($total, 2) .
        " has been deducted from your account. New balance: {$symbol}" . number_format($new_balance, 2);

    $stmt = $conn->prepare("
        INSERT INTO notifications (user_id, message, is_read, created_at)
        VALUES (?, ?, 0, NOW())
    ");

    $stmt->bind_param("is", $user_id, $notification_message);

    if (!$stmt->execute()) {
        throw new Exception("Notification insert failed.");
    }
    $stmt->close();

    // ✅ Update transfer status
    $stmt = $conn->prepare("UPDATE transfers SET status='completed' WHERE id=?");
    $stmt->bind_param("i", $transfer_id);
    if (!$stmt->execute()) throw new Exception("Transfer update failed.");
    $stmt->close();

    // ✅ Final commit
    $conn->commit();

} catch (Exception $e) {
    $conn->rollback();
    die("Transaction failed: " . $e->getMessage());
}

// -----------------------------
// Send email with currency symbol
// -----------------------------
try {
    $formatted_amount = number_format($amount, 2);
    $formatted_total  = number_format($total, 2);

    $message = "
        <p>Hello <b>$user_name</b>,</p>
        <p>Your <b>{$transfer['type']}</b> transfer has been completed successfully.</p>
        <div style='background:#f0f4ff; padding:15px; border-radius:6px; margin:15px 0;'>
            <p><b>Amount:</b> $symbol$formatted_amount</p>
            <p><b>Total Debited:</b> $symbol$formatted_total</p>
            <p><b>Remaining Balance:</b> $symbol" . number_format($new_balance,2) . "</p>
        </div>
        <p>Thank you for using our services.</p>
    ";

    sendMail($user['email'], "Transfer Completed", $message);

} catch (Exception $e) {
    error_log("Email error: " . $e->getMessage());
}

// -----------------------------
// Show confirmation before redirect
// -----------------------------

echo "
<!DOCTYPE html>
<html>
<head>
    <title>Transfer Completed</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f6f9;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .confirmation-box {
            background-color: #ffffff;
            padding: 30px 40px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 400px;
        }
        .confirmation-box h2 {
            color: #1a73e8;
            margin-bottom: 20px;
        }
        .confirmation-box p {
            font-size: 16px;
            color: #333;
            margin: 8px 0;
        }
        .confirmation-box .amount {
            font-weight: bold;
            color: #000;
        }
        .confirmation-box .status {
            font-weight: bold;
            color: green;
        }
        .confirmation-box small {
            color: #777;
            display: block;
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <div class='confirmation-box'>
        <h2>✅ Transfer Completed</h2>
        <p>Amount: <span class='amount'>{$symbol}" . number_format($amount, 2) . "</span></p>
        <p>Total Debited: <span class='amount'>{$symbol}" . number_format($total, 2) . "</span></p>
        <p>Remaining Balance: <span class='amount'>{$symbol}" . number_format($new_balance, 2) . "</span></p>
        <p>Status: <span class='status'>Completed</span></p>
        <small>You will be redirected to your dashboard in 5 seconds...</small>
    </div>

    <script>
        setTimeout(function() {
            window.location.href = '/user/dashboard.php';
        }, 5000);
    </script>
</body>
</html>
";

exit;
?>