<?php
/* ============================================================================
   ADMIN — ORDER MANAGEMENT
   ----------------------------------------------------------------------------
   Every order, on the new engine: what has been paid, what a seller still has
   to collect, and whether the office has verified what came in.
   ============================================================================ */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/wallet.php';
require_once __DIR__ . '/../includes/shares.php';
require_once __DIR__ . '/../includes/purchase.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
if (!hasPermission('manage_orders')) { die("Access Denied: You do not have permission to manage orders."); }

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

$can_users = hasPermission('manage_users');
$can_sellers = hasPermission('manage_sellers');
$can_staff = hasPermission('manage_staff_roles');
$can_services = hasPermission('manage_services');
$can_orders = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets = hasPermission('manage_tickets');
$can_settings = hasPermission('manage_settings');

buy_ensure_schema($db);

/* ---------- a small JSON endpoint for the detail drawer ---------- */
if (isset($_GET['ajax']) && $_GET['ajax'] === 'order') {
    header('Content-Type: application/json');
    $o = buy_order($db, (int)($_GET['id'] ?? 0));
    if (!$o) { echo json_encode(null); exit; }
    $o['collections'] = buy_collections($db, ['order_id' => (int)$o['id'], 'limit' => 50]);
    echo json_encode($o);
    exit;
}

/* ---------- actions ---------- */
$act = '';
foreach (['assign_seller','approve_collection','reject_collection','mark_visit_done','activate_order','complete_order','cancel_order','delete_order'] as $k) {
    if (isset($_POST[$k])) { $act = $k; break; }
}
if ($act !== '') {
    $oid = (int)($_POST['order_id'] ?? 0);
    $back = '../admin/orders.php' . (!empty($_GET['cat_id']) ? '?cat_id=' . (int)$_GET['cat_id'] : '');

    if ($act === 'assign_seller') {
        $r = buy_assign_seller($db, $oid, (int)($_POST['seller_id'] ?? 0), trim((string)($_POST['note'] ?? '')));
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Seller assigned.' : ($r['error'] ?? 'Could not assign the seller.');
    } elseif ($act === 'approve_collection') {
        $r = buy_approve_collection($db, (int)($_POST['collection_id'] ?? 0), trim((string)($_POST['note'] ?? '')));
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Collection verified.' : ($r['error'] ?? 'Could not verify it.');
    } elseif ($act === 'reject_collection') {
        $r = buy_reject_collection($db, (int)($_POST['collection_id'] ?? 0), trim((string)($_POST['reason'] ?? '')));
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Collection rejected.' : ($r['error'] ?? 'Could not reject it.');
    } elseif ($act === 'mark_visit_done') {
        $r = buy_mark_visit($db, $oid, 'done', '', 'Marked done by the office.');
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Visit marked as done.' : ($r['error'] ?? 'Could not save it.');
    } elseif ($act === 'activate_order') {
        $r = buy_activate_order($db, $oid, 'Activated by the office.');
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Service activated.' : ($r['error'] ?? 'Could not activate.');
    } elseif ($act === 'complete_order') {
        $r = buy_complete_order($db, $oid, 'Completed by the office.');
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Order completed.' : ($r['error'] ?? 'Could not complete.');
    } elseif ($act === 'cancel_order') {
        $r = buy_cancel_order($db, $oid, trim((string)($_POST['reason'] ?? 'Cancelled by the office.')));
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Order cancelled.' : ($r['error'] ?? 'Could not cancel.');
    } elseif ($act === 'delete_order') {
        try {
            $db->insert("DELETE FROM order_items WHERE order_id = ?", [$oid]);
            $db->insert("DELETE FROM order_timeline WHERE order_id = ?", [$oid]);
            $db->insert("DELETE FROM seller_collections WHERE order_id = ?", [$oid]);
            $db->insert("DELETE FROM orders WHERE id = ?", [$oid]);
            $_SESSION['flash_success'] = "Order deleted successfully!";
        } catch (\Throwable $e) { $_SESSION['flash_error'] = 'Could not delete that order.'; }
    }
    redirect($back);
}

/* ===========================================================================
   CATEGORY-WISE ORDER MANAGEMENT
   ======================================================================== */
/* 0 = every order · a positive number = that category · -1 = the ones with no category */
$filter_cat = isset($_GET['cat_id']) ? (int)$_GET['cat_id'] : 0;

$categories = [];
try {
    $categories = $db->select("SELECT id, title, icon_class FROM service_categories WHERE COALESCE(status,1)=1 ORDER BY display_order ASC, id ASC");
} catch (\Throwable $e) { $categories = []; }

/* ---------------------------------------------------------------------------
   EVERY ORDER NEEDS TO KNOW ITS CATEGORY

   `orders.category_id` is written at checkout, but it was added to the table
   after the site had already been taking orders — so every order placed before
   that had NULL in it, the tabs all read zero, and All Orders showed the lot.

   This fills in what is missing, from the order's own items first and from the
   product it names second. It only ever touches rows that are still empty, so
   after the first page load it does nothing at all.
   --------------------------------------------------------------------------- */
try {
    $db->insert("UPDATE orders o
                   JOIN order_items i ON i.order_id = o.id AND COALESCE(i.category_id,0) > 0
                    SET o.category_id = i.category_id
                  WHERE COALESCE(o.category_id,0) = 0");
} catch (\Throwable $e) {}
try {
    $db->insert("UPDATE orders o
                   JOIN seller_services s ON UPPER(TRIM(s.title)) = UPPER(TRIM(o.service_name))
                    SET o.category_id = s.category_id
                  WHERE COALESCE(o.category_id,0) = 0 AND COALESCE(s.category_id,0) > 0");
} catch (\Throwable $e) {}

$cat_counts = [];
$total_orders_all = 0;
$uncat_count = 0;
try {
    foreach ($db->select("SELECT COALESCE(category_id,0) c, COUNT(*) n FROM orders GROUP BY COALESCE(category_id,0)") as $row) {
        $cat_counts[(int)$row['c']] = (int)$row['n'];
        $total_orders_all += (int)$row['n'];
    }
    /* Orders whose product no longer exists belong to no category. They get
       their own chip rather than disappearing, so the tabs always add up to
       the All Orders figure. */
    $uncat_count = $cat_counts[0] ?? 0;
} catch (\Throwable $e) {}

$order_where  = '1=1';
$order_params = [];
if ($filter_cat > 0)       { $order_where = 'o.category_id = ?'; $order_params[] = $filter_cat; }
elseif ($filter_cat === -1) { $order_where = 'COALESCE(o.category_id,0) = 0'; }

$q = trim((string)($_GET['q'] ?? ''));
if ($q !== '') {
    $order_where .= " AND (o.order_code LIKE ? OR u.name LIKE ? OR u.mobile LIKE ? OR o.service_name LIKE ?)";
    $like = '%' . $q . '%';
    array_push($order_params, $like, $like, $like, $like);
}

$orders = $db->select(
    /* LEFT JOIN, not JOIN. Nine orders belong to accounts that have since been
       deleted; an inner join dropped them from the list while the count above
       still included them, so the page said "54" and showed 45. An order is a
       record of money — it does not stop existing because the account did. */
    "SELECT o.*, u.name as customer_name, u.mobile as customer_mobile, s.name as seller_name
       FROM orders o
       LEFT JOIN users u ON o.user_id = u.id
       LEFT JOIN users s ON o.seller_id = s.id
      WHERE $order_where
      ORDER BY o.created_at DESC LIMIT 300",
    $order_params
);

$active_cat_title = $filter_cat === -1 ? 'Orders with no category' : 'All Orders';
foreach ($categories as $c) {
    if ((int)$c['id'] === $filter_cat) { $active_cat_title = html_entity_decode($c['title'], ENT_QUOTES, 'UTF-8'); break; }
}

$sellers_list = [];
try { $sellers_list = $db->select("SELECT id, name, mobile FROM users WHERE user_type = 'seller' AND status = 1 ORDER BY name ASC"); }
catch (\Throwable $e) {}

/* ---------- headline figures ---------- */
$stats = buy_stats($db);
$fin = ['advance_received' => 0.0, 'seller_cash' => 0.0, 'seller_payout' => 0.0, 'company_profit' => 0.0, 'advance_orders' => 0, 'pending_verify' => 0];
try {
    $r = $db->select("SELECT COALESCE(SUM(paid_amount),0) ar, COALESCE(SUM(seller_payout),0) sp, COALESCE(SUM(company_profit),0) cp,
                              COALESCE(SUM(payment_mode='advance'),0) ao
                         FROM orders WHERE stage <> 'cancelled'");
    if (!empty($r)) {
        $fin['advance_received'] = round((float)$r[0]['ar'], 2);
        $fin['seller_payout']    = round((float)$r[0]['sp'], 2);
        $fin['company_profit']   = round((float)$r[0]['cp'], 2);
        $fin['advance_orders']   = (int)$r[0]['ao'];
    }
    $r2 = $db->select("SELECT COALESCE(SUM(amount),0) c FROM seller_collections WHERE status = 'approved' AND mode = 'cash'");
    $fin['seller_cash'] = round((float)($r2[0]['c'] ?? 0), 2);
    $r3 = $db->select("SELECT COUNT(*) n FROM seller_collections WHERE status = 'pending'");
    $fin['pending_verify'] = (int)($r3[0]['n'] ?? 0);
} catch (\Throwable $e) {}

$company_logo = getSetting('company_logo', '../assets/images/logo.png');
$company_name = getSetting('company_name', 'WBMCZ');

function opr($n) { return '₹' . number_format((float)$n, 2); }
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Orders - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .hide-scrollbar::-webkit-scrollbar { display: none; }
        .stat { background:#fff; border:1px solid #eef1f5; border-radius:16px; padding:16px 18px; }
        .row2 { display:flex; align-items:center; justify-content:space-between; padding:8px 0; border-bottom:1px dashed #eef2f7; font-size:.83rem; }
        .row2:last-child { border-bottom:0; }
    </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, orderModal: false, curId: 0, o: {}, loading: false,
    open(id) { this.curId = id; this.o = {}; this.loading = true; this.orderModal = true;
               fetch('orders.php?ajax=order&id=' + id).then(r => r.json()).then(d => { this.o = d || {}; this.loading = false; }); },
    money(n) { return '₹' + Number(n || 0).toFixed(2); } }">

    <div class="flex h-screen overflow-hidden">

        <?php include __DIR__ . '/includes/sidebar.php'; ?>
        <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
            <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 shadow-sm border-b border-gray-200 z-40 relative">
                <div class="flex items-center"><button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg"><i class="fas fa-bars text-xl"></i></button><h2 class="text-xl font-bold hidden md:block text-slate-800">Manage Orders</h2></div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6">

                <?php if (!empty($_SESSION['flash_success'])): ?>
                <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                    <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo $_SESSION['flash_success']; unset($_SESSION['flash_success']); ?></span>
                </div>
                <?php endif; ?>
                <?php if (!empty($_SESSION['flash_error'])): ?>
                <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                    <i class="fas fa-circle-exclamation mr-2"></i><span class="font-medium"><?php echo $_SESSION['flash_error']; unset($_SESSION['flash_error']); ?></span>
                </div>
                <?php endif; ?>

                <!-- ============ STAT CARDS ============ -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-5">
                    <div class="stat"><p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Total Orders</p><p class="text-2xl font-extrabold text-slate-800 mt-1"><?php echo number_format($stats['orders']); ?></p></div>
                    <div class="stat"><p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Advance Payments</p><p class="text-2xl font-extrabold text-amber-600 mt-1"><?php echo number_format($fin['advance_orders']); ?></p></div>
                    <div class="stat"><p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Pending Verification</p><p class="text-2xl font-extrabold text-rose-600 mt-1"><?php echo number_format($fin['pending_verify']); ?></p></div>
                    <div class="stat"><p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Completed Orders</p><p class="text-2xl font-extrabold text-emerald-600 mt-1"><?php echo number_format($stats['completed']); ?></p></div>
                </div>

                <!-- ============ FINANCIAL OVERVIEW ============ -->
                <div class="bg-white rounded-2xl border border-gray-200 p-5 mb-6">
                    <p class="text-xs font-extrabold text-slate-500 uppercase tracking-wide mb-3">Financial Overview</p>
                    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
                        <div><p class="text-[11px] text-slate-400 font-semibold">Total Advance Received</p><p class="text-lg font-extrabold text-slate-800"><?php echo opr($fin['advance_received']); ?></p></div>
                        <div><p class="text-[11px] text-slate-400 font-semibold">Seller Collection (Cash)</p><p class="text-lg font-extrabold text-slate-800"><?php echo opr($fin['seller_cash']); ?></p></div>
                        <div><p class="text-[11px] text-slate-400 font-semibold">Seller Payout</p><p class="text-lg font-extrabold text-slate-800"><?php echo opr($fin['seller_payout']); ?></p></div>
                        <div><p class="text-[11px] text-slate-400 font-semibold">Company Profit</p><p class="text-lg font-extrabold text-emerald-600"><?php echo opr($fin['company_profit']); ?></p></div>
                    </div>
                </div>

                <!-- ============ CATEGORY FILTER ============ -->
                <div class="mb-6">
                    <div class="flex items-baseline justify-between gap-3 mb-3 flex-wrap">
                        <h3 class="text-lg font-extrabold text-slate-800"><?php echo htmlspecialchars($active_cat_title); ?></h3>
                        <form method="GET" class="flex items-center gap-2">
                            <?php if ($filter_cat > 0): ?><input type="hidden" name="cat_id" value="<?php echo $filter_cat; ?>"><?php endif; ?>
                            <input type="text" name="q" value="<?php echo htmlspecialchars($q); ?>" placeholder="Search order, customer, mobile…" class="px-3 py-1.5 text-xs border border-slate-200 rounded-lg w-56">
                            <button class="px-3 py-1.5 text-xs font-bold bg-slate-800 text-white rounded-lg">Search</button>
                        </form>
                        <p class="text-xs text-slate-400 font-semibold"><?php echo number_format(count($orders)); ?> order<?php echo count($orders) === 1 ? '' : 's'; ?> shown</p>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <?php
                        $chip_on  = 'bg-slate-900 text-white ring-slate-900 shadow-lg shadow-slate-900/20';
                        $chip_off = 'bg-white text-slate-600 ring-slate-200 hover:bg-slate-50 hover:text-slate-900';
                        ?>
                        <a href="orders.php" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold ring-1 transition-all <?php echo $filter_cat === 0 ? $chip_on : $chip_off; ?>">
                            <i class="fas fa-layer-group text-[.7rem]"></i> All Orders
                            <?php if ($total_orders_all > 0): ?><span class="opacity-60"><?php echo $total_orders_all; ?></span><?php endif; ?>
                        </a>
                        <?php foreach ($categories as $c):
                            $cid = (int)$c['id'];
                            $n   = $cat_counts[$cid] ?? 0; ?>
                            <a href="orders.php?cat_id=<?php echo $cid; ?>"
                               class="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold ring-1 transition-all <?php echo $filter_cat === $cid ? $chip_on : $chip_off; ?>">
                                <i class="fas <?php echo htmlspecialchars($c['icon_class'] ?: 'fa-circle-dot'); ?> text-[.7rem]"></i>
                                <?php echo htmlspecialchars(html_entity_decode($c['title'], ENT_QUOTES, 'UTF-8')); ?>
                                <?php if ($n > 0): ?><span class="opacity-60"><?php echo $n; ?></span><?php endif; ?>
                            </a>
                        <?php endforeach; ?>
                        <?php if ($uncat_count > 0): ?>
                            <a href="orders.php?cat_id=-1"
                               class="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold ring-1 transition-all <?php echo $filter_cat === -1 ? $chip_on : $chip_off; ?>"
                               title="Their product no longer exists, so they belong to no category">
                                <i class="fas fa-circle-question text-[.7rem]"></i> No category
                                <span class="opacity-60"><?php echo $uncat_count; ?></span>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wider border-b border-gray-100">
                                    <th class="p-4 pl-6 font-semibold">Order</th>
                                    <th class="p-4 font-semibold">Service &amp; Seller</th>
                                    <th class="p-4 font-semibold">Payment</th>
                                    <th class="p-4 font-semibold text-center">Stage</th>
                                    <th class="p-4 pr-6 font-semibold text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-50">
                                <?php if (!empty($orders)): foreach ($orders as $order):
                                    $meta = buy_stage_meta($order['stage']);
                                    $cancelled = $order['stage'] === 'cancelled';
                                    $badge = $cancelled ? 'bg-rose-100 text-rose-700' : ((float)$order['due_amount'] > 0 ? 'bg-amber-100 text-amber-700' : 'bg-emerald-100 text-emerald-700');
                                ?>
                                <tr class="hover:bg-gray-50 transition-colors">
                                    <td class="p-4 pl-6">
                                        <p class="font-bold text-gray-800 text-sm"><?php echo htmlspecialchars($order['order_code'] ?: ('#' . $order['id'])); ?></p>
                                        <p class="text-xs text-gray-500">
                                            <?php if (($order['customer_name'] ?? '') !== ''): ?>
                                                <?php echo htmlspecialchars($order['customer_name']); ?> · <?php echo htmlspecialchars((string)$order['customer_mobile']); ?>
                                            <?php else: ?>
                                                <?php /* the account was deleted — the order stays, and says so */ ?>
                                                <span class="text-slate-400 italic">Account removed</span>
                                                <?php if (($order['customer_mobile'] ?? '') !== ''): ?> · <?php echo htmlspecialchars((string)$order['customer_mobile']); ?><?php endif; ?>
                                            <?php endif; ?>
                                        </p>
                                        <p class="text-[10px] text-gray-400 mt-1"><?php echo date('d M Y, h:i A', strtotime($order['created_at'])); ?></p>
                                    </td>
                                    <td class="p-4">
                                        <p class="font-bold text-slate-700 text-sm"><?php echo htmlspecialchars($order['service_name']); ?></p>
                                        <?php if ($order['seller_id'] > 0): ?>
                                            <p class="text-xs text-emerald-600 font-semibold"><i class="fas fa-store mr-1"></i> <?php echo htmlspecialchars($order['seller_name']); ?></p>
                                        <?php else: ?>
                                            <p class="text-xs text-blue-600 font-semibold"><i class="fas fa-server mr-1"></i> Not assigned</p>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4">
                                        <p class="font-extrabold text-gray-800 text-sm"><?php echo opr($order['amount']); ?></p>
                                        <p class="text-[10.5px] text-slate-400"><?php echo ucfirst($order['payment_mode']); ?> · Paid <?php echo opr($order['paid_amount']); ?><?php if ((float)$order['due_amount'] > 0): ?> · Due <span class="text-amber-600 font-bold"><?php echo opr($order['due_amount']); ?></span><?php endif; ?></p>
                                    </td>
                                    <td class="p-4 text-center">
                                        <span class="px-3 py-1 text-[10px] font-bold uppercase tracking-wider rounded-full <?php echo $badge; ?>"><?php echo htmlspecialchars($meta[0]); ?></span>
                                    </td>
                                    <td class="p-4 pr-6 text-right whitespace-nowrap">
                                        <button @click="open(<?php echo (int)$order['id']; ?>)" class="w-8 h-8 rounded-lg bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors inline-flex items-center justify-center" title="View / manage">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <form method="POST" class="inline-block" onsubmit="return confirm('Delete this order permanently? This also removes its items, timeline and collections.');">
                                            <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                            <button type="submit" name="delete_order" class="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-600 transition-colors inline-flex items-center justify-center">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; else: ?>
                                    <tr><td colspan="5" class="p-8 text-center text-gray-500">No orders found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </main>
        </div>
    </div>

    <!-- ============ ORDER DETAIL / MANAGE DRAWER ============ -->
    <div x-show="orderModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4" style="display:none;">
        <div @click.away="orderModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[92vh] overflow-hidden flex flex-col">
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50 flex-shrink-0">
                <h3 class="font-bold text-gray-900 text-lg" x-text="o.order_code || ('Order #' + curId)"></h3>
                <button @click="orderModal = false" class="text-gray-400 hover:text-rose-500"><i class="fas fa-times text-xl"></i></button>
            </div>
            <div class="p-6 overflow-y-auto space-y-5">
                <template x-if="loading"><p class="text-center text-slate-400 py-8"><i class="fas fa-spinner fa-spin mr-2"></i>Loading…</p></template>

                <template x-if="!loading && o.id">
                <div class="space-y-5">
                    <div class="bg-slate-50 rounded-xl border border-slate-100 p-4">
                        <div class="row2"><span class="text-slate-500 font-semibold">Customer</span><span class="font-bold text-slate-800" x-text="o.customer_name + ' · ' + o.customer_mobile"></span></div>
                        <div class="row2"><span class="text-slate-500 font-semibold">Product</span><span class="font-bold text-slate-800" x-text="o.service_name"></span></div>
                        <div class="row2"><span class="text-slate-500 font-semibold">Payment method</span><span class="font-bold text-slate-800" x-text="o.payment_mode"></span></div>
                        <div class="row2"><span class="text-slate-500 font-semibold">Order total</span><span class="font-extrabold text-slate-800" x-text="money(o.amount)"></span></div>
                        <div class="row2"><span class="text-slate-500 font-semibold">Paid so far</span><span class="font-extrabold text-emerald-600" x-text="money(o.paid_amount)"></span></div>
                        <div class="row2"><span class="text-amber-700 font-semibold">Still due</span><span class="font-extrabold text-amber-700" x-text="money(o.due_amount)"></span></div>
                        <template x-if="o.payment_code"><div class="row2"><span class="text-slate-500 font-semibold">Payment code</span><span class="font-extrabold text-amber-700" x-text="o.payment_code + ' (' + o.payment_code_status + ')'"></span></div></template>
                    </div>

                    <!-- assign seller -->
                    <form method="POST" class="flex items-end gap-2">
                        <input type="hidden" name="order_id" :value="curId">
                        <div class="flex-1">
                            <label class="block text-[11px] font-bold text-slate-500 uppercase mb-1">Seller</label>
                            <select name="seller_id" class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm">
                                <option value="0">— none —</option>
                                <?php foreach ($sellers_list as $s): ?>
                                    <option value="<?php echo (int)$s['id']; ?>" :selected="String(o.seller_id) === '<?php echo (int)$s['id']; ?>'"><?php echo htmlspecialchars($s['name']); ?> (<?php echo htmlspecialchars($s['mobile']); ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="submit" name="assign_seller" class="px-4 py-2 text-xs font-bold bg-slate-800 text-white rounded-lg h-[38px]">Assign</button>
                    </form>

                    <!-- pending collections -->
                    <template x-if="(o.collections || []).length">
                        <div>
                            <p class="text-[11px] font-extrabold uppercase tracking-wide text-slate-400 mb-2">Collections reported</p>
                            <template x-for="c in o.collections" :key="c.id">
                                <div class="flex items-center justify-between border border-slate-100 rounded-lg px-3 py-2 mb-2 text-[12.5px]">
                                    <div>
                                        <p class="font-bold text-slate-700" x-text="c.mode + ' · ' + money(c.amount)"></p>
                                        <p class="text-slate-400" x-text="c.created_at"></p>
                                    </div>
                                    <template x-if="c.status === 'pending'">
                                        <div class="flex gap-1.5">
                                            <form method="POST"><input type="hidden" name="order_id" :value="curId"><input type="hidden" name="collection_id" :value="c.id">
                                                <button name="approve_collection" class="px-2.5 py-1 text-[11px] font-bold bg-emerald-600 text-white rounded-lg">Verify</button></form>
                                            <form method="POST"><input type="hidden" name="order_id" :value="curId"><input type="hidden" name="collection_id" :value="c.id">
                                                <button name="reject_collection" class="px-2.5 py-1 text-[11px] font-bold bg-rose-100 text-rose-700 rounded-lg">Reject</button></form>
                                        </div>
                                    </template>
                                    <span x-show="c.status !== 'pending'" class="px-2 py-0.5 rounded-full text-[10px] font-bold"
                                          :class="c.status === 'approved' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'" x-text="c.status"></span>
                                </div>
                            </template>
                        </div>
                    </template>

                    <!-- stage actions -->
                    <div class="flex flex-wrap gap-2 pt-2 border-t border-slate-100">
                        <form method="POST"><input type="hidden" name="order_id" :value="curId">
                            <button name="mark_visit_done" x-show="o.fulfilment === 'visit'" class="px-3 py-2 text-xs font-bold bg-blue-50 text-blue-700 rounded-lg"><i class="fas fa-person-walking mr-1"></i> Mark Visit Done</button></form>
                        <form method="POST"><input type="hidden" name="order_id" :value="curId">
                            <button name="activate_order" x-show="Number(o.due_amount) <= 0" class="px-3 py-2 text-xs font-bold bg-indigo-50 text-indigo-700 rounded-lg"><i class="fas fa-circle-check mr-1"></i> Activate Service</button></form>
                        <form method="POST"><input type="hidden" name="order_id" :value="curId">
                            <button name="complete_order" x-show="Number(o.due_amount) <= 0" class="px-3 py-2 text-xs font-bold bg-emerald-600 text-white rounded-lg"><i class="fas fa-flag-checkered mr-1"></i> Mark Completed</button></form>
                        <form method="POST" onsubmit="return confirm('Cancel this order? Any online payment is refunded to the wallet.');"><input type="hidden" name="order_id" :value="curId">
                            <button name="cancel_order" x-show="o.stage !== 'completed' && o.stage !== 'cancelled'" class="px-3 py-2 text-xs font-bold bg-rose-50 text-rose-700 rounded-lg"><i class="fas fa-ban mr-1"></i> Cancel Order</button></form>
                    </div>

                    <!-- timeline -->
                    <div>
                        <p class="text-[11px] font-extrabold uppercase tracking-wide text-slate-400 mb-2">Timeline</p>
                        <template x-for="t in (o.timeline || [])" :key="t.id">
                            <div class="text-[12px] py-1.5 border-b border-slate-50">
                                <span class="font-bold text-slate-700" x-text="t.title"></span>
                                <span class="text-slate-400" x-text="' — ' + t.created_at"></span>
                                <p class="text-slate-400" x-text="t.note"></p>
                            </div>
                        </template>
                    </div>
                </div>
                </template>
            </div>
        </div>
    </div>
</body>
</html>
