<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "partner") {
    header("Location: ../auth/login.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM partner_shops WHERE user_id = ? LIMIT 1");
$stmt->execute([$_SESSION["user_id"]]);
$shop = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$shop) {
    die("No partner shop connected to this account.");
}

$error   = "";
$success = "";

/* ── Ensure pay_ref and transfer_photo columns exist ── */
try {
    $cols = $pdo->query("SHOW COLUMNS FROM credit_requests")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array("pay_ref", $cols)) {
        $pdo->exec("ALTER TABLE credit_requests ADD pay_ref VARCHAR(255) NULL AFTER reference_no");
    }
    if (!in_array("transfer_photo", $cols)) {
        $pdo->exec("ALTER TABLE credit_requests ADD transfer_photo VARCHAR(255) NULL AFTER pay_ref");
    }
} catch (Throwable $e) { /* ignore if no ALTER permission */ }

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $request_type   = $_POST["request_type"];
    $amount         = floatval(str_replace(",", "", $_POST["amount"] ?? 0));
    $payment_method = trim($_POST["payment_method"]);
    $reference_no   = trim($_POST["reference_no"]);
    $pay_ref        = trim($_POST["pay_ref"] ?? "");
    $note           = trim($_POST["note"]);

    /* ── Handle transfer photo upload ── */
    $transfer_photo = null;

    if (!empty($_FILES["transfer_photo"]["name"]) && $_FILES["transfer_photo"]["error"] === UPLOAD_ERR_OK) {
        $file      = $_FILES["transfer_photo"];
        $maxSize   = 10 * 1024 * 1024; /* 10 MB */

        if ($file["size"] > $maxSize) {
            $error = json_encode(["lo" => "ໄຟລ໌ໃຫຍ່ເກີນໄປ (ສູງສຸດ 10MB)", "en" => "File too large (max 10MB)."]);
        } else {
            $uploadDir = __DIR__ . "/../uploads/transfer_photos/";
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

            /* Allow any file type — use original extension */
            $origExt  = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
            $safeName = "txphoto_" . time() . "_" . bin2hex(random_bytes(4)) . ($origExt ? "." . $origExt : "");
            $destPath = $uploadDir . $safeName;

            if (move_uploaded_file($file["tmp_name"], $destPath)) {
                $transfer_photo = "uploads/transfer_photos/" . $safeName;
            } else {
                $error = json_encode(["lo" => "ບໍ່ສາມາດອັບໂຫຼດໄຟລ໌ໄດ້", "en" => "Failed to upload file."]);
            }
        }
    }

    if (!$error) {
        if ($amount <= 0) {
            $error = json_encode(["lo" => "ຈຳນວນເງີນຕ້ອງຫຼາຍກວ່າສູນ", "en" => "Amount must be greater than zero."]);
        } elseif ($request_type === "credit_to_cash" && $amount > $shop["credit_balance"]) {
            $error = json_encode(["lo" => "ຍອດເຄຣດິດບໍ່ພໍ", "en" => "Not enough credit balance."]);
        } else {
            $pdo->prepare("
                INSERT INTO credit_requests
                (partner_shop_id, request_type, amount, payment_method, reference_no, pay_ref, transfer_photo, note)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ")->execute([$shop["id"], $request_type, $amount, $payment_method, $reference_no, $pay_ref, $transfer_photo, $note]);

            $success = json_encode(["lo" => "ສົ່ງຄຳຮ້ອງສຳເລັດ", "en" => "Request submitted successfully."]);
        } /* end else */
    } /* end if (!$error) */
} /* end if POST */

/* Refresh shop */
$stmt = $pdo->prepare("SELECT * FROM partner_shops WHERE id = ? LIMIT 1");
$stmt->execute([$shop["id"]]);
$shop = $stmt->fetch(PDO::FETCH_ASSOC);

$stmt = $pdo->prepare("SELECT * FROM credit_requests WHERE partner_shop_id = ? ORDER BY id DESC");
$stmt->execute([$shop["id"]]);
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Credit Request</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700;800&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --primary:    #2563eb;
            --primary-dk: #1e3a5f;
            --green:      #16a34a;
            --green-lt:   #dcfce7;
            --red:        #dc2626;
            --red-lt:     #fee2e2;
            --amber:      #92400e;
            --amber-lt:   #fef3c7;
            --surface:    #fff;
            --bg:         #f0f4f8;
            --border:     #e2e8f0;
            --text:       #0f172a;
            --muted:      #64748b;
            --radius:     14px;
            --shadow:     0 2px 14px rgba(15,23,42,.09);
        }

        body {
            font-family: "Noto Sans Lao", "Inter", Arial, sans-serif;
            background: var(--bg);
            color: var(--text);
            padding: 24px 20px;
        }

        .container { max-width: 1100px; margin: auto; }

        /* ── Language bar ── */
        .lang-bar {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 6px;
            margin-bottom: 14px;
        }

        .lang-label { font-size: 12px; color: var(--muted); font-weight: 500; }

        .lang-btn {
            display: inline-flex; align-items: center; gap: 5px;
            padding: 5px 13px; border-radius: 999px;
            border: 1.5px solid var(--border);
            background: var(--surface);
            font-size: 12px; font-weight: 700; color: var(--muted);
            cursor: pointer; font-family: inherit;
            transition: border-color .15s, color .15s, background .15s;
        }

        .lang-btn:hover   { border-color: var(--primary); color: var(--primary); }
        .lang-btn.active  { background: var(--primary); border-color: var(--primary); color: #fff; }

        /* ── Balance header ── */
        .balance-header {
            background: linear-gradient(135deg, #0f2444 0%, #1e3a5f 55%, #1d4ed8 100%);
            border-radius: 18px;
            padding: 22px 28px;
            margin-bottom: 22px;
            color: #fff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 14px;
            box-shadow: 0 6px 24px rgba(15,23,42,.18);
        }

        .balance-header .shop-name  { font-size: 17px; font-weight: 700; margin-bottom: 4px; }
        .balance-header .bal-label  { font-size: 11px; font-weight: 600; color: rgba(255,255,255,.65); letter-spacing: .6px; text-transform: uppercase; }
        .balance-header .bal-amount { font-size: 32px; font-weight: 800; letter-spacing: -1px; }
        .balance-header .bal-amount .cur { font-size: 15px; font-weight: 600; color: rgba(255,255,255,.65); margin-right: 3px; }

        .back-btn {
            background: rgba(255,255,255,.14); border: 1.5px solid rgba(255,255,255,.3);
            color: #fff; padding: 8px 16px; border-radius: 10px;
            text-decoration: none; font-size: 13px; font-weight: 600;
            transition: background .15s;
        }
        .back-btn:hover { background: rgba(255,255,255,.24); }

        /* ── Card ── */
        .card {
            background: var(--surface);
            border-radius: var(--radius);
            padding: 28px;
            box-shadow: var(--shadow);
            border: 1px solid var(--border);
            margin-bottom: 22px;
        }

        .card h2 {
            font-size: 19px; font-weight: 700;
            color: var(--text); margin-bottom: 22px;
            display: flex; align-items: center; gap: 8px;
        }

        /* ── Form ── */
        .form-group { margin-bottom: 18px; }

        .form-group label {
            display: block; font-size: 12px; font-weight: 700;
            color: var(--muted); text-transform: uppercase;
            letter-spacing: .5px; margin-bottom: 7px;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 11px 14px;
            border: 1.5px solid var(--border);
            border-radius: 10px;
            font-size: 15px;
            font-family: inherit;
            color: var(--text);
            background: #fff;
            outline: none;
            transition: border-color .15s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus { border-color: var(--primary); }

        .form-group textarea { min-height: 90px; resize: vertical; }

        /* Amount field special styling */
        .amount-wrap { position: relative; }

        .amount-wrap .currency-prefix {
            position: absolute; left: 14px; top: 50%;
            transform: translateY(-50%);
            font-size: 16px; font-weight: 700; color: var(--muted);
            pointer-events: none;
        }

        .amount-wrap input {
            padding-left: 30px;
            font-size: 22px;
            font-weight: 800;
            color: var(--primary);
            letter-spacing: -.5px;
        }

        /* Quick chips */
        .amount-chips {
            display: flex; flex-wrap: wrap; gap: 7px; margin-top: 10px;
        }

        .chip {
            padding: 5px 13px; border-radius: 999px;
            border: 1.5px solid var(--border);
            background: var(--surface);
            font-size: 12px; font-weight: 700; color: var(--muted);
            cursor: pointer; font-family: inherit;
            transition: border-color .15s, color .15s, background .15s;
        }

        .chip:hover, .chip.active {
            border-color: var(--primary);
            color: var(--primary);
            background: #dbeafe;
        }

        /* Type cards */
        .type-cards {
            display: grid; grid-template-columns: 1fr 1fr; gap: 12px;
        }

        .type-card {
            border: 2px solid var(--border);
            border-radius: 12px; padding: 14px 16px;
            cursor: pointer; transition: border-color .15s, background .15s;
            display: flex; align-items: flex-start; gap: 10px;
        }

        .type-card input[type=radio] { margin-top: 3px; accent-color: var(--primary); }

        .type-card .tc-icon { font-size: 22px; flex-shrink: 0; }

        .type-card .tc-title { font-size: 14px; font-weight: 700; color: var(--text); }
        .type-card .tc-desc  { font-size: 12px; color: var(--muted); margin-top: 3px; line-height: 1.4; }

        .type-card:has(input:checked) {
            border-color: var(--primary);
            background: #eff6ff;
        }

        /* Action buttons */
        .action-row { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 6px; }

        .btn {
            padding: 12px 24px; border: none; border-radius: 10px;
            font-size: 14px; font-weight: 700; font-family: inherit;
            cursor: pointer; text-decoration: none;
            display: inline-flex; align-items: center; gap: 7px;
            transition: opacity .15s, transform .1s;
        }

        .btn:hover   { opacity: .88; transform: translateY(-1px); }
        .btn:active  { transform: translateY(0); }
        .btn-primary { background: var(--primary); color: #fff; }
        .btn-gray    { background: #e5e7eb; color: #374151; }

        /* Alerts */
        .alert {
            border-radius: 10px; padding: 13px 16px;
            font-size: 14px; font-weight: 600; margin-bottom: 18px;
        }

        .alert-success { background: var(--green-lt); color: #166534; border: 1px solid #86efac; }
        .alert-error   { background: var(--red-lt);   color: #991b1b; border: 1px solid #fca5a5; }

        /* ── Table ── */
        .table-wrapper { width: 100%; overflow-x: auto; }

        table { width: 100%; min-width: 720px; border-collapse: collapse; }

        th {
            background: #0f172a; color: #fff;
            text-align: left; padding: 12px 14px;
            font-size: 12px; font-weight: 700;
            text-transform: uppercase; letter-spacing: .5px;
        }

        td { padding: 12px 14px; border-bottom: 1px solid var(--border); font-size: 13px; vertical-align: middle; }
        tr:hover td { background: #f9fafb; }

        .amount-val { font-weight: 800; color: var(--primary); }

        .status-badge {
            padding: 4px 11px; border-radius: 999px;
            font-size: 12px; font-weight: 700; display: inline-block;
        }

        .pending  { background: var(--amber-lt); color: var(--amber); }
        .approved { background: var(--green-lt);  color: var(--green); }
        .rejected { background: var(--red-lt);    color: var(--red); }

        .type-badge {
            padding: 3px 10px; border-radius: 999px;
            font-size: 12px; font-weight: 700; display: inline-block;
        }

        .cash_to_credit { background: #dbeafe; color: #1d4ed8; }
        .credit_to_cash { background: #fce7f3; color: #9d174d; }

        .empty-row td { text-align: center; color: var(--muted); padding: 30px; font-style: italic; }

        /* ── Upload box ── */
        .upload-box {
            border: 2px dashed var(--border);
            border-radius: 12px;
            padding: 22px;
            text-align: center;
            cursor: pointer;
            transition: border-color .15s, background .15s;
            background: #fafbff;
        }

        .upload-box:hover {
            border-color: var(--primary);
            background: #eff6ff;
        }

        .upload-box.has-file {
            border-color: var(--green);
            background: #f0fdf4;
        }

        .upload-icon { font-size: 28px; margin-bottom: 6px; }
        .upload-text { font-size: 14px; font-weight: 600; color: var(--text); }
        .upload-hint { font-size: 12px; color: var(--muted); margin-top: 4px; }

        @media (max-width: 600px) {
            body { padding: 14px; }
            .type-cards { grid-template-columns: 1fr; }
            .balance-header { flex-direction: column; align-items: flex-start; }
        }
    </style>
</head>
<body>
<div class="container">

    <!-- Language bar -->
    <div class="lang-bar">
        <span class="lang-label">ພາສາ / Language:</span>
        <button class="lang-btn active" id="btn-lo" onclick="setLang('lo')">
            <span>🇱🇦</span> ລາວ
        </button>
        <button class="lang-btn" id="btn-en" onclick="setLang('en')">
            <span>🇬🇧</span> English
        </button>
    </div>

    <!-- Balance header -->
    <div class="balance-header">
        <div>
            <div class="shop-name"><?= htmlspecialchars($shop["shop_name"]) ?></div>
            <div class="bal-label"
                 data-lo="ຍອດເຄຣດິດທີ່ໃຊ້ໄດ້"
                 data-en="AVAILABLE CREDIT">ຍອດເຄຣດິດທີ່ໃຊ້ໄດ້</div>
            <div class="bal-amount">
                <span class="cur">₭</span><?= number_format($shop["credit_balance"], 2) ?>
            </div>
        </div>
        <a class="back-btn" href="dashboard.php">
            ← <span data-lo="ກັບຄືນ" data-en="Back">ກັບຄືນ</span>
        </a>
    </div>

    <!-- Alerts -->
    <?php if ($error): ?>
        <?php $e = json_decode($error, true); ?>
        <div class="alert alert-error">
            ⚠️ <span data-lo="<?= htmlspecialchars($e['lo']) ?>"
                      data-en="<?= htmlspecialchars($e['en']) ?>">
                <?= htmlspecialchars($e['lo']) ?>
            </span>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <?php $s = json_decode($success, true); ?>
        <div class="alert alert-success">
            ✅ <span data-lo="<?= htmlspecialchars($s['lo']) ?>"
                     data-en="<?= htmlspecialchars($s['en']) ?>">
                <?= htmlspecialchars($s['lo']) ?>
            </span>
        </div>
    <?php endif; ?>

    <!-- Form card -->
    <div class="card">
        <h2>
            📋 <span data-lo="ສ້າງຄຳຮ້ອງຂໍເຄຣດິດ" data-en="Create Credit Request">ສ້າງຄຳຮ້ອງຂໍເຄຣດິດ</span>
        </h2>

        <form method="POST" enctype="multipart/form-data" id="creditForm">
            <input type="hidden" name="amount" id="amountHidden">

            <!-- Request type -->
            <div class="form-group">
                <label data-lo="ປະເພດຄຳຮ້ອງ" data-en="REQUEST TYPE">ປະເພດຄຳຮ້ອງ</label>
                <div class="type-cards">
                    <label class="type-card">
                        <input type="radio" name="request_type" value="cash_to_credit" checked>
                        <div class="tc-icon">💵</div>
                        <div>
                            <div class="tc-title"
                                 data-lo="ເງິນສົດ / ໂອນ → ເຄຣດິດ"
                                 data-en="Cash / Bank → Credit">
                                ເງິນສົດ / ໂອນ → ເຄຣດິດ
                            </div>
                            <div class="tc-desc"
                                 data-lo="ຊຳລະແລ້ວ ຂໍຕື່ມເຄຣດິດ"
                                 data-en="Pay cash or transfer, request credit top-up.">
                                ຊຳລະແລ້ວ ຂໍຕື່ມເຄຣດິດ
                            </div>
                        </div>
                    </label>

                    <label class="type-card">
                        <input type="radio" name="request_type" value="credit_to_cash">
                        <div class="tc-icon">🏦</div>
                        <div>
                            <div class="tc-title"
                                 data-lo="ເຄຣດິດ → ເງິນສົດ"
                                 data-en="Credit → Cash">
                                ເຄຣດິດ → ເງິນສົດ
                            </div>
                            <div class="tc-desc"
                                 data-lo="ແລກເຄຣດິດຄືນເງິນສົດ"
                                 data-en="Exchange credit back to cash.">
                                ແລກເຄຣດິດຄືນເງິນສົດ
                            </div>
                        </div>
                    </label>
                </div>
            </div>

            <!-- Amount -->
            <div class="form-group">
                <label data-lo="ຈຳນວນເງີນ (₭)" data-en="AMOUNT (₭)">ຈຳນວນເງີນ (₭)</label>
                <div class="amount-wrap">
                    <span class="currency-prefix">₭</span>
                    <input type="text" id="amountDisplay"
                           placeholder="0"
                           autocomplete="off"
                           inputmode="numeric">
                </div>
                <div class="amount-chips">
                    <?php foreach ([10000,20000,50000,100000,200000,500000,1000000] as $v): ?>
                        <button type="button" class="chip"
                                onclick="setChip(<?= $v ?>, this)">
                            ₭<?= number_format($v) ?>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Payment method -->
            <div class="form-group">
                <label data-lo="ວິທີຊຳລະ" data-en="PAYMENT METHOD">ວິທີຊຳລະ</label>
                <select name="payment_method">
                    <option value="cash"          data-lo="ເງິນສົດ"         data-en="Cash">ເງິນສົດ</option>
                    <option value="bank_transfer"  data-lo="ໂອນຜ່ານທະນາຄານ" data-en="Bank Transfer">ໂອນຜ່ານທະນາຄານ</option>
                </select>
            </div>

            <!-- Reference -->
            <div class="form-group">
                <label data-lo="ເລກອ້າງອີງ" data-en="REFERENCE NO.">ເລກອ້າງອີງ</label>
                <input type="text" name="reference_no"
                       data-lo-placeholder="ເລກໂອນ / ເລກໃບຮັບ"
                       data-en-placeholder="Transfer / Receipt number"
                       placeholder="ເລກໂອນ / ເລກໃບຮັບ">
            </div>

            <!-- Pay Ref -->
            <div class="form-group">
                <label data-lo="ເລກອ້າງອີງການຈ່າຍ (Pay Ref)" data-en="PAYMENT REFERENCE (Pay Ref)">ເລກອ້າງອີງການຈ່າຍ (Pay Ref)</label>
                <input type="text" name="pay_ref"
                       data-lo-placeholder="ເລກ Pay Ref ຈາກທະນາຄານ / ແອັບ"
                       data-en-placeholder="Pay Ref from bank / payment app"
                       placeholder="ເລກ Pay Ref ຈາກທະນາຄານ / ແອັບ">
            </div>

            <!-- Transfer photo -->
            <div class="form-group">
                <label data-lo="ຮູບສະລິບການໂອນ / ຫຼັກຖານ" data-en="TRANSFER PROOF / PHOTO">ຮູບສະລິບການໂອນ / ຫຼັກຖານ</label>
                <div class="upload-box" id="uploadBox" onclick="document.getElementById('photoInput').click()">
                    <div class="upload-icon">📎</div>
                    <div class="upload-text">
                        <span data-lo="ຄລິກເພື່ອແນບໄຟລ໌ (ຮູບ, PDF, ທຸກປະເພດ)"
                              data-en="Click to attach file (image, PDF, any type)">
                            ຄລິກເພື່ອແນບໄຟລ໌ (ຮູບ, PDF, ທຸກປະເພດ)
                        </span>
                    </div>
                    <div class="upload-hint" id="uploadHint">
                        <span data-lo="ສູງສຸດ 10MB" data-en="Max 10MB">ສູງສຸດ 10MB</span>
                    </div>
                </div>
                <input type="file" name="transfer_photo" id="photoInput"
                       accept="*/*" style="display:none;"
                       onchange="previewFile(this)">

                <!-- Preview area -->
                <div id="previewArea" style="display:none;margin-top:12px;">
                    <img id="previewImg" src="" alt="preview"
                         style="max-width:100%;max-height:280px;border-radius:10px;
                                border:2px solid var(--border);display:none;">
                    <div id="previewFile"
                         style="display:none;background:#f8faff;border:1px solid var(--border);
                                border-radius:10px;padding:12px 16px;display:flex;
                                align-items:center;gap:10px;font-size:13px;">
                        <span style="font-size:24px;" id="previewFileIcon">📄</span>
                        <div>
                            <div id="previewFileName" style="font-weight:700;"></div>
                            <div id="previewFileSize" style="color:var(--muted);font-size:12px;"></div>
                        </div>
                        <button type="button"
                                onclick="clearFile()"
                                style="margin-left:auto;background:var(--red-lt);color:var(--red);
                                       border:1px solid #fca5a5;border-radius:6px;padding:4px 10px;
                                       cursor:pointer;font-size:12px;font-weight:700;font-family:inherit;">
                            ✕
                        </button>
                    </div>
                </div>
            </div>

            <!-- Note -->
            <div class="form-group">
                <label data-lo="ໝາຍເຫດ" data-en="NOTE">ໝາຍເຫດ</label>
                <textarea name="note"
                          data-lo-placeholder="ໝາຍເຫດເພີ່ມເຕີມ (ຖ້າມີ)"
                          data-en-placeholder="Additional note (optional)"
                          placeholder="ໝາຍເຫດເພີ່ມເຕີມ (ຖ້າມີ)"></textarea>
            </div>

            <div class="action-row">
                <button type="submit" class="btn btn-primary">
                    📤 <span data-lo="ສົ່ງຄຳຮ້ອງ" data-en="Submit Request">ສົ່ງຄຳຮ້ອງ</span>
                </button>
                <a class="btn btn-gray" href="dashboard.php">
                    ← <span data-lo="ກັບຄືນ" data-en="Back">ກັບຄືນ</span>
                </a>
            </div>
        </form>
    </div>

    <!-- History card -->
    <div class="card">
        <h2>
            🗂️ <span data-lo="ປະຫວັດຄຳຮ້ອງ" data-en="My Credit Requests">ປະຫວັດຄຳຮ້ອງ</span>
        </h2>

        <div class="table-wrapper">
            <table>
                <tr>
                    <th>#</th>
                    <th><span data-lo="ປະເພດ"     data-en="Type">ປະເພດ</span></th>
                    <th><span data-lo="ຈຳນວນ"     data-en="Amount">ຈຳນວນ</span></th>
                    <th><span data-lo="ວິທີຊຳລະ"  data-en="Method">ວິທີຊຳລະ</span></th>
                    <th><span data-lo="ອ້າງອີງ"   data-en="Reference">ອ້າງອີງ</span></th>
                    <th><span data-lo="ຫຼັກຖານ"   data-en="Proof">ຫຼັກຖານ</span></th>
                    <th><span data-lo="ສະຖານະ"    data-en="Status">ສະຖານະ</span></th>
                    <th><span data-lo="ວັນທີ"     data-en="Date">ວັນທີ</span></th>
                </tr>

                <?php if (empty($requests)): ?>
                    <tr class="empty-row">
                        <td colspan="8">
                            <span data-lo="ຍັງບໍ່ມີຄຳຮ້ອງ" data-en="No requests yet.">ຍັງບໍ່ມີຄຳຮ້ອງ</span>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($requests as $i => $row): ?>
                        <tr>
                            <td><?= $i + 1 ?></td>
                            <td>
                                <span class="type-badge <?= htmlspecialchars($row["request_type"]) ?>">
                                    <?php
                                    $typeMap = [
                                        "cash_to_credit" => ["lo" => "ເງິນ → ເຄຣດິດ", "en" => "Cash → Credit"],
                                        "credit_to_cash" => ["lo" => "ເຄຣດິດ → ເງິນ", "en" => "Credit → Cash"],
                                    ];
                                    $t = $typeMap[$row["request_type"]] ?? ["lo" => $row["request_type"], "en" => $row["request_type"]];
                                    ?>
                                    <span data-lo="<?= htmlspecialchars($t['lo']) ?>"
                                          data-en="<?= htmlspecialchars($t['en']) ?>">
                                        <?= htmlspecialchars($t['lo']) ?>
                                    </span>
                                </span>
                            </td>
                            <td class="amount-val">₭<?= number_format($row["amount"], 2) ?></td>
                            <td>
                                <?php
                                $methodMap = [
                                    "cash"          => ["lo" => "ເງິນສົດ",      "en" => "Cash"],
                                    "bank_transfer" => ["lo" => "ໂອນທະນາຄານ", "en" => "Bank Transfer"],
                                ];
                                $m = $methodMap[$row["payment_method"]] ?? ["lo" => $row["payment_method"], "en" => $row["payment_method"]];
                                ?>
                                <span data-lo="<?= htmlspecialchars($m['lo']) ?>"
                                      data-en="<?= htmlspecialchars($m['en']) ?>">
                                    <?= htmlspecialchars($m['lo']) ?>
                                </span>
                            </td>
                            <td style="color:var(--muted);font-size:12px;">
                                <?= htmlspecialchars($row["reference_no"] ?: "—") ?>
                            </td>

                            <!-- ── Proof photo + file size ── -->
                            <td>
                                <?php if (!empty($row["transfer_photo"])): ?>
                                    <?php
                                    $photoPath = "../" . $row["transfer_photo"];
                                    $absPath   = __DIR__ . "/../" . $row["transfer_photo"];
                                    $ext       = strtolower(pathinfo($row["transfer_photo"], PATHINFO_EXTENSION));
                                    $isImg     = in_array($ext, ["jpg","jpeg","png","gif","webp","bmp","svg"]);
                                    $fileBytes = file_exists($absPath) ? filesize($absPath) : 0;
                                    $fileLabel = $fileBytes >= 1048576
                                        ? number_format($fileBytes / 1048576, 1) . " MB"
                                        : number_format($fileBytes / 1024, 0) . " KB";
                                    ?>
                                    <?php if ($isImg): ?>
                                        <div style="display:inline-flex;flex-direction:column;align-items:center;gap:4px;">
                                            <img src="<?= htmlspecialchars($photoPath) ?>"
                                                 alt="proof"
                                                 onclick="openPartnerLightbox('<?= htmlspecialchars($photoPath) ?>')"
                                                 style="width:52px;height:52px;object-fit:cover;
                                                        border-radius:8px;border:2px solid var(--border);
                                                        cursor:zoom-in;transition:transform .15s;"
                                                 onmouseover="this.style.transform='scale(1.08)'"
                                                 onmouseout="this.style.transform='scale(1)'">
                                            <span style="font-size:10px;color:var(--muted);font-weight:600;">
                                                <?= $fileLabel ?>
                                            </span>
                                        </div>
                                    <?php else: ?>
                                        <div style="display:inline-flex;flex-direction:column;align-items:center;gap:4px;">
                                            <a href="<?= htmlspecialchars($photoPath) ?>" target="_blank"
                                               style="background:#f0f5ff;border:1px solid var(--border);
                                                      border-radius:8px;padding:5px 10px;font-size:12px;
                                                      font-weight:700;color:var(--primary);text-decoration:none;
                                                      display:inline-block;">
                                                📎 <?= strtoupper($ext) ?>
                                            </a>
                                            <span style="font-size:10px;color:var(--muted);font-weight:600;">
                                                <?= $fileLabel ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span style="color:var(--muted);font-size:12px;">—</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?php
                                $statusMap = [
                                    "pending"  => ["lo" => "ລໍຖ້າ",       "en" => "Pending"],
                                    "approved" => ["lo" => "ອະນຸມັດແລ້ວ", "en" => "Approved"],
                                    "rejected" => ["lo" => "ປະຕິເສດ",     "en" => "Rejected"],
                                ];
                                $st = $statusMap[$row["status"]] ?? ["lo" => $row["status"], "en" => $row["status"]];
                                ?>
                                <span class="status-badge <?= htmlspecialchars($row["status"]) ?>">
                                    <span data-lo="<?= htmlspecialchars($st['lo']) ?>"
                                          data-en="<?= htmlspecialchars($st['en']) ?>">
                                        <?= htmlspecialchars($st['lo']) ?>
                                    </span>
                                </span>
                            </td>
                            <td style="white-space:nowrap;color:var(--muted);font-size:12px;">
                                <?= htmlspecialchars($row["created_at"]) ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </table>
        </div>
    </div>

</div><!-- /container -->

<!-- Shared lang.js content inlined — copy this block to any future page -->
<script>
/* ════════════════════════════════════════
   LANGUAGE SWITCHER  (reusable snippet)
   Copy this <script> block to any page.
   Tag elements with data-lo="..." data-en="..."
   For inputs/textareas also add:
       data-lo-placeholder="..." data-en-placeholder="..."
   For <select> options also add data-lo / data-en.
════════════════════════════════════════ */
function setLang(lang) {
    localStorage.setItem("lang", lang);
    applyLang(lang);
}

function applyLang(lang) {
    /* Toggle buttons */
    const btnLo = document.getElementById("btn-lo");
    const btnEn = document.getElementById("btn-en");
    if (btnLo) btnLo.classList.toggle("active", lang === "lo");
    if (btnEn) btnEn.classList.toggle("active", lang === "en");

    /* Swap text content */
    document.querySelectorAll("[data-lo][data-en]").forEach(el => {
        const val = el.dataset[lang];
        if (val !== undefined) el.innerHTML = val;
    });

    /* Swap placeholders */
    document.querySelectorAll("[data-lo-placeholder][data-en-placeholder]").forEach(el => {
        el.placeholder = lang === "lo" ? el.dataset.loPlaceholder : el.dataset.enPlaceholder;
    });

    /* Swap <option> text */
    document.querySelectorAll("option[data-lo][data-en]").forEach(opt => {
        opt.textContent = opt.dataset[lang] || opt.textContent;
    });

    window._lang = lang;
}

(function () {
    const saved = localStorage.getItem("lang") || "lo";
    applyLang(saved);
})();

/* ════════════════════════════════════════
   AMOUNT INPUT with comma formatting
════════════════════════════════════════ */
const amountDisplay = document.getElementById("amountDisplay");
const amountHidden  = document.getElementById("amountHidden");

amountDisplay.addEventListener("input", function () {
    let raw = this.value.replace(/,/g, "").replace(/[^\d]/g, "");
    this.value = raw ? Number(raw).toLocaleString("en-US") : "";
    /* Remove active chip highlight when typing manually */
    document.querySelectorAll(".chip").forEach(c => c.classList.remove("active"));
});

function setChip(val, el) {
    amountDisplay.value = val.toLocaleString("en-US");
    document.querySelectorAll(".chip").forEach(c => c.classList.remove("active"));
    el.classList.add("active");
}

function prepareSubmit() {
    const raw = parseFloat(amountDisplay.value.replace(/,/g, "")) || 0;
    amountHidden.value = raw;
}

/* ── File preview + client-side image compression ── */
const IMAGE_TYPES = ["jpg","jpeg","png","gif","webp","bmp","svg"];

/* Compression settings */
const MAX_WIDTH   = 1200;   /* px — resize if wider than this */
const MAX_HEIGHT  = 1200;   /* px */
const JPEG_QUALITY = 0.75;  /* 0-1, 0.75 = good quality, ~70-80% smaller */

/* Store compressed blob so the form submits it instead of the original */
let compressedBlob = null;
let compressedName = null;

function previewFile(input) {
    const file = input.files[0];
    if (!file) return;

    const ext     = file.name.split(".").pop().toLowerCase();
    const isImage = IMAGE_TYPES.includes(ext) && ext !== "svg";

    const box      = document.getElementById("uploadBox");
    const area     = document.getElementById("previewArea");
    const img      = document.getElementById("previewImg");
    const fileDiv  = document.getElementById("previewFile");
    const fileName = document.getElementById("previewFileName");
    const fileSize = document.getElementById("previewFileSize");
    const fileIcon = document.getElementById("previewFileIcon");
    const hint     = document.getElementById("uploadHint");

    box.classList.add("has-file");
    area.style.display = "block";
    compressedBlob = null;
    compressedName = null;

    if (isImage) {
        hint.textContent = "⏳ ກຳລັງບີບອັດຮູບ… / Compressing…";
        img.style.display    = "block";
        fileDiv.style.display = "none";

        const reader = new FileReader();
        reader.onload = function(e) {
            const originalSrc = e.target.result;

            /* Show original preview immediately */
            img.src = originalSrc;

            /* Compress via canvas */
            const image = new Image();
            image.onload = function() {
                let w = image.width;
                let h = image.height;

                /* Scale down if too large */
                if (w > MAX_WIDTH || h > MAX_HEIGHT) {
                    const ratio = Math.min(MAX_WIDTH / w, MAX_HEIGHT / h);
                    w = Math.round(w * ratio);
                    h = Math.round(h * ratio);
                }

                const canvas = document.createElement("canvas");
                canvas.width  = w;
                canvas.height = h;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(image, 0, 0, w, h);

                canvas.toBlob(function(blob) {
                    compressedBlob = blob;
                    compressedName = file.name.replace(/\.[^.]+$/, "") + "_compressed.jpg";

                    /* Show compressed preview */
                    const compressedUrl = URL.createObjectURL(blob);
                    img.src = compressedUrl;

                    const origKB  = (file.size / 1024).toFixed(0);
                    const newKB   = (blob.size / 1024).toFixed(0);
                    const saved   = Math.round((1 - blob.size / file.size) * 100);

                    hint.innerHTML = `✅ ${compressedName} &nbsp;·&nbsp;
                        <span style="color:#16a34a;font-weight:700;">
                            ${newKB}KB
                            <span style="color:#64748b;font-weight:400;">
                                (ຫຼຸດຈາກ / was ${origKB}KB, ລົດ ${saved}%)
                            </span>
                        </span>`;
                }, "image/jpeg", JPEG_QUALITY);
            };
            image.src = originalSrc;
        };
        reader.readAsDataURL(file);

    } else {
        /* Non-image file — no compression, just show info */
        img.style.display    = "none";
        fileDiv.style.display = "flex";
        const icons = { pdf:"📄", doc:"📝", docx:"📝", xls:"📊", xlsx:"📊", zip:"🗜️", rar:"🗜️" };
        fileIcon.textContent = icons[ext] || "📎";
        fileName.textContent = file.name;
        fileSize.textContent = (file.size / 1024 / 1024).toFixed(2) + " MB";
        hint.textContent     = "✅ " + file.name;
    }
}

function clearFile() {
    document.getElementById("photoInput").value = "";
    compressedBlob = null;
    compressedName = null;
    document.getElementById("uploadBox").classList.remove("has-file");
    document.getElementById("uploadHint").innerHTML =
        '<span data-lo="ສູງສຸດ 10MB" data-en="Max 10MB">ສູງສຸດ 10MB</span>';
    document.getElementById("previewArea").style.display = "none";
    document.getElementById("previewImg").src = "";
    /* re-apply lang to the restored span */
    if (window._lang) applyLang(window._lang);
}

/* ── Override form submit to swap in compressed blob if available ── */
document.getElementById("creditForm").addEventListener("submit", function(e) {
    /* Always sync the amount hidden field */
    prepareSubmit();

    /* If we have a compressed image, inject it into the form via DataTransfer */
    if (compressedBlob && compressedName) {
        try {
            const dt   = new DataTransfer();
            const file = new File([compressedBlob], compressedName, { type: "image/jpeg" });
            dt.items.add(file);
            document.getElementById("photoInput").files = dt.files;
        } catch (err) {
            /* DataTransfer not supported (very old browsers) — submit original */
            console.warn("DataTransfer not supported, submitting original file.", err);
        }
    }
});
</script>

<!-- Partner lightbox -->
<div id="partnerLightbox"
     onclick="closePartnerLightbox()"
     style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.85);
            z-index:9999;align-items:center;justify-content:center;padding:20px;">
    <div style="position:relative;max-width:90vw;max-height:90vh;text-align:center;">
        <img id="partnerLightboxImg" src="" alt="proof"
             style="max-width:100%;max-height:82vh;border-radius:12px;
                    box-shadow:0 20px 60px rgba(0,0,0,.5);display:block;">
        <div id="partnerLightboxInfo"
             style="color:#fff;font-size:12px;margin-top:10px;opacity:.8;"></div>
        <button onclick="closePartnerLightbox()"
                style="position:absolute;top:-14px;right:-14px;width:32px;height:32px;
                       border-radius:50%;background:#fff;border:none;font-size:16px;
                       cursor:pointer;font-weight:700;color:#111;
                       box-shadow:0 2px 8px rgba(0,0,0,.3);">✕</button>
    </div>
</div>

<script>
function openPartnerLightbox(src) {
    const lb  = document.getElementById("partnerLightbox");
    const img = document.getElementById("partnerLightboxImg");
    const info = document.getElementById("partnerLightboxInfo");
    img.src = src;
    lb.style.display = "flex";
    document.body.style.overflow = "hidden";

    /* Show file size once image loads */
    img.onload = function() {
        info.textContent = img.naturalWidth + " × " + img.naturalHeight + " px";
    };
}

function closePartnerLightbox() {
    document.getElementById("partnerLightbox").style.display = "none";
    document.body.style.overflow = "";
}

document.addEventListener("keydown", function(e) {
    if (e.key === "Escape") closePartnerLightbox();
});
</script>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>