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

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

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

/* ── Ensure transaction_type ENUM includes notification values ──
   MySQL ENUM will truncate/warn on unknown values.
   We ALTER the column to add our new types if they aren't already there.
*/
try {
    $enumRow = $pdo->query("
        SELECT COLUMN_TYPE
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME   = 'transactions'
          AND COLUMN_NAME  = 'transaction_type'
    ")->fetch(PDO::FETCH_ASSOC);

    if ($enumRow) {
        $enumDef = $enumRow["COLUMN_TYPE"];
        $needed  = ["credit_request_approved", "credit_request_rejected"];
        $missing = [];

        foreach ($needed as $val) {
            if (strpos($enumDef, "'$val'") === false) {
                $missing[] = $val;
            }
        }

        if ($missing) {
            preg_match_all("/'([^']+)'/", $enumDef, $m);
            $existing = $m[1];
            $all      = array_merge($existing, $missing);
            $newEnum  = "ENUM(" . implode(",", array_map(fn($v) => "'$v'", $all)) . ")";
            $pdo->exec("ALTER TABLE transactions MODIFY COLUMN transaction_type $newEnum");
        }
    }
} catch (Throwable $e) { /* non-fatal */ }

/* ── Fix remarks column charset to support Lao / UTF-8 ──
   Run once — safe to call every time, ALTER is skipped if already utf8mb4.
*/
try {
    $colRow = $pdo->query("
        SELECT CHARACTER_SET_NAME, COLLATION_NAME, COLUMN_TYPE
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME   = 'transactions'
          AND COLUMN_NAME  = 'remarks'
    ")->fetch(PDO::FETCH_ASSOC);

    if ($colRow && strtolower($colRow["CHARACTER_SET_NAME"]) !== "utf8mb4") {
        $colType = $colRow["COLUMN_TYPE"]; /* e.g. varchar(255) or text */
        $pdo->exec("
            ALTER TABLE transactions
            MODIFY COLUMN remarks {$colType}
            CHARACTER SET utf8mb4
            COLLATE utf8mb4_unicode_ci
        ");
    }
} catch (Throwable $e) { /* non-fatal — may lack ALTER permission */ }

if (isset($_GET["action"], $_GET["id"])) {
    $id     = intval($_GET["id"]);
    $action = $_GET["action"];

    $stmt = $pdo->prepare("
        SELECT cr.*, ps.shop_name, ps.credit_balance
        FROM credit_requests cr
        JOIN partner_shops ps ON cr.partner_shop_id = ps.id
        WHERE cr.id = ? AND cr.status = 'pending'
        LIMIT 1
    ");
    $stmt->execute([$id]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$request) {
        $error = json_encode(["lo" => "ບໍ່ພົບຄຳຮ້ອງ ຫຼື ດຳເນີນການແລ້ວ", "en" => "Request not found or already processed."]);
    } elseif ($action === "reject") {
        $pdo->prepare("UPDATE credit_requests SET status='rejected', approved_at=NOW() WHERE id=?")
            ->execute([$id]);

        /* ── Notify partner: request was rejected ── */
        try {
            $pdo->prepare("
                INSERT INTO transactions
                (from_type, from_id, to_type, to_id, amount,
                 transaction_type, remarks, partner_read_at, created_at)
                VALUES
                ('admin', ?, 'partner', ?, ?,
                 'credit_request_rejected',
                 'Your credit request was rejected.',
                 NULL, NOW())
            ")->execute([$_SESSION["user_id"], $request["partner_shop_id"], $request["amount"]]);
        } catch (Throwable $e) { /* non-fatal */ }

        $success = json_encode(["lo" => "ປະຕິເສດຄຳຮ້ອງສຳເລັດ", "en" => "Request rejected."]);

    } elseif ($action === "approve") {
        try {
            $pdo->beginTransaction();

            if ($request["request_type"] === "cash_to_credit") {
                $pdo->prepare("UPDATE partner_shops SET credit_balance = credit_balance + ? WHERE id = ?")
                    ->execute([$request["amount"], $request["partner_shop_id"]]);
            }

            if ($request["request_type"] === "credit_to_cash") {
                if ($request["amount"] > $request["credit_balance"]) {
                    throw new Exception("Partner does not have enough credit.");
                }
                $pdo->prepare("UPDATE partner_shops SET credit_balance = credit_balance - ? WHERE id = ?")
                    ->execute([$request["amount"], $request["partner_shop_id"]]);
            }

            $tx_code = "TRX" . time();
            $type    = $request["request_type"] === "cash_to_credit" ? "cash_to_credit" : "credit_to_cash";
            $remark  = $type === "cash_to_credit"
                     ? "Partner paid cash/bank transfer to buy credit"
                     : "Partner exchanged credit to cash";

            /* Main transaction record */
            $pdo->prepare("INSERT INTO transactions
                (transaction_code, from_type, from_id, to_type, to_id, amount, transaction_type, remarks)
                VALUES (?, 'partner', ?, 'admin', ?, ?, ?, ?)")
                ->execute([$tx_code, $request["partner_shop_id"], $_SESSION["user_id"], $request["amount"], $type, $remark]);

            /* ── Partner notification row ──
               Same structure as customer→partner payments so the existing
               dashboard polling (check_new_payments.php) picks it up.
               from_type = 'admin'  (the approver)
               to_type   = 'partner'
               partner_read_at = NULL  → unread
            */
            $notif_remark = $type === "cash_to_credit"
                ? "Credit request approved. +" . number_format($request["amount"], 2)
                : "Credit-to-cash request approved. -" . number_format($request["amount"], 2);

            $pdo->prepare("
                INSERT INTO transactions
                (from_type, from_id, to_type, to_id, amount,
                 transaction_type, remarks, partner_read_at, created_at)
                VALUES
                ('admin', ?, 'partner', ?, ?,
                 'credit_request_approved',
                 ?, NULL, NOW())
            ")->execute([
                $_SESSION["user_id"],
                $request["partner_shop_id"],
                $request["amount"],
                $notif_remark
            ]);

            $pdo->prepare("UPDATE credit_requests SET status='approved', approved_at=NOW() WHERE id=?")
                ->execute([$id]);

            $pdo->commit();
            $success = json_encode(["lo" => "ອະນຸມັດຄຳຮ້ອງສຳເລັດ", "en" => "Request approved successfully."]);
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = json_encode(["lo" => $e->getMessage(), "en" => $e->getMessage()]);
        }
    }
}

/* ── Filters ── */
$filterStatus  = $_GET["status"]  ?? "";
$filterType    = $_GET["type"]    ?? "";
$filterFrom    = $_GET["from"]    ?? "";
$filterTo      = $_GET["to"]      ?? "";

$where  = [];
$params = [];

if ($filterStatus !== "") { $where[] = "cr.status = ?";              $params[] = $filterStatus; }
if ($filterType   !== "") { $where[] = "cr.request_type = ?";        $params[] = $filterType; }
if ($filterFrom   !== "") { $where[] = "DATE(cr.created_at) >= ?";   $params[] = $filterFrom; }
if ($filterTo     !== "") { $where[] = "DATE(cr.created_at) <= ?";   $params[] = $filterTo; }

$whereSQL = $where ? "WHERE " . implode(" AND ", $where) : "";

$requests = $pdo->prepare("
    SELECT cr.*, ps.shop_name, ps.shop_code
    FROM credit_requests cr
    JOIN partner_shops ps ON cr.partner_shop_id = ps.id
    {$whereSQL}
    ORDER BY cr.id DESC
");
$requests->execute($params);
$requests = $requests->fetchAll(PDO::FETCH_ASSOC);

/* Counts for summary */
$counts = $pdo->query("SELECT status, COUNT(*) as c FROM credit_requests GROUP BY status")
              ->fetchAll(PDO::FETCH_ASSOC);
$countMap = ["pending" => 0, "approved" => 0, "rejected" => 0];
foreach ($counts as $c) $countMap[$c["status"]] = (int)$c["c"];
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Credit Requests</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">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="../assets/lang.js" defer></script>
    <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:     #d97706;
            --amber-lt:  #fef3c7;
            --surface:   #ffffff;
            --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; min-height: 100vh;
        }

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

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

        .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; }

        /* ── Header ── */
        .page-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);
        }

        .page-header h1 { font-size: 22px; font-weight: 800; }
        .page-header p  { font-size: 13px; color: rgba(255,255,255,.7); margin-top: 4px; }

        .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; white-space: nowrap;
        }
        .back-btn:hover { background: rgba(255,255,255,.24); }

        /* ── Summary boxes ── */
        .summary-row {
            display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap;
        }

        .summary-box {
            flex: 1; min-width: 140px; border-radius: 12px;
            padding: 14px 18px; text-align: center;
            border: 1px solid var(--border); cursor: pointer;
            text-decoration: none; transition: transform .15s, box-shadow .15s;
        }

        .summary-box:hover { transform: translateY(-2px); box-shadow: var(--shadow); }

        .summary-box .s-val { font-size: 28px; font-weight: 800; line-height: 1; }
        .summary-box .s-lbl { font-size: 12px; font-weight: 600; margin-top: 4px; text-transform: uppercase; letter-spacing: .4px; }

        .s-all     { background: #f0f5ff; }
        .s-all     .s-val { color: var(--primary-dk); }
        .s-pending { background: var(--amber-lt); }
        .s-pending .s-val { color: var(--amber); }
        .s-approved{ background: var(--green-lt); }
        .s-approved .s-val { color: var(--green); }
        .s-rejected{ background: var(--red-lt); }
        .s-rejected .s-val { color: var(--red); }

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

        /* ── 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; }

        /* ── Filter bar ── */
        .filter-bar {
            display: flex; flex-wrap: wrap; gap: 10px;
            align-items: flex-end; background: #f8faff;
            border: 1px solid var(--border); border-radius: 10px;
            padding: 14px 18px; margin-bottom: 18px;
        }

        .filter-group { display: flex; flex-direction: column; gap: 4px; min-width: 150px; }

        .filter-group label {
            font-size: 11px; font-weight: 700; color: var(--muted);
            text-transform: uppercase; letter-spacing: .5px;
        }

        .filter-group select,
        .filter-group input {
            padding: 8px 10px; border: 1px solid var(--border);
            border-radius: 7px; font-size: 13px;
            background: #fff; font-family: inherit;
        }

        .filter-actions { display: flex; gap: 8px; align-items: flex-end; padding-bottom: 1px; }

        .btn {
            padding: 8px 16px; border: none; border-radius: 8px;
            font-size: 13px; font-weight: 700; font-family: inherit;
            cursor: pointer; text-decoration: none; display: inline-flex;
            align-items: center; gap: 5px;
            transition: opacity .15s, transform .1s;
        }
        .btn:hover  { opacity: .88; transform: translateY(-1px); }
        .btn:active { transform: translateY(0); }

        .btn-filter  { background: var(--primary-dk); color: #fff; }
        .btn-clear   { background: #e5e7eb; color: #374151; }
        .btn-approve { background: var(--green); color: #fff; }
        .btn-reject  { background: var(--red);   color: #fff; }
        .btn-gray    { background: #6b7280; color: #fff; }

        /* ── Filter notice ── */
        .filter-notice {
            background: var(--amber-lt); border: 1px solid #fcd34d;
            border-radius: 8px; padding: 8px 14px;
            font-size: 13px; color: #78350f;
            margin-bottom: 14px; display: flex; align-items: center;
            gap: 8px; flex-wrap: wrap;
        }

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

        table { width: 100%; min-width: 1000px; 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: .4px; white-space: nowrap;
        }

        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-cell { text-align: center; color: var(--muted); padding: 40px; font-style: italic; }

        .note-cell { font-size: 12px; color: var(--muted); max-width: 160px; word-break: break-word; }

        /* Pending row highlight */
        tr.row-pending td { background: #fffbeb; }
        tr.row-pending:hover td { background: #fef9c3; }

        @media (max-width: 700px) {
            body { padding: 14px; }
            .page-header { flex-direction: column; align-items: flex-start; }
            .summary-row { flex-direction: column; }
        }
    </style>
</head>
<body>
<div class="container">

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

    <!-- Header -->
    <div class="page-header">
        <div>
            <h1 data-lo="ຄຳຮ້ອງຂໍເຄຣດິດ" data-en="Credit Requests">ຄຳຮ້ອງຂໍເຄຣດິດ</h1>
            <p  data-lo="ອະນຸມັດ ຫຼື ປະຕິເສດຄຳຮ້ອງຂໍເຄຣດິດຂອງ Partner"
                data-en="Approve or reject partner cash and credit exchange requests.">
                ອະນຸມັດ ຫຼື ປະຕິເສດຄຳຮ້ອງຂໍເຄຣດິດຂອງ Partner
            </p>
        </div>
        <a class="back-btn" href="dashboard.php">
            ← <span data-lo="ກັບຄືນ Dashboard" data-en="Back to Dashboard">ກັບຄືນ Dashboard</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; ?>

    <!-- Summary boxes (click to filter) -->
    <div class="summary-row">
        <a class="summary-box s-all" href="credit_requests.php">
            <div class="s-val"><?= $countMap["pending"] + $countMap["approved"] + $countMap["rejected"] ?></div>
            <div class="s-lbl" data-lo="ທັງໝົດ" data-en="All">ທັງໝົດ</div>
        </a>
        <a class="summary-box s-pending" href="?status=pending">
            <div class="s-val"><?= $countMap["pending"] ?></div>
            <div class="s-lbl" data-lo="ລໍຖ້າ" data-en="Pending">ລໍຖ້າ</div>
        </a>
        <a class="summary-box s-approved" href="?status=approved">
            <div class="s-val"><?= $countMap["approved"] ?></div>
            <div class="s-lbl" data-lo="ອະນຸມັດ" data-en="Approved">ອະນຸມັດ</div>
        </a>
        <a class="summary-box s-rejected" href="?status=rejected">
            <div class="s-val"><?= $countMap["rejected"] ?></div>
            <div class="s-lbl" data-lo="ປະຕິເສດ" data-en="Rejected">ປະຕິເສດ</div>
        </a>
    </div>

    <!-- Card -->
    <div class="card">

        <!-- Filter bar -->
        <form method="GET" action="">
            <div class="filter-bar">

                <div class="filter-group">
                    <label data-lo="ສະຖານະ" data-en="STATUS">ສະຖານະ</label>
                    <select name="status">
                        <option value="" data-lo="— ທຸກສະຖານະ —" data-en="— All Status —">— ທຸກສະຖານະ —</option>
                        <option value="pending"  <?= $filterStatus==="pending"  ? "selected":"" ?>
                                data-lo="ລໍຖ້າ"      data-en="Pending">ລໍຖ້າ</option>
                        <option value="approved" <?= $filterStatus==="approved" ? "selected":"" ?>
                                data-lo="ອະນຸມັດ"   data-en="Approved">ອະນຸມັດ</option>
                        <option value="rejected" <?= $filterStatus==="rejected" ? "selected":"" ?>
                                data-lo="ປະຕິເສດ"   data-en="Rejected">ປະຕິເສດ</option>
                    </select>
                </div>

                <div class="filter-group">
                    <label data-lo="ປະເພດ" data-en="TYPE">ປະເພດ</label>
                    <select name="type">
                        <option value="" data-lo="— ທຸກປະເພດ —" data-en="— All Types —">— ທຸກປະເພດ —</option>
                        <option value="cash_to_credit" <?= $filterType==="cash_to_credit" ? "selected":"" ?>
                                data-lo="ເງິນ → ເຄຣດິດ" data-en="Cash → Credit">ເງິນ → ເຄຣດິດ</option>
                        <option value="credit_to_cash" <?= $filterType==="credit_to_cash" ? "selected":"" ?>
                                data-lo="ເຄຣດິດ → ເງິນ" data-en="Credit → Cash">ເຄຣດິດ → ເງິນ</option>
                    </select>
                </div>

                <div class="filter-group">
                    <label data-lo="ຈາກວັນທີ" data-en="FROM DATE">ຈາກວັນທີ</label>
                    <input type="text" name="from" id="from-date"
                           placeholder="Select date…"
                           value="<?= htmlspecialchars($filterFrom) ?>" readonly>
                </div>

                <div class="filter-group">
                    <label data-lo="ເຖິງວັນທີ" data-en="TO DATE">ເຖິງວັນທີ</label>
                    <input type="text" name="to" id="to-date"
                           placeholder="Select date…"
                           value="<?= htmlspecialchars($filterTo) ?>" readonly>
                </div>

                <div class="filter-actions">
                    <button class="btn btn-filter" type="submit">
                        🔍 <span data-lo="ຄົ້ນຫາ" data-en="Filter">ຄົ້ນຫາ</span>
                    </button>
                    <a class="btn btn-clear" href="credit_requests.php">
                        <span data-lo="ລ້າງ" data-en="Clear">ລ້າງ</span>
                    </a>
                </div>

            </div>
        </form>

        <!-- Active filter notice -->
        <?php if ($filterStatus || $filterType || $filterFrom || $filterTo): ?>
            <div class="filter-notice">
                🔎
                <?php if ($filterStatus): ?>
                    <strong><?= htmlspecialchars(ucfirst($filterStatus)) ?></strong>
                <?php endif; ?>
                <?php if ($filterType): ?>
                    | <?= htmlspecialchars(str_replace("_"," ",$filterType)) ?>
                <?php endif; ?>
                <?php if ($filterFrom || $filterTo): ?>
                    | <?= htmlspecialchars($filterFrom ?: "—") ?> →
                      <?= htmlspecialchars($filterTo   ?: "—") ?>
                <?php endif; ?>
                &nbsp;·&nbsp; <?= count($requests) ?>
                <span data-lo="ລາຍການ" data-en="records">ລາຍການ</span>
                <a href="credit_requests.php"
                   style="margin-left:auto;color:#92400e;font-weight:700;text-decoration:none;">
                    ✕ <span data-lo="ລ້າງ" data-en="Clear">ລ້າງ</span>
                </a>
            </div>
        <?php endif; ?>

        <!-- Table -->
        <div class="table-wrapper">
            <table>
                <tr>
                    <th>#</th>
                    <th><span data-lo="ຮ້ານຄ້າ"      data-en="Shop">ຮ້ານຄ້າ</span></th>
                    <th><span data-lo="ລະຫັດຮ້ານ"    data-en="Code">ລະຫັດຮ້ານ</span></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="Pay Ref"         data-en="Pay Ref">Pay Ref</span></th>
                    <th><span data-lo="ຫຼັກຖານ"        data-en="Proof">ຫຼັກຖານ</span></th>
                    <th><span data-lo="ໝາຍເຫດ"        data-en="Note">ໝາຍເຫດ</span></th>
                    <th><span data-lo="ສະຖານະ"        data-en="Status">ສະຖານະ</span></th>
                    <th><span data-lo="ວັນທີ"          data-en="Date">ວັນທີ</span></th>
                    <th><span data-lo="ດຳເນີນການ"     data-en="Action">ດຳເນີນການ</span></th>
                </tr>

                <?php if (empty($requests)): ?>
                    <tr>
                        <td colspan="11" class="empty-cell">
                            <span data-lo="ບໍ່ມີຄຳຮ້ອງ" data-en="No credit requests found.">ບໍ່ມີຄຳຮ້ອງ</span>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($requests as $i => $row): ?>
                        <?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"]];

                        $methodMap = [
                            "cash"          => ["lo" => "ເງິນສົດ",      "en" => "Cash"],
                            "bank_transfer" => ["lo" => "ໂອນທະນາຄານ", "en" => "Bank Transfer"],
                        ];
                        $m = $methodMap[$row["payment_method"]] ?? ["lo" => $row["payment_method"], "en" => $row["payment_method"]];

                        $statusMap = [
                            "pending"  => ["lo" => "ລໍຖ້າ",       "en" => "Pending"],
                            "approved" => ["lo" => "ອະນຸມັດ",    "en" => "Approved"],
                            "rejected" => ["lo" => "ປະຕິເສດ",    "en" => "Rejected"],
                        ];
                        $st = $statusMap[$row["status"]] ?? ["lo" => $row["status"], "en" => $row["status"]];

                        $rowClass = $row["status"] === "pending" ? "row-pending" : "";
                        ?>
                        <tr class="<?= $rowClass ?>">
                            <td style="color:var(--muted);font-size:12px;"><?= $i + 1 ?></td>
                            <td style="font-weight:600;"><?= htmlspecialchars($row["shop_name"]) ?></td>
                            <td style="font-family:monospace;font-size:12px;color:var(--muted);">
                                <?= htmlspecialchars($row["shop_code"]) ?>
                            </td>
                            <td>
                                <span class="type-badge <?= htmlspecialchars($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>
                                <span data-lo="<?= htmlspecialchars($m['lo']) ?>"
                                      data-en="<?= htmlspecialchars($m['en']) ?>">
                                    <?= htmlspecialchars($m['lo']) ?>
                                </span>
                            </td>
                            <td style="font-size:12px;color:var(--muted);">
                                <?= htmlspecialchars($row["reference_no"] ?: "—") ?>
                            </td>
                            <td style="font-size:12px;color:var(--muted);">
                                <?= htmlspecialchars($row["pay_ref"] ?? "—" ?: "—") ?>
                            </td>
                            <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="openLightbox('<?= htmlspecialchars($photoPath) ?>','<?= $fileLabel ?>')"
                                                 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="display:inline-flex;align-items:center;gap:5px;
                                                      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;">
                                                📎 <?= 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 class="note-cell">
                                <?= htmlspecialchars($row["note"] ?: "—") ?>
                            </td>
                            <td>
                                <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;font-size:12px;color:var(--muted);">
                                <?= htmlspecialchars($row["created_at"]) ?>
                            </td>
                            <td>
                                <?php if ($row["status"] === "pending"): ?>
                                    <a class="btn btn-approve"
                                       href="credit_requests.php?action=approve&id=<?= $row["id"] ?>"
                                       onclick="return confirm(window._lang==='lo' ? 'ອະນຸມັດຄຳຮ້ອງນີ້?' : 'Approve this request?')">
                                        ✅ <span data-lo="ອະນຸມັດ" data-en="Approve">ອະນຸມັດ</span>
                                    </a>
                                    <a class="btn btn-reject"
                                       href="credit_requests.php?action=reject&id=<?= $row["id"] ?>"
                                       onclick="return confirm(window._lang==='lo' ? 'ປະຕິເສດຄຳຮ້ອງນີ້?' : 'Reject this request?')"
                                       style="margin-top:4px;display:inline-flex;">
                                        ✕ <span data-lo="ປະຕິເສດ" data-en="Reject">ປະຕິເສດ</span>
                                    </a>
                                <?php else: ?>
                                    <span style="color:var(--muted);font-size:12px;">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </table>
        </div>

    </div><!-- /card -->

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

<!-- Lightbox -->
<div id="lightbox"
     onclick="closeLightbox()"
     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="lightboxImg" 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;">
        <!-- File size + dimensions info bar -->
        <div id="lightboxInfo"
             style="color:#fff;font-size:12px;margin-top:10px;
                    opacity:.85;display:flex;justify-content:center;gap:16px;flex-wrap:wrap;">
        </div>
        <button onclick="closeLightbox()"
                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>
        <a id="lightboxDownload" href="" download target="_blank"
           onclick="event.stopPropagation()"
           style="position:absolute;bottom:-44px;left:50%;transform:translateX(-50%);
                  background:#fff;color:#111;border-radius:8px;padding:6px 18px;
                  font-size:13px;font-weight:700;text-decoration:none;
                  box-shadow:0 2px 8px rgba(0,0,0,.2);">
            ⬇ <span data-lo="ດາວໂຫຼດ" data-en="Download">ດາວໂຫຼດ</span>
        </a>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
    const fromPicker = flatpickr("#from-date", {
        dateFormat: "Y-m-d", allowInput: false,
        onChange: (d, str) => toPicker.set("minDate", str)
    });
    const toPicker = flatpickr("#to-date", {
        dateFormat: "Y-m-d", allowInput: false,
        onChange: (d, str) => fromPicker.set("maxDate", str)
    });

    function openLightbox(src, fileSize) {
        const lb   = document.getElementById("lightbox");
        const img  = document.getElementById("lightboxImg");
        const dl   = document.getElementById("lightboxDownload");
        const info = document.getElementById("lightboxInfo");

        img.src  = src;
        dl.href  = src;
        info.innerHTML = fileSize
            ? `<span>📦 ${fileSize}</span><span id="lbDimensions"></span>`
            : "";

        lb.style.display = "flex";
        document.body.style.overflow = "hidden";

        /* Show pixel dimensions once image loads */
        img.onload = function() {
            const dim = document.getElementById("lbDimensions");
            if (dim) dim.textContent = " · " + img.naturalWidth + " × " + img.naturalHeight + " px";
        };
    }

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

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