<?php
/* ============================================================================
   SELLER — ORDERS & COLLECTIONS
   ----------------------------------------------------------------------------
   What has been assigned to this seller, what still needs a visit, and what
   is left to collect. Recording a collection here only reports it — the
   office still has to verify it before it counts.
   ============================================================================ */
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() || $_SESSION['user_type'] !== 'seller') { redirect('../login.php'); }

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

buy_ensure_schema($db);

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;

$categories = $db->select("SELECT * FROM service_categories WHERE status = 1 AND show_to_seller = 1 ORDER BY display_order ASC");
$seller_cat_ids = !empty($user['seller_categories']) ? explode(',', $user['seller_categories']) : [1, 5];
$sidebar_allowed_cats = [];
foreach ($categories as $cat) { if (in_array($cat['id'], $seller_cat_ids)) { $sidebar_allowed_cats[] = $cat; } }

$filter_cat = isset($_GET['cat_id']) ? intval($_GET['cat_id']) : 0;

/* ---------- ajax: one order's full detail, for the manage drawer ---------- */
if (isset($_GET['ajax']) && $_GET['ajax'] === 'order') {
    header('Content-Type: application/json');
    $o = buy_order($db, (int)($_GET['id'] ?? 0));
    if (!$o || (int)$o['seller_id'] !== (int)$user_id) { 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 (['record_collection', 'mark_visit_scheduled', 'mark_visit_done'] as $k) {
    if (isset($_POST[$k])) { $act = $k; break; }
}
if ($act !== '') {
    $oid = (int)($_POST['order_id'] ?? 0);
    $own = $db->select("SELECT id FROM orders WHERE id = ? AND seller_id = ?", [$oid, $user_id]);
    if (empty($own)) { $_SESSION['flash_error'] = 'That order is not assigned to you.'; redirect('orders.php'); }

    if ($act === 'record_collection') {
        $r = buy_record_collection($db, $oid, [
            'amount'    => (float)($_POST['amount'] ?? 0),
            'mode'      => (string)($_POST['mode'] ?? 'cash'),
            'reference' => trim((string)($_POST['reference'] ?? '')),
            'note'      => trim((string)($_POST['note'] ?? '')),
            'seller_id' => $user_id,
        ]);
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok']
            ? 'Collection reported — it will show as verified once the office checks it.'
            : ($r['error'] ?? 'Could not save it.');
    } elseif ($act === 'mark_visit_scheduled') {
        $r = buy_mark_visit($db, $oid, 'scheduled', trim((string)($_POST['when'] ?? '')), trim((string)($_POST['note'] ?? '')));
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Visit scheduled.' : ($r['error'] ?? 'Could not save it.');
    } elseif ($act === 'mark_visit_done') {
        $r = buy_mark_visit($db, $oid, 'done', '', 'Visit completed by the seller.');
        $_SESSION[$r['ok'] ? 'flash_success' : 'flash_error'] = $r['ok'] ? 'Visit marked as done.' : ($r['error'] ?? 'Could not save it.');
    }
    redirect('orders.php' . ($filter_cat > 0 ? "?cat_id=$filter_cat" : ""));
}

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : '../' . ltrim($company_logo, '/');

$order_where  = 'o.seller_id = ?';
$order_params = [$user_id];
if ($filter_cat > 0) { $order_where .= ' AND o.category_id = ?'; $order_params[] = $filter_cat; }

$orders = $db->select(
    "SELECT o.*, u.name as buyer_name, u.mobile as buyer_mobile
       FROM orders o JOIN users u ON o.user_id = u.id
      WHERE $order_where
      ORDER BY o.created_at DESC LIMIT 300",
    $order_params
);

/* action-required: something still needs doing on this seller's own orders */
$action_needed = array_values(array_filter($orders, function ($o) {
    return $o['stage'] !== 'cancelled' && $o['stage'] !== 'completed'
        && ((float)$o['due_amount'] > 0 || in_array($o['stage'], ['assigned', 'visit'], true));
}));

$stats = buy_stats($db, ['seller_id' => $user_id]);
$done_today = 0;
try {
    $r = $db->select("SELECT COUNT(*) n FROM orders WHERE seller_id = ? AND stage = 'completed' AND DATE(updated_at) = CURDATE()", [$user_id]);
    $done_today = (int)($r[0]['n'] ?? 0);
} catch (\Throwable $e) {}

function spr($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>Customer Orders - WBMCZ Seller</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=Poppins:wght@300;400;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; } .font-poppins { font-family: 'Poppins', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; }
        [x-cloak] { display: none !important; }
        .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>
<?php
require_once __DIR__ . '/../includes/theme.php';
$__scats = [];
foreach ($categories as $__c) { if (in_array($__c['id'], $seller_cat_ids)) $__scats[] = $__c; }
$__menu = theme_seller_menu($__scats);
theme_open([
    'panel' => 'seller', 'base' => '../', 'title' => 'Customer Orders', 'active' => 'orders',
    'user' => $user ?: ['name' => 'User', 'mobile' => ''], 'wallet' => $wallet_balance,
    'notifs' => $unread_notifs, 'logo' => $company_logo, 'brand' => getSetting('company_name', 'WBMCZ'),
    'menu' => $__menu,
    'state' => "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); }",
]);
?>
<main class="flex-1 overflow-y-auto p-4 md:p-8">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
        <div>
            <h2 class="text-2xl font-bold text-gray-800 mb-1">
                <?php
                if ($filter_cat > 0) {
                    $found = false;
                    foreach ($sidebar_allowed_cats as $c) { if ($c['id'] == $filter_cat) { echo htmlspecialchars($c['title']); $found = true; break; } }
                    if (!$found) echo "Filtered Orders";
                } else { echo "All Customer Orders"; }
                ?>
            </h2>
            <p class="text-gray-500 text-sm">Visit for advance-booked orders, report what you collect, and the office verifies it.</p>
        </div>
    </div>

    <?php if (!empty($_SESSION['flash_success'])): ?>
        <div class="mb-6 bg-teal-50 border border-teal-200 text-teal-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
            <i class="fas fa-check-circle mr-3 text-xl"></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-3 text-xl"></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-6">
        <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">Pending Visit</p><p class="text-2xl font-extrabold text-amber-600 mt-1"><?php echo number_format($stats['pending_visits']); ?></p></div>
        <div class="stat"><p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Cash to Collect</p><p class="text-2xl font-extrabold text-rose-600 mt-1"><?php echo spr($stats['due']); ?></p></div>
        <div class="stat"><p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Completed Today</p><p class="text-2xl font-extrabold text-emerald-600 mt-1"><?php echo number_format($done_today); ?></p></div>
    </div>

    <!-- ============ ACTION REQUIRED ============ -->
    <?php if (!empty($action_needed)): ?>
    <div class="bg-white rounded-2xl border border-amber-200 shadow-sm mb-6 overflow-hidden">
        <div class="px-5 py-3 bg-amber-50 border-b border-amber-100"><p class="text-sm font-extrabold text-amber-800"><i class="fas fa-triangle-exclamation mr-1.5"></i>Action Required (<?php echo count($action_needed); ?>)</p></div>
        <div class="divide-y divide-slate-50">
        <?php foreach ($action_needed as $a): $meta = buy_stage_meta($a['stage']); ?>
            <div class="p-4 flex flex-wrap items-center justify-between gap-3">
                <div>
                    <p class="font-bold text-slate-800 text-sm"><?php echo htmlspecialchars($a['service_name']); ?> <span class="text-slate-400 font-semibold">· <?php echo htmlspecialchars($meta[0]); ?></span></p>
                    <p class="text-xs text-slate-500"><?php echo htmlspecialchars($a['buyer_name']); ?> · <?php echo htmlspecialchars($a['buyer_mobile']); ?></p>
                </div>
                <div class="flex items-center gap-2">
                    <?php if ((float)$a['due_amount'] > 0): ?><span class="text-xs font-bold text-rose-600"><?php echo spr($a['due_amount']); ?> to collect</span><?php endif; ?>
                    <a href="tel:<?php echo htmlspecialchars($a['buyer_mobile']); ?>" class="w-8 h-8 rounded-lg bg-slate-800 text-white inline-flex items-center justify-center"><i class="fas fa-phone"></i></a>
                    <a href="https://wa.me/91<?php echo htmlspecialchars(preg_replace('~\D~', '', $a['buyer_mobile'])); ?>" target="_blank" class="w-8 h-8 rounded-lg inline-flex items-center justify-center" style="background:#25D366;color:#fff"><i class="fab fa-whatsapp"></i></a>
                    <button @click="open(<?php echo (int)$a['id']; ?>)" class="px-3 py-1.5 rounded-lg bg-[#C8901B] text-[#14202f] text-xs font-extrabold">Manage</button>
                </div>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <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">Customer</th>
                        <th class="p-4 font-semibold">Service</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">Manage</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-50">
                    <?php if (!empty($orders)): foreach ($orders as $ord):
                        $meta = buy_stage_meta($ord['stage']);
                        $cancelled = $ord['stage'] === 'cancelled';
                        $badge = $cancelled ? 'bg-rose-100 text-rose-700' : ((float)$ord['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"><?php echo htmlspecialchars($ord['order_code'] ?: ('#' . $ord['id'])); ?></p>
                            <p class="text-xs text-gray-500 mt-1"><?php echo date('d M Y, h:i A', strtotime($ord['created_at'])); ?></p>
                        </td>
                        <td class="p-4">
                            <p class="font-bold text-sm text-gray-800"><?php echo htmlspecialchars($ord['buyer_name']); ?></p>
                            <p class="text-xs text-gray-500"><i class="fas fa-phone-alt text-[10px] mr-1"></i> <?php echo htmlspecialchars($ord['buyer_mobile']); ?></p>
                        </td>
                        <td class="p-4"><span class="font-semibold text-teal-700 text-sm"><?php echo htmlspecialchars($ord['service_name']); ?></span></td>
                        <td class="p-4">
                            <p class="font-bold text-gray-800"><?php echo spr($ord['amount']); ?></p>
                            <p class="text-[10.5px] text-slate-400">Your payout <?php echo spr($ord['seller_payout']); ?><?php if ((float)$ord['due_amount'] > 0): ?> · <span class="text-amber-600 font-bold">Due <?php echo spr($ord['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">
                            <button @click="open(<?php echo (int)$ord['id']; ?>)" class="px-3 py-1.5 rounded-lg bg-slate-800 text-white text-xs font-bold"><i class="fas fa-eye mr-1"></i>View</button>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="6" class="p-12 text-center text-gray-500">
                            <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-300 text-2xl border border-gray-100"><i class="fas fa-box-open"></i></div>
                            <p class="text-lg font-medium">No customer orders found in this category.</p>
                        </td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ============ 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-lg 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">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 to collect</span><span class="font-extrabold text-amber-700" x-text="money(o.due_amount)"></span></div>
                        <div class="row2"><span class="text-slate-500 font-semibold">Your payout</span><span class="font-extrabold text-slate-800" x-text="money(o.seller_payout)"></span></div>
                        <template x-if="o.address"><div class="row2"><span class="text-slate-500 font-semibold">Address</span><span class="font-bold text-slate-800 text-right" x-text="o.address" style="max-width:60%"></span></div></template>
                    </div>

                    <template x-if="Number(o.due_amount) > 0">
                    <form method="POST" class="space-y-2 bg-emerald-50/60 border border-emerald-200 rounded-xl p-4">
                        <p class="text-[11px] font-extrabold uppercase tracking-wide text-emerald-700">Report a collection</p>
                        <input type="hidden" name="order_id" :value="curId">
                        <div class="grid grid-cols-2 gap-2">
                            <input type="number" step="0.01" min="0" name="amount" :max="o.due_amount" placeholder="Amount" class="px-3 py-2 border border-slate-200 rounded-lg text-sm" required>
                            <select name="mode" class="px-3 py-2 border border-slate-200 rounded-lg text-sm">
                                <option value="cash">Cash</option>
                                <option value="online">Online to me (UPI/transfer)</option>
                                <option value="company">Paid to the company directly</option>
                            </select>
                        </div>
                        <input type="text" name="reference" placeholder="Reference / UTR (optional)" class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm">
                        <button type="submit" name="record_collection" class="w-full py-2 bg-emerald-600 text-white font-bold rounded-lg text-sm">Submit for verification</button>
                    </form>
                    </template>

                    <div class="flex flex-wrap gap-2">
                        <form method="POST"><input type="hidden" name="order_id" :value="curId">
                            <button name="mark_visit_scheduled" x-show="o.visit_status === 'pending' || o.visit_status === 'none'" class="px-3 py-2 text-xs font-bold bg-blue-50 text-blue-700 rounded-lg"><i class="fas fa-calendar-check mr-1"></i> Mark Visit Scheduled</button></form>
                        <form method="POST"><input type="hidden" name="order_id" :value="curId">
                            <button name="mark_visit_done" x-show="o.fulfilment === 'visit' && o.visit_status !== 'done'" class="px-3 py-2 text-xs font-bold bg-indigo-50 text-indigo-700 rounded-lg"><i class="fas fa-person-walking mr-1"></i> Mark Visit Done</button></form>
                    </div>

                    <template x-if="(o.collections || []).length">
                        <div>
                            <p class="text-[11px] font-extrabold uppercase tracking-wide text-slate-400 mb-2">What you've reported</p>
                            <template x-for="c in o.collections" :key="c.id">
                                <div class="flex items-center justify-between text-[12.5px] py-1.5 border-b border-slate-50">
                                    <span x-text="c.mode + ' · ' + money(c.amount)"></span>
                                    <span class="px-2 py-0.5 rounded-full text-[10px] font-bold" :class="c.status==='approved' ? 'bg-emerald-100 text-emerald-700' : (c.status==='rejected' ? 'bg-rose-100 text-rose-700' : 'bg-amber-100 text-amber-700')" x-text="c.status"></span>
                                </div>
                            </template>
                        </div>
                    </template>
                </div>
                </template>
            </div>
        </div>
    </div>
</main>
<?php theme_close(); ?>
</html>
