<?php
// Handle AJAX requests BEFORE any HTML output
if (isset($_POST['action'])) {
    if (session_status() === PHP_SESSION_NONE)
        session_start();
    require_once dirname(__DIR__, 2) . '/include/con_data.php';

    // Check auth
    if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'manager') {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }

    $shop_id = $_SESSION['shop_id'] ?? null;
    if (!$shop_id) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'No shop assigned']);
        exit;
    }

    $action = $_POST['action'];

    try {
        if ($action === 'save_rates') {
            $rates = $_POST['rates'] ?? []; // Array of { currency_id: 'CUR_X', rate: 1234 }

            if (empty($rates)) {
                echo json_encode(['success' => false, 'message' => 'No rates provided']);
                exit;
            }

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("INSERT INTO rates (rate_id, currencys_id, rate_amount, rate_date, rate_datetime, shop_id) 
                                   VALUES (:rate_id, :curr_id, :amount, :date, :datetime, :shop_id)");

            $today = date('Y-m-d');
            $now = date('Y-m-d H:i:s');

            foreach ($rates as $curr_id => $amount) {
                // Skip if amount is invalid
                if (!is_numeric($amount) || $amount <= 0)
                    continue;

                // Generate Rate ID (simple approach for now, trigger handles it better but let's send NULL if trigger exists or generate if strict)
                // Looking at schema, trigger `trg_rates_before_insert` handles NULL rate_id.
                // So we pass NULL for rate_id.

                $stmt->execute([
                    ':rate_id' => null, // Let trigger handle it
                    ':curr_id' => $curr_id,
                    ':amount' => $amount,
                    ':date' => $today,
                    ':datetime' => $now,
                    ':shop_id' => $shop_id
                ]);
            }

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'ບັນທຶກອັດຕາແລກປ່ຽນສຳເລັດ']);
            exit;
        }
    } catch (PDOException $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}

// ===== Page rendering =====
$page_title = 'ກຳນົດອັດຕາແລກປ່ຽນ';
require_once '../includes/header.php';

$shop_id = $_SESSION['shop_id'];

// Get Currencies and their LATEST rates
// We use a correlated subquery or join to get the latest rate for each currency
$sql = "SELECT c.*, 
        (SELECT rate_amount FROM rates r 
         WHERE r.currencys_id = c.currencys_id AND r.shop_id = c.shop_id 
         ORDER BY r.rate_datetime DESC LIMIT 1) as current_rate
        FROM currencys c 
        WHERE c.shop_id = :shop_id AND c.currencys_name != 'Lao Kip'
        ORDER BY c.id ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute([':shop_id' => $shop_id]);
$currencies = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get History
$history_sql = "SELECT r.*, c.currencys_name, c.currencys_symbol 
                FROM rates r 
                JOIN currencys c ON r.currencys_id = c.currencys_id 
                WHERE r.shop_id = :shop_id AND c.currencys_name != 'Lao Kip'
                ORDER BY r.id DESC LIMIT 20";
$history_stmt = $pdo->prepare($history_sql);
$history_stmt->execute([':shop_id' => $shop_id]);
$history = $history_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .page-header h2 {
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 25px;
        width: 100%;
        margin: 0;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
    }

    .rate-form-group {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid var(--border-color);
        border-radius: 10px;
        background: var(--bg-primary);
        display: flex;
        align-items: center;
        gap: 15px;
        transition: all 0.2s;
    }

    .rate-form-group:hover {
        border-color: var(--accent);
        background: var(--card-bg);
    }

    .currency-info {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .currency-icon {
        width: 45px;
        height: 45px;
        background: rgba(193, 153, 42, 0.1);
        color: var(--accent);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        font-weight: bold;
    }

    .currency-details h4 {
        margin: 0;
        font-size: 16px;
        color: var(--text-primary);
    }

    .currency-details span {
        font-size: 13px;
        color: var(--text-secondary);
    }

    .rate-input-group {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 5px;
    }

    .rate-input-wrapper {
        position: relative;
        width: 200px;
    }

    .rate-input-wrapper input {
        width: 100%;
        padding: 10px 15px;
        padding-right: 40px;
        border: 2px solid var(--border-color);
        border-radius: 8px;
        background: var(--card-bg);
        color: var(--text-primary);
        font-size: 16px;
        font-weight: 600;
        text-align: right;
        transition: all 0.2s;
    }

    .rate-input-wrapper input:focus {
        border-color: var(--accent);
        outline: none;
        box-shadow: 0 0 0 3px rgba(193, 153, 42, 0.1);
    }

    .rate-input-wrapper input:disabled {
        background: var(--bg-secondary);
        color: var(--text-secondary);
        border-color: transparent;
    }

    .rate-unit {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-secondary);
        font-weight: 500;
        font-size: 14px;
    }

    .current-rate-label {
        font-size: 12px;
        color: var(--text-secondary);
    }

    .base-currency-badge {
        background: #28a745;
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 600;
        margin-left: 8px;
    }

    .btn-save {
        width: 100%;
        padding: 15px;
        background: var(--accent);
        color: white;
        border: none;
        border-radius: 10px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }

    .btn-save:hover {
        opacity: 0.9;
        transform: translateY(-2px);
    }

    .history-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 25px;
        width: 100%;
        margin: 20px 0 0;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
    }

    .pro-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
    }

    .pro-table th {
        background: rgba(193, 153, 42, 0.1);
        padding: 12px 14px;
        font-weight: 600;
        font-size: 13px;
        color: var(--text-secondary);
        text-align: left;
    }

    .pro-table td {
        padding: 12px 14px;
        border-bottom: 1px solid var(--border-color);
        color: var(--text-primary);
        font-size: 14px;
    }

    .pro-table tr:last-child td {
        border-bottom: none;
    }
</style>

<div class="page-header">
    <h2><i class="fas fa-money-bill-wave" style="color:var(--accent)"></i> ກຳນົດອັດຕາແລກປ່ຽນປະຈຳວັນ</h2>
</div>

<div class="card">
    <form id="ratesForm" onsubmit="saveRates(event)">
        <h3 style="margin-top:0;margin-bottom:20px;border-bottom:1px solid var(--border-color);padding-bottom:15px;">
            <i class="fas fa-calendar-alt"></i> ວັນທີ:
            <?= date('d/m/Y') ?>
        </h3>

        <?php foreach ($currencies as $curr): ?>
            <div class="rate-form-group">
                <div class="currency-info">
                    <div class="currency-icon">
                        <?= $curr['currencys_symbol'] ?>
                    </div>
                    <div class="currency-details">
                        <h4>
                            <?= $curr['currencys_name'] ?>
                            <?php if ($curr['base_currency'] === 'YES'): ?>
                                <span class="base-currency-badge">ສະກຸນເງິນຫຼັກ</span>
                            <?php endif; ?>
                        </h4>
                        <span>
                            <?= $curr['currencys_fullname'] ?>
                        </span>
                    </div>
                </div>

                <div class="rate-input-group">
                    <?php if ($curr['base_currency'] === 'YES'): ?>
                        <!-- Base currency (LAK) - Just display checkmark or static text, NO input -->
                        <div style="color:var(--success);font-weight:600;display:flex;align-items:center;gap:5px;">
                            <i class="fas fa-check-circle"></i> ອັດຕາຄົງທີ່ (1)
                        </div>
                    <?php else: ?>
                        <div class="rate-input-wrapper">
                            <input type="number" step="0.01" name="rates[<?= $curr['currencys_id'] ?>]"
                                value="<?= $curr['current_rate'] ? floatval($curr['current_rate']) : '' ?>" placeholder="0.00"
                                required>
                            <span class="rate-unit">₭</span>
                        </div>
                        <span class="current-rate-label">
                            ລ່າສຸດ:
                            <?= $curr['current_rate'] ? number_format($curr['current_rate'], 2) : '-' ?> ₭
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>

        <button type="submit" class="btn-save">
            <i class="fas fa-save"></i> ບັນທຶກອັດຕາແລກປ່ຽນ
        </button>
    </form>
</div>

<!-- History Table -->
<div class="history-card">
    <h3 style="margin-top:0;margin-bottom:15px;display:flex;align-items:center;gap:10px;">
        <i class="fas fa-history" style="color:var(--text-secondary)"></i> ປະຫວັດການປ່ຽນແປງ
    </h3>

    <div style="overflow-x:auto;">
        <table class="pro-table">
            <thead>
                <tr>
                    <th>ວັນທີ/ເວລາ</th>
                    <th>ສະກຸນເງິນ</th>
                    <th>ອັດຕາແລກປ່ຽນ</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($history)): ?>
                    <tr>
                        <td colspan="3" style="text-align:center;padding:20px;color:var(--text-secondary);">
                            ບໍ່ພົບປະຫວັດການປ່ຽນແປງ
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($history as $row): ?>
                        <tr>
                            <td><?= date('d/m/Y H:i', strtotime($row['rate_datetime'])) ?></td>
                            <td>
                                <strong><?= $row['currencys_name'] ?></strong>
                                (<?= $row['currencys_symbol'] ?>)
                            </td>
                            <td style="font-weight:600;color:var(--accent);">
                                1 <?= $row['currencys_symbol'] ?> = <?= number_format($row['rate_amount'], 2) ?> ₭
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
    function saveRates(e) {
        e.preventDefault();

        Swal.fire({
            title: 'ຢືນຢັນການບັນທຶກ?',
            text: "ຕ້ອງການບັນທຶກອັດຕາແລກປ່ຽນຂອງມື້ນີ້ບໍ່?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'ບັນທຶກ',
            cancelButtonText: 'ຍົກເລີກ'
        }).then((result) => {
            if (result.isConfirmed) {
                const btn = document.querySelector('.btn-save');
                const oldContent = btn.innerHTML;
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ກຳລັງບັນທຶກ...';
                btn.disabled = true;

                const formData = new FormData(e.target);
                formData.append('action', 'save_rates');

                fetch('rates.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(r => r.json())
                    .then(res => {
                        if (res.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'ສຳເລັດ!',
                                text: res.message,
                                timer: 1500,
                                showConfirmButton: false
                            }).then(() => {
                                window.location.reload();
                            });
                        } else {
                            Swal.fire('ຜິດພາດ!', res.message, 'error');
                        }
                    })
                    .catch(err => {
                        console.error(err);
                        Swal.fire('ຜິດພາດ!', 'ເກີດຂໍ້ຜິດພາດໃນການເຊື່ອມຕໍ່', 'error');
                    })
                    .finally(() => {
                        btn.innerHTML = oldContent;
                        btn.disabled = false;
                    });
            }
        });
    }
</script>

<?php require_once '../includes/footer.php'; ?>