<?php
/**
 * Standalone PHP Kuriyar: list Firebase orders (REST ?auth=idToken; no service account file).
 * Open from dashboard: PHP Kuriyar menu (no MySQL session).
 */
require_once __DIR__ . '/api/kuriyar-firebase-client.php';

$clientId = isset($_GET['clientId']) ? trim((string) $_GET['clientId']) : '';
$token = isset($_GET['token']) ? trim((string) $_GET['token']) : '';

$err = null;
$orders = [];

if ($clientId === '' || $token === '') {
    $err = 'Missing clientId or token. Open this page from the store dashboard (PHP Kuriyar).';
} else {
    $chk = kuriyar_verify_store_admin($clientId, $token);
    if (isset($chk['error'])) {
        $err = $chk['error'];
    } else {
        $snap = kuriyar_rtdb_get('clients/' . $clientId . '/orders', $token);
        if (isset($snap['error'])) {
            $err = 'Could not load orders: ' . $snap['error'];
        } else {
            $raw = $snap['data'] ?? null;
            if (is_array($raw)) {
                foreach ($raw as $key => $order) {
                    if (!is_string($key) || !is_array($order)) {
                        continue;
                    }
                    $orders[] = ['key' => $key, 'order' => $order];
                }
            }
        }
    }
}

function kuriyar_order_sort_ts(array $row) {
    $c = $row['order']['createdAt'] ?? null;
    if (is_numeric($c)) {
        return (int) $c;
    }
    if (is_array($c)) {
        return 0;
    }
    return 0;
}

usort($orders, static function ($a, $b) {
    return kuriyar_order_sort_ts($b) <=> kuriyar_order_sort_ts($a);
});

$pageTitle = 'PHP Kuriyar';
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8'); ?></title>
    <link rel="stylesheet" href="style.css">
    <style>
        .kuriyar-wrap { max-width: 1100px; margin: 0 auto; padding: 1rem 1.25rem 2rem; }
        .kuriyar-wrap h1 { font-size: 1.35rem; margin-bottom: 0.5rem; }
        .kuriyar-sub { color: #64748b; font-size: 0.9rem; margin-bottom: 1.25rem; }
        .kuriyar-table-wrap { overflow-x: auto; margin-bottom: 1.5rem; border: 1px solid #e2e8f0; border-radius: 8px; }
        table.kuriyar-orders { width: 100%; border-collapse: collapse; font-size: 0.875rem; }
        table.kuriyar-orders th, table.kuriyar-orders td { padding: 0.5rem 0.65rem; text-align: left; border-bottom: 1px solid #e2e8f0; }
        table.kuriyar-orders th { background: #f8fafc; font-weight: 600; }
        table.kuriyar-orders tr:hover td { background: #f1f5f9; }
        .badge { display: inline-block; padding: 0.15rem 0.45rem; border-radius: 4px; font-size: 0.75rem; }
        .badge-pending { background: #fef3c7; color: #92400e; }
        .badge-shipped { background: #d1fae5; color: #065f46; }
        .kuriyar-form .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; }
        @media (max-width: 640px) { .kuriyar-form .row2 { grid-template-columns: 1fr; } }
        .kuriyar-form label { display: block; font-weight: 500; margin-top: 0.65rem; margin-bottom: 0.25rem; font-size: 0.85rem; }
        .kuriyar-form input, .kuriyar-form textarea, .kuriyar-form select { width: 100%; box-sizing: border-box; padding: 0.45rem 0.5rem; border: 1px solid #cbd5e1; border-radius: 6px; }
        .kuriyar-actions { margin-top: 1rem; display: flex; gap: 0.75rem; flex-wrap: wrap; align-items: center; }
        #kuriyar-msg { margin-top: 0.75rem; padding: 0.65rem; border-radius: 6px; display: none; }
        #kuriyar-msg.ok { display: block; background: #d1fae5; color: #065f46; }
        #kuriyar-msg.err { display: block; background: #fee2e2; color: #991b1b; }
    </style>
</head>
<body class="standalone-page">
<div class="kuriyar-wrap container">
    <h1><?php echo htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8'); ?></h1>
    <p class="kuriyar-sub">Firebase অর্ডার দেখে Steadfast-এ পাঠান। ড্যাশবোর্ড থেকে এই পেজ ওপেন করুন (টোকেন URL-এ থাকে — শেয়ার করবেন না)।</p>

    <?php if ($err !== null): ?>
        <p class="msg error"><?php echo htmlspecialchars($err, ENT_QUOTES, 'UTF-8'); ?></p>
    <?php else: ?>
        <p class="page-subtitle" style="margin-top:0;">Client: <code><?php echo htmlspecialchars($clientId, ENT_QUOTES, 'UTF-8'); ?></code> · মোট <?php echo count($orders); ?> অর্ডার</p>

        <script type="application/json" id="kuriyar-orders-data"><?php
            echo json_encode($orders, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_UNESCAPED_UNICODE);
        ?></script>
        <div class="kuriyar-table-wrap">
            <table class="kuriyar-orders" id="kuriyar-order-table">
                <thead>
                    <tr>
                        <th>Invoice (Steadfast)</th>
                        <th>অর্ডার ID</th>
                        <th>গ্রাহক</th>
                        <th>ফোন</th>
                        <th>COD</th>
                        <th>স্ট্যাটাস</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $row):
                        $k = $row['key'];
                        $o = $row['order'];
                        $ci = isset($o['customerInfo']) && is_array($o['customerInfo']) ? $o['customerInfo'] : [];
                        $name = isset($ci['name']) ? (string) $ci['name'] : '';
                        $phone = isset($ci['phone']) ? (string) $ci['phone'] : '';
                        $inv = preg_replace('/[^a-zA-Z0-9_-]/', '_', $k);
                        if ($inv === '') {
                            $inv = 'order';
                        }
                        if (strlen($inv) > 191) {
                            $inv = substr($inv, 0, 191);
                        }
                        $oid = isset($o['orderId']) ? (string) $o['orderId'] : '';
                        $total = isset($o['totalBill']) ? $o['totalBill'] : (isset($o['amount']['total']) ? $o['amount']['total'] : '');
                        $st = isset($o['status']) ? (string) $o['status'] : '';
                        $hasCourier = !empty($o['courierInfo']) && is_array($o['courierInfo']);
                        $badgeClass = ($hasCourier || stripos($st, 'ship') !== false) ? 'badge-shipped' : 'badge-pending';
                        ?>
                        <tr data-key="<?php echo htmlspecialchars($k, ENT_QUOTES, 'UTF-8'); ?>">
                            <td><code><?php echo htmlspecialchars($inv, ENT_QUOTES, 'UTF-8'); ?></code></td>
                            <td><?php echo htmlspecialchars($oid, ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars($phone, ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars((string) $total, ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><span class="badge <?php echo $badgeClass; ?>"><?php echo htmlspecialchars($st !== '' ? $st : '—', ENT_QUOTES, 'UTF-8'); ?></span></td>
                            <td><button type="button" class="btn-load-order">ফর্মে নিন</button></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="card kuriyar-form">
            <h2 class="section-title" style="margin-top:0;">Steadfast অর্ডার</h2>
            <input type="hidden" id="firebase_order_key" value="">
            <div class="row2">
                <div>
                    <label for="invoice">Invoice</label>
                    <input type="text" id="invoice" maxlength="191" autocomplete="off">
                </div>
                <div>
                    <label for="cod_amount">COD (BDT)</label>
                    <input type="number" id="cod_amount" min="0" step="0.01" value="0">
                </div>
            </div>
            <label for="recipient_name">প্রাপকের নাম</label>
            <input type="text" id="recipient_name" maxlength="100">
            <div class="row2">
                <div>
                    <label for="recipient_phone">ফোন (১১ অঙ্ক)</label>
                    <input type="text" id="recipient_phone" maxlength="11" placeholder="01712345678">
                </div>
                <div>
                    <label for="alternative_phone">বিকল্প ফোন (ঐচ্ছিক)</label>
                    <input type="text" id="alternative_phone" maxlength="11">
                </div>
            </div>
            <label for="recipient_address">ঠিকানা</label>
            <textarea id="recipient_address" rows="3" maxlength="250"></textarea>
            <div class="row2">
                <div>
                    <label for="item_description">পণ্য বিবরণ</label>
                    <input type="text" id="item_description">
                </div>
                <div>
                    <label for="delivery_type">ডেলিভারি</label>
                    <select id="delivery_type">
                        <option value="0">হোম ডেলিভারি</option>
                        <option value="1">হাব পিকআপ</option>
                    </select>
                </div>
            </div>
            <label for="note">নোট</label>
            <input type="text" id="note">
            <div class="kuriyar-actions">
                <button type="button" id="btn-submit-kuriyar">কুরিয়ারে পাঠান</button>
            </div>
        </div>

        <div id="kuriyar-msg"></div>

        <script type="application/json" id="kuriyar-bootstrap"><?php
            echo json_encode([
                'clientId' => $clientId,
                'token' => $token,
            ], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_UNESCAPED_UNICODE);
        ?></script>
        <script>
        (function() {
            var bootEl = document.getElementById('kuriyar-bootstrap');
            var boot = bootEl ? JSON.parse(bootEl.textContent) : {};
            var clientId = boot.clientId || '';
            var idToken = boot.token || '';

            var ordersByKey = {};
            try {
                var od = document.getElementById('kuriyar-orders-data');
                if (od && od.textContent) {
                    var list = JSON.parse(od.textContent);
                    if (Array.isArray(list)) {
                        list.forEach(function(row) {
                            if (row && row.key) ordersByKey[row.key] = row.order || {};
                        });
                    }
                }
            } catch (e2) { ordersByKey = {}; }

            function onlyDigits(s) { return String(s || '').replace(/\D/g, ''); }

            function buildSteadfastInvoice(orderKey) {
                var s = String(orderKey || '').replace(/[^a-zA-Z0-9_-]/g, '_');
                if (!s) s = 'order';
                if (s.length > 191) s = s.slice(0, 191);
                return s;
            }

            function itemsLineFromOrder(order) {
                var items = Array.isArray(order.items) ? order.items : Object.values(order.items || {});
                return items.map(function(i) {
                    return (i.name || '') + ' (x' + (i.quantity || 0) + ')';
                }).join(', ');
            }

            function fillFromOrder(key, order) {
                document.getElementById('firebase_order_key').value = key;
                document.getElementById('invoice').value = buildSteadfastInvoice(key);
                var ci = order.customerInfo || {};
                document.getElementById('recipient_name').value = (ci.name || '').trim();
                document.getElementById('recipient_phone').value = onlyDigits(ci.phone || '');
                document.getElementById('recipient_address').value = (ci.address || '').trim();
                var cod = Number(order.totalBill != null ? order.totalBill : (order.amount && order.amount.total));
                document.getElementById('cod_amount').value = isNaN(cod) ? 0 : cod;
                var line = itemsLineFromOrder(order);
                document.getElementById('item_description').value = line;
                document.getElementById('note').value = line ? ('Items: ' + line) : '';
            }

            document.querySelectorAll('.btn-load-order').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var tr = btn.closest('tr');
                    if (!tr) return;
                    var key = tr.getAttribute('data-key');
                    var order = ordersByKey[key];
                    if (!order) {
                        alert('অর্ডার ডেটা পাওয়া যায়নি');
                        return;
                    }
                    fillFromOrder(key, order);
                });
            });

            function showMsg(text, ok) {
                var el = document.getElementById('kuriyar-msg');
                el.textContent = text;
                el.className = ok ? 'ok' : 'err';
                el.style.display = 'block';
            }

            document.getElementById('btn-submit-kuriyar').addEventListener('click', function() {
                var fk = document.getElementById('firebase_order_key').value.trim();
                if (!fk) {
                    showMsg('আগে টেবিল থেকে একটি অর্ডার নির্বাচন করুন (ফর্মে নিন)।', false);
                    return;
                }
                var payload = {
                    clientId: clientId,
                    idToken: idToken,
                    firebase_order_key: fk,
                    invoice: document.getElementById('invoice').value.trim(),
                    recipient_name: document.getElementById('recipient_name').value.trim(),
                    recipient_phone: onlyDigits(document.getElementById('recipient_phone').value),
                    recipient_address: document.getElementById('recipient_address').value.trim(),
                    cod_amount: document.getElementById('cod_amount').value,
                    note: document.getElementById('note').value.trim(),
                    item_description: document.getElementById('item_description').value.trim(),
                    delivery_type: parseInt(document.getElementById('delivery_type').value, 10),
                    alternative_phone: onlyDigits(document.getElementById('alternative_phone').value)
                };
                if (payload.alternative_phone === '') delete payload.alternative_phone;

                var btn = document.getElementById('btn-submit-kuriyar');
                btn.disabled = true;
                fetch('kuriyar-api.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                }).then(function(r) { return r.json().then(function(d) { return { ok: r.ok, d: d }; }); })
                .then(function(x) {
                    btn.disabled = false;
                    if (x.d && x.d.success) {
                        showMsg(x.d.message + (x.d.tracking_code ? (' ট্র্যাকিং: ' + x.d.tracking_code) : ''), true);
                    } else {
                        showMsg((x.d && x.d.message) ? x.d.message : 'ব্যর্থ', false);
                    }
                }).catch(function() {
                    btn.disabled = false;
                    showMsg('নেটওয়ার্ক ত্রুটি।', false);
                });
            });
        })();
        </script>
    <?php endif; ?>
</div>
</body>
</html>
