<?php
require_once '../src/auth.php';
require_once __DIR__ . '/../config/database.php';
protectPage();

// 1. Fetch Safes
$safes = $pdo->query("SELECT cashbox_id, cashbox_name, current_balance FROM cash_boxes WHERE status = 'active'")->fetchAll();

// 2. Fetch Rates (Mapping your exchange_rates table)
$rates_query = $pdo->query("SELECT currency_name, buy_rate FROM exchange_rates");
$rates = [];
while ($row = $rates_query->fetch(PDO::FETCH_ASSOC)) {
    $rates[$row['currency_name']] = (float)$row['buy_rate'];
}

$message = "";

// 3. Process Transaction
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['do_transfer'])) {
    try {
        $pdo->beginTransaction();

        $from_id   = (int)$_POST['from_cashbox_id'];
        $to_id     = (int)$_POST['to_cashbox_id'];
        $amt_from  = (float)$_POST['amount_from'];
        $rate      = (float)$_POST['exchange_rate'];
        $amt_to    = round($amt_from * $rate, 2);
        $notes     = $_POST['notes'];
        $user_id   = $_SESSION['user_id'];
        $today     = date('Y-m-d H:i:s');

        if ($from_id === $to_id) throw new Exception("Source and Destination cannot be the same.");

        $stmt = $pdo->prepare("SELECT current_balance, cashbox_name FROM cash_boxes WHERE cashbox_id = ?");
        $stmt->execute([$from_id]);
        $source = $stmt->fetch();

        if ($source['current_balance'] < $amt_from) {
            throw new Exception("Insufficient balance in ({$source['cashbox_name']}).");
        }

        // UPDATE Balances
        $pdo->prepare("UPDATE cash_boxes SET current_balance = current_balance - ? WHERE cashbox_id = ?")->execute([$amt_from, $from_id]);
        $pdo->prepare("UPDATE cash_boxes SET current_balance = current_balance + ? WHERE cashbox_id = ?")->execute([$amt_to, $to_id]);

        // LOG Transaction
        $pdo->prepare("INSERT INTO currency_exchanges (user_id, from_cashbox_id, to_cashbox_id, amount_from, exchange_rate, amount_to, exchange_date, notes) 
                       VALUES (?, ?, ?, ?, ?, ?, ?, ?)")->execute([$user_id, $from_id, $to_id, $amt_from, $rate, $amt_to, $today, $notes]);

        $pdo->commit();
        header("Location: safes.php?success=transfer_completed");
        exit;

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $message = "<div class='alert error'>Error: " . $e->getMessage() . "</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Currency Transfer</title>
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <style>
        body { font-family: sans-serif; background: #f1f5f9; padding: 20px; direction: ltr; }
        .transfer-container { max-width: 600px; margin: auto; background: #fff; padding: 30px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #475569; }
        select, input, textarea { width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 5px; box-sizing: border-box; }
        input[readonly] { background: #f8fafc; cursor: not-allowed; }
        .info-box { background: #f0fdf4; padding: 15px; border-radius: 5px; border-left: 4px solid #16a34a; margin: 20px 0; }
        .total-display { font-size: 24px; font-weight: bold; color: #16a34a; }
        .btn { width: 100%; padding: 12px; border: none; border-radius: 5px; font-weight: bold; cursor: pointer; background: #16a34a; color: #fff; }
        .alert { padding: 10px; background: #fee2e2; color: #991b1b; border-radius: 5px; margin-bottom: 15px; text-align: center; }
    </style>
</head>
<body>

<div class="transfer-container">
    <h2><i class="fas fa-exchange-alt"></i> Money Transfer</h2>
    <form method="POST">
        <?= $message ?>
        <div class="form-group">
            <label>From:</label>
            <select name="from_cashbox_id" id="from_id" required onchange="updateRate()">
                <option value="">-- Select Source --</option>
                <?php foreach($safes as $s): ?>
                    <option value="<?= $s['cashbox_id'] ?>" data-name="<?= $s['cashbox_name'] ?>">
                        <?= $s['cashbox_name'] ?> (<?= number_format($s['current_balance'], 2) ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label>To:</label>
            <select name="to_cashbox_id" id="to_id" required onchange="updateRate()">
                <option value="">-- Select Destination --</option>
                <?php foreach($safes as $s): ?>
                    <option value="<?= $s['cashbox_id'] ?>" data-name="<?= $s['cashbox_name'] ?>">
                        <?= $s['cashbox_name'] ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div style="display: flex; gap: 10px;">
            <div class="form-group" style="flex: 2;">
                <label>Amount:</label>
                <input type="number" step="0.01" name="amount_from" id="amt_from" required oninput="calculate()">
            </div>
            <div class="form-group" style="flex: 1;">
                <label>Rate (Fixed):</label>
                <input type="number" step="0.000001" name="exchange_rate" id="ex_rate" value="1.00" readonly>
            </div>
        </div>

        <div class="info-box">
            <label>You will receive:</label>
            <div class="total-display" id="display_total">0.00</div>
        </div>

        <div class="form-group">
            <label>Notes:</label>
            <textarea name="notes" rows="2"></textarea>
        </div>

        <button type="submit" name="do_transfer" class="btn">AUTHORIZE TRANSFER</button>
    </form>
</div>



<script>
    const dbRates = {
        USD_SAR: <?= $rates['USD_SAR'] ?? 3.75 ?>,
        USD_YER: <?= $rates['USD_YER'] ?? 533 ?>,
        SAR_YER: <?= $rates['SAR_YER'] ?? 140 ?>
    };

    function updateRate() {
        const fromName = document.getElementById('from_id').options[document.getElementById('from_id').selectedIndex]?.getAttribute('data-name')?.toUpperCase() || "";
        const toName = document.getElementById('to_id').options[document.getElementById('to_id').selectedIndex]?.getAttribute('data-name')?.toUpperCase() || "";
        const rateInput = document.getElementById('ex_rate');
        
        let rate = 1;

        if (fromName.includes("DOLLAR") && toName.includes("SAR")) rate = dbRates.USD_SAR;
        else if (fromName.includes("SAR") && toName.includes("DOLLAR")) rate = 1 / dbRates.USD_SAR;
        
        else if (fromName.includes("DOLLAR") && toName.includes("YR")) rate = dbRates.USD_YER;
        else if (fromName.includes("YR") && toName.includes("DOLLAR")) rate = 1 / dbRates.USD_YER;
        
        else if (fromName.includes("SAR") && toName.includes("YR")) rate = dbRates.SAR_YER;
        else if (fromName.includes("YR") && toName.includes("SAR")) rate = 1 / dbRates.SAR_YER;

        rateInput.value = rate.toFixed(6);
        calculate();
    }

    function calculate() {
        const amt = parseFloat(document.getElementById('amt_from').value) || 0;
        const rate = parseFloat(document.getElementById('ex_rate').value) || 0;
        document.getElementById('display_total').innerText = (amt * rate).toLocaleString(undefined, {minimumFractionDigits: 2});
    }
</script>
</body>
</html>