<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . "/../includes/admin_auth.php"; // Must be first
require_once '../includes/db.php';
require_once '../includes/mailer.php';

$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$type = $_GET['type'] ?? 'credit';

$message = "";
$user = null;

/* ==========================
   FUNCTION: FETCH USER + ACCOUNT (SAFE)
========================== */
function getUserAccount($conn, $user_id) {
    $stmt = $conn->prepare("
        SELECT 
            u.id,
            u.first_name,
            u.last_name,
            u.email,
            a.id AS account_id,
            a.balance,
            a.currency,
            a.account_number
        FROM users u
        LEFT JOIN accounts a ON u.id = a.user_id
        WHERE u.id = ?
        LIMIT 1
    ");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

/* ==========================
   CURRENCY SYMBOLS
========================== */
$currencySymbols = [
    'USD' => '$',
    'EUR' => '€',
    'GBP' => '£',
    'JPY' => '¥',
    'CNY' => '¥',
    'NGN' => '₦',
    'GHS' => '₵',
    'INR' => '₹',
    'CAD' => 'C$',
    'AUD' => 'A$'
];

/* ==========================
   INITIAL LOAD
========================== */
if ($user_id > 0) {
    $user = getUserAccount($conn, $user_id);
    if (!$user || !$user['account_id']) {
        $message = "User or account not found.";
        $user = null;
    }
}

/* ==========================
   HANDLE TRANSACTION
========================== */
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $user_id = intval($_POST['user_id']);
    $amount = floatval($_POST['amount']);
    $description = trim($_POST['description']);
    $action = $_POST['action'];

    if ($amount <= 0) {
        $message = "Invalid amount.";
    } else {

        $conn->begin_transaction();

        try {

            /* LOCK ACCOUNT */
            $stmt = $conn->prepare("
                SELECT 
                    u.email,
                    u.first_name,
                    u.last_name,
                    a.id AS account_id,
                    a.balance,
                    a.currency
                FROM users u
                LEFT JOIN accounts a ON u.id = a.user_id
                WHERE u.id = ?
                LIMIT 1
                FOR UPDATE
            ");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $data = $stmt->get_result()->fetch_assoc();

            if (!$data || !$data['account_id']) {
                throw new Exception("User/account not found.");
            }

            $account_id = $data['account_id'];
            $balance = (float)$data['balance'];
            $currency = $data['currency'];
            $symbol = $currencySymbols[$currency] ?? $currency;

            /* CALCULATE */
            if ($action === "credit") {
                $new_balance = $balance + $amount;
                $txn_type = "credit";
            } elseif ($action === "debit") {
                if ($balance < $amount) {
                    throw new Exception("Insufficient balance.");
                }
                $new_balance = $balance - $amount;
                $txn_type = "debit";
            } else {
                throw new Exception("Invalid action.");
            }

            /* UPDATE BALANCE */
            $update = $conn->prepare("UPDATE accounts SET balance = ? WHERE id = ?");
            $update->bind_param("di", $new_balance, $account_id);
            $update->execute();

            /* LOG TRANSACTION */
            $reference = strtoupper($txn_type) . '-' . time() . '-' . rand(1000,9999);
            $log = $conn->prepare("
                INSERT INTO transactions (account_id, type, amount, description, reference)
                VALUES (?, ?, ?, ?, ?)
            ");
            $log->bind_param(
                "isdss",
                $account_id,
                $txn_type,
                $amount,
                $description,
                $reference
            );
            $log->execute();

            /* CREATE NOTIFICATION */
            $notification_msg = "💰 You have received a {$txn_type} of {$symbol}{$amount}. Reference: {$reference}";
            $notify = $conn->prepare("
                INSERT INTO notifications (user_id, message)
                VALUES (?, ?)
            ");
            $notify->bind_param("is", $user_id, $notification_msg);
            $notify->execute();

            $conn->commit();

            /* REFRESH USER DATA */
            $user = getUserAccount($conn, $user_id);

            /* SEND EMAIL */
            $fullName = $data['first_name'] . ' ' . $data['last_name'];
            $subject = "Lombard Odier Financial Bank {$txn_type} Notification";

            $body = "
Hello {$fullName},

A {$txn_type} transaction has been completed.

Amount: {$symbol}{$amount}
Reference: {$reference}
New Balance: {$symbol}{$new_balance}

Description: {$description}
";

            try {
                sendMail($data['email'], $subject, $body);
            } catch (Exception $e) {}

            $message = "Transaction successful!";

        } catch (Exception $e) {
            $conn->rollback();
            $message = $e->getMessage();
        }
    }
}

/* ==========================
   VIEW
========================== */
ob_start();
?>

<div class="card">
    <h2>Credit / Debit User</h2>

    <?php if ($message): ?>
        <div class="alert"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <?php if ($user): ?>
        <div class="card">
            <p><strong>Name:</strong> <?= htmlspecialchars($user['first_name'].' '.$user['last_name']) ?></p>
            <p><strong>Account:</strong> <?= htmlspecialchars($user['account_number']) ?></p>
            <p><strong>Balance:</strong> <?= htmlspecialchars($user['currency'].' '.number_format($user['balance'],2)) ?></p>
        </div>
    <?php endif; ?>

    <form method="POST">
        <input type="hidden" name="user_id" value="<?= $user_id ?>">

        <label>Action</label>
        <select name="action" class="form-control" required>
            <option value="credit" <?= $type === 'credit' ? 'selected' : '' ?>>Credit</option>
            <option value="debit" <?= $type === 'debit' ? 'selected' : '' ?>>Debit</option>
        </select>

        <label>Amount</label>
        <input type="number" step="0.01" name="amount" class="form-control" required>

        <label>Description</label>
        <textarea name="description" class="form-control" required></textarea>

        <br>

        <button type="submit" class="btn btn-primary">
            Submit Transaction
        </button>
    </form>
</div>

<?php
$content = ob_get_clean();
$pageTitle = "Credit / Debit User";
include '../components/admin_layout.php';
?>