<?php
require_once '../includes/auth.php';
require_once 'functions.php';

$filters = [
    'status' => $_GET['status'] ?? '',
    'payment_status' => $_GET['payment_status'] ?? '',
    'order_type' => $_GET['order_type'] ?? '',
    'payment_method_id' => $_GET['payment_method_id'] ?? '',
    'province' => trim((string)($_GET['province'] ?? '')),
    'pickup_branch' => trim((string)($_GET['pickup_branch'] ?? '')),
    'date_from' => trim((string)($_GET['date_from'] ?? '')),
    'date_to' => trim((string)($_GET['date_to'] ?? '')),
    'quick' => trim((string)($_GET['quick'] ?? '')),
    'keyword' => trim((string)($_GET['keyword'] ?? '')),
];
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$messages = [];
$errors = [];
$adminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : null;

function orders_list_query(array $filters, int $page, array $extra = []): string {
    $params = array_filter([
        'keyword' => $filters['keyword'] ?? '',
        'status' => $filters['status'] ?? '',
        'payment_status' => $filters['payment_status'] ?? '',
        'order_type' => $filters['order_type'] ?? '',
        'payment_method_id' => $filters['payment_method_id'] ?? '',
        'province' => $filters['province'] ?? '',
        'pickup_branch' => $filters['pickup_branch'] ?? '',
        'date_from' => $filters['date_from'] ?? '',
        'date_to' => $filters['date_to'] ?? '',
        'quick' => $filters['quick'] ?? '',
        'page' => $page > 1 ? $page : null,
    ], static fn($v) => $v !== null && $v !== '');
    foreach ($extra as $key => $value) {
        if ($value === null || $value === '') {
            unset($params[$key]);
        } else {
            $params[$key] = $value;
        }
    }
    return http_build_query($params);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $queryBase = $filters;
    $queryBase['page'] = $page;
    admin_require_post_action('orders.list.bulk', 'list.php?' . http_build_query(array_filter($queryBase, static fn($v) => $v !== null && $v !== '')));

    $singleOrderId = (int)($_POST['confirm_payment_order_id'] ?? 0);
    if ($singleOrderId > 0) {
        [$ok, $confirmErrors] = order_confirm_payment($conn, $singleOrderId, $adminId);
        if ($ok) {
            if (function_exists('admin_log_activity')) {
                admin_log_activity('orders.payment_confirmed', 'تأكيد دفع طلب', 'تم تأكيد دفع الطلب من قائمة الطلبات.', 'order', $singleOrderId, ['source' => 'orders_list']);
            }
            $queryBase['msg'] = 'تم تأكيد الدفع للطلب المحدد بنجاح.';
            header('Location: list.php?' . http_build_query(array_filter($queryBase, static fn($v) => $v !== null && $v !== '')));
            exit;
        }
        $errors = array_merge($errors, $confirmErrors ?: ['تعذر تأكيد الدفع لهذا الطلب.']);
    } else {
        $selectedIds = array_values(array_unique(array_filter(array_map('intval', $_POST['selected_orders'] ?? []))));
        $bulkAction = trim((string)($_POST['bulk_action'] ?? ''));

        if (!$selectedIds) {
            $errors[] = 'حدد طلب واحد على الأقل حتى تنفذ الإجراء الجماعي.';
        } elseif ($bulkAction === 'update_status') {
            $bulkStatus = trim((string)($_POST['bulk_status'] ?? ''));
            [$ok, $bulkErrors, $updatedCount] = order_bulk_update_status($conn, $selectedIds, $bulkStatus, $adminId);
            if ($ok && $updatedCount > 0) {
                if (function_exists('admin_log_activity')) {
                    admin_log_activity('orders.bulk_status_updated', 'تحديث جماعي لحالة الطلبات', 'تم تحديث حالة مجموعة طلبات من قائمة الطلبات.', 'orders', 0, ['count' => $updatedCount, 'status' => $bulkStatus, 'ids' => $selectedIds]);
                }
                $queryBase['msg'] = 'تم تحديث ' . $updatedCount . ' طلب بنجاح.';
                header('Location: list.php?' . http_build_query(array_filter($queryBase, static fn($v) => $v !== null && $v !== '')));
                exit;
            }
            $errors = array_merge($errors, $bulkErrors ?: ['ما صار أي تحديث على الطلبات المحددة.']);
        } elseif ($bulkAction === 'print') {
            header('Location: print.php?ids=' . implode(',', $selectedIds));
            exit;
        } elseif ($bulkAction === 'mobile') {
            header('Location: compact.php?ids=' . implode(',', $selectedIds));
            exit;
        } else {
            $errors[] = 'اختر إجراء جماعي صالح.';
        }
    }
}

if (!empty($_GET['msg'])) {
    $messages[] = trim((string)$_GET['msg']);
}

if (($_GET['export'] ?? '') === 'csv') {
    $exportRows = order_list_paginated($conn, $filters, 1, 5000)['items'];
    if (function_exists('admin_log_activity')) {
        admin_log_activity('orders.export_csv', 'تصدير طلبات CSV', 'تم تصدير قائمة الطلبات حسب الفلاتر الحالية.', 'orders', 0, ['filters' => $filters, 'count' => count($exportRows)]);
    }
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="nay-orders-' . date('Ymd-His') . '.csv"');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['id', 'order_number', 'customer_name', 'customer_phone', 'order_type', 'order_status', 'payment_status', 'payment_method', 'province', 'pickup_branch', 'total_amount', 'created_at']);
    foreach ($exportRows as $row) {
        fputcsv($out, [
            (int)($row['id'] ?? 0),
            order_csv_cell(order_display_serial($row)),
            order_csv_cell($row['customer_name'] ?? ''),
            order_csv_cell($row['customer_phone'] ?? ''),
            order_csv_cell(order_type_options()[$row['order_type']] ?? ($row['order_type'] ?? '')),
            order_csv_cell(order_status_label($row['order_status'] ?? '')),
            order_csv_cell(payment_status_options()[$row['payment_status']] ?? ($row['payment_status'] ?? '')),
            order_csv_cell($row['payment_method_name'] ?? ''),
            order_csv_cell($row['province'] ?? ''),
            order_csv_cell($row['pickup_branch'] ?? ''),
            (float)($row['total_amount'] ?? 0),
            order_csv_cell($row['created_at'] ?? ''),
        ]);
    }
    fclose($out);
    exit;
}

$result = order_list_paginated($conn, $filters, $page, $perPage);
$orders = $result['items'];
$paymentMethods = order_payment_methods_for_filter($conn);
$provinces = order_provinces_for_filter($conn);
$pickupBranches = order_pickup_branches_for_filter($conn);
$page_title = 'قائمة الطلبات';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>
<style>
.orders-shell{padding:24px}.orders-hero,.orders-card{background:#fff;border-radius:22px;box-shadow:0 12px 34px rgba(25,68,107,.08);padding:22px;margin-bottom:18px}.orders-hero{display:flex;justify-content:space-between;gap:18px;align-items:flex-start;flex-wrap:wrap}.orders-hero h1{margin:0 0 8px;color:#183b56}.orders-hero p{margin:0;color:#648096;max-width:780px;line-height:1.8}.orders-actions,.bulk-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center}.orders-btn{display:inline-flex;align-items:center;gap:8px;border:0;border-radius:14px;padding:12px 16px;font-weight:800;text-decoration:none;cursor:pointer;background:#edf5fa;color:#183b56}.orders-btn.primary{background:#183b56;color:#fff}.orders-btn.soft{background:#96b8cc;color:#fff}.orders-btn.export{background:#eaf8ef;color:#1c7d47}.quick-filters{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px}.quick-pill{display:inline-flex;align-items:center;gap:7px;border-radius:999px;padding:9px 13px;background:#f2f7fb;color:#33536c;text-decoration:none;font-weight:800;font-size:12px}.quick-pill.active{background:#183b56;color:#fff}.filters-grid{display:grid;grid-template-columns:2fr repeat(4,minmax(150px,1fr));gap:12px;align-items:end}.filters-grid input,.filters-grid select,.bulk-actions select{width:100%;padding:12px 14px;border:1px solid #d7e4ee;border-radius:14px;background:#fff}.field label{display:block;margin-bottom:8px;font-size:13px;font-weight:800;color:#33536c}.filter-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}.bulk-bar{display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:14px}.bulk-bar .summary{font-weight:800;color:#183b56}.orders-table-wrap{overflow:auto;border:1px solid #e6eef5;border-radius:20px;background:#fbfdff}.orders-table{width:100%;border-collapse:separate;border-spacing:0;min-width:1260px}.orders-table thead th{padding:16px 12px;text-align:right;background:#f4f8fc;color:#5f7d95;font-size:12px;font-weight:900;border-bottom:1px solid #e6eef5;position:sticky;top:0;z-index:1;white-space:nowrap}.orders-table tbody td{padding:16px 12px;border-bottom:1px solid #edf3f8;text-align:right;vertical-align:middle;background:#fff}.orders-table tbody tr:hover td{background:#f9fcff}.orders-table tbody tr:last-child td{border-bottom:none}.row-index{font-weight:900;color:#90a4b5;font-size:13px}.order-num{display:inline-flex;align-items:center;justify-content:center;min-width:104px;padding:9px 14px;border-radius:999px;background:#eef5fb;color:#183b56;font-weight:900;text-decoration:none;letter-spacing:.4px}.customer-name{font-weight:900;color:#183b56;margin-bottom:4px}.muted{color:#738aa0;font-size:12px;line-height:1.7}.badge{display:inline-flex;padding:6px 12px;border-radius:999px;font-size:12px;font-weight:800}.badge.neutral{background:#eef5f9;color:#224760}.badge.info{background:#e8f3ff;color:#195f9d}.badge.success{background:#e8f8ef;color:#1e7c49}.badge.warn{background:#fff1eb;color:#aa5121}.badge.soft{background:#f4f0ff;color:#6f49bf}.line-stack{display:flex;flex-direction:column;gap:5px}.table-actions{display:flex;flex-wrap:wrap;gap:8px}.table-actions a,.table-actions button{font-weight:800;text-decoration:none;color:#183b56;background:#f3f8fc;padding:8px 11px;border-radius:12px;border:0;cursor:pointer;font-family:inherit;white-space:nowrap}.table-actions button.confirm-payment{background:#eaf8ef;color:#1c7d47}.money{font-weight:900;color:#183b56;font-size:15px}.message-box,.error-box{padding:14px 16px;border-radius:16px;margin-bottom:14px;font-weight:700}.message-box{background:#eaf8ef;color:#1c7d47}.error-box{background:#fff1f0;color:#a52e2a}.pagination{display:flex;gap:8px;flex-wrap:wrap;justify-content:center;margin-top:18px}.pagination a,.pagination span{min-width:42px;height:42px;border-radius:12px;display:inline-flex;align-items:center;justify-content:center;text-decoration:none;font-weight:800;background:#f3f8fc;color:#183b56}.pagination .current{background:#183b56;color:#fff}.checkbox-lg{width:18px;height:18px}.hidden{display:none!important}.payment-confirm-wrap{margin-top:6px}@media (max-width:1100px){.filters-grid{grid-template-columns:1fr 1fr}.orders-shell{padding:16px}}@media (max-width:760px){.filters-grid{grid-template-columns:1fr}}
</style>
<div class="orders-shell">
    <div class="orders-hero">
        <div>
            <h1>قائمة الطلبات</h1>
            <p>واجهة تشغيل للطلبات مع فلاتر عملية، تحديد متعدد، تأكيد دفع، وتصدير CSV حسب الفلاتر الحالية.</p>
        </div>
        <div class="orders-actions">
            <a class="orders-btn primary" href="<?= e(base_admin_url('orders/create.php')) ?>"><i class="fa-solid fa-plus"></i> طلب جديد</a>
            <a class="orders-btn" href="<?= e(base_admin_url('orders/index.php')) ?>"><i class="fa-solid fa-chart-line"></i> ملخص الطلبات</a>
            <a class="orders-btn export" href="?<?= e(orders_list_query($filters, $result['page'], ['export' => 'csv'])) ?>"><i class="fa-solid fa-file-arrow-down"></i> تصدير CSV</a>
        </div>
    </div>

    <?php foreach ($messages as $message): ?><div class="message-box"><?= e($message) ?></div><?php endforeach; ?>
    <?php foreach ($errors as $error): ?><div class="error-box"><?= e($error) ?></div><?php endforeach; ?>

    <div class="orders-card">
        <div class="quick-filters">
            <a class="quick-pill <?= $filters['quick']===''?'active':'' ?>" href="<?= e(base_admin_url('orders/list.php')) ?>">كل الطلبات</a>
            <?php foreach (order_quick_filter_options() as $key => $label): ?>
                <a class="quick-pill <?= $filters['quick']===$key?'active':'' ?>" href="?<?= e(orders_list_query($filters, 1, ['quick' => $key])) ?>"><?= e($label) ?></a>
            <?php endforeach; ?>
        </div>
        <form method="get">
            <div class="filters-grid">
                <div class="field"><label>بحث سريع</label><input type="text" name="keyword" value="<?= e($filters['keyword']) ?>" placeholder="اسم الزبون / الهاتف / رقم الطلب"></div>
                <div class="field"><label>الحالة</label><select name="status"><option value="">كل الحالات</option><?php foreach (order_status_options() as $key => $label): ?><option value="<?= e($key) ?>" <?= $filters['status'] === $key ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>الدفع</label><select name="payment_status"><option value="">كل حالات الدفع</option><?php foreach (payment_status_options() as $key => $label): ?><option value="<?= e($key) ?>" <?= $filters['payment_status'] === $key ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>طريقة الدفع</label><select name="payment_method_id"><option value="">كل الطرق</option><?php foreach ($paymentMethods as $m): ?><option value="<?= (int)$m['id'] ?>" <?= (string)$filters['payment_method_id'] === (string)$m['id'] ? 'selected' : '' ?>><?= e($m['name']) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>نوع الطلب</label><select name="order_type"><option value="">كل الأنواع</option><?php foreach (order_type_options() as $key => $label): ?><option value="<?= e($key) ?>" <?= $filters['order_type'] === $key ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>المحافظة</label><select name="province"><option value="">كل المحافظات</option><?php foreach ($provinces as $province): ?><option value="<?= e($province) ?>" <?= $filters['province'] === $province ? 'selected' : '' ?>><?= e($province) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>فرع الاستلام</label><select name="pickup_branch"><option value="">كل الفروع</option><?php foreach ($pickupBranches as $branch): ?><option value="<?= e($branch) ?>" <?= $filters['pickup_branch'] === $branch ? 'selected' : '' ?>><?= e($branch) ?></option><?php endforeach; ?></select></div>
                <div class="field"><label>من تاريخ</label><input type="date" name="date_from" value="<?= e($filters['date_from']) ?>"></div>
                <div class="field"><label>إلى تاريخ</label><input type="date" name="date_to" value="<?= e($filters['date_to']) ?>"></div>
                <input type="hidden" name="quick" value="<?= e($filters['quick']) ?>">
            </div>
            <div class="filter-actions">
                <button class="orders-btn primary" type="submit"><i class="fa-solid fa-magnifying-glass"></i> فلترة</button>
                <a class="orders-btn" href="<?= e(base_admin_url('orders/list.php')) ?>"><i class="fa-solid fa-rotate-left"></i> إعادة ضبط</a>
            </div>
        </form>
    </div>

    <div class="orders-card">
        <form method="post" id="bulk-form">
            <?= admin_csrf_input('orders.list.bulk') ?>
            <div class="bulk-bar">
                <div class="summary">المعروض حالياً: <strong><?= number_format((int)$result['total']) ?></strong> طلب — الصفحة <strong><?= (int)$result['page'] ?></strong> من <strong><?= (int)$result['pages'] ?></strong></div>
                <div class="bulk-actions">
                    <select name="bulk_action" id="bulk_action"><option value="">إجراء جماعي</option><option value="update_status">تحديث حالة الطلب</option><option value="print">طباعة المحدد</option><option value="mobile">عرض الموبايل للمحدد</option></select>
                    <select name="bulk_status" id="bulk_status" class="hidden"><option value="">اختر الحالة الجديدة</option><?php foreach (order_status_options() as $key => $label): ?><option value="<?= e($key) ?>"><?= e($label) ?></option><?php endforeach; ?></select>
                    <button class="orders-btn primary" type="submit"><i class="fa-solid fa-bolt"></i> تنفيذ</button>
                </div>
            </div>

            <div class="orders-table-wrap">
                <table class="orders-table">
                    <thead><tr><th><input type="checkbox" class="checkbox-lg" id="select-all"></th><th>ت</th><th>رقم الطلب</th><th>الزبون</th><th>نوع الطلب</th><th>الدفع</th><th>الحالة</th><th>الإجمالي</th><th>المحافظة</th><th>التاريخ</th><th>إجراءات</th></tr></thead>
                    <tbody>
                    <?php if (!$orders): ?>
                        <tr><td colspan="11"><div class="muted">لا توجد طلبات مطابقة للفلاتر الحالية.</div></td></tr>
                    <?php else: ?>
                        <?php $rowNumber = (($result['page'] - 1) * $perPage); foreach ($orders as $order): $rowNumber++; ?>
                            <tr>
                                <td><input type="checkbox" class="checkbox-lg order-check" name="selected_orders[]" value="<?= (int)$order['id'] ?>"></td>
                                <td><span class="row-index"><?= (int)$rowNumber ?></span></td>
                                <td><div class="line-stack"><a class="order-num" href="view.php?id=<?= (int)$order['id'] ?>"><?= e(order_display_serial($order)) ?></a><?php if (!empty($order['promo_code_text'])): ?><span class="muted">بروموكود: <?= e($order['promo_code_text']) ?></span><?php endif; ?></div></td>
                                <td><div class="line-stack"><div class="customer-name"><?= e($order['customer_name']) ?></div><span class="muted"><?= e($order['customer_phone']) ?></span></div></td>
                                <td><div class="line-stack"><span class="badge neutral"><?= e(order_type_options()[$order['order_type']] ?? $order['order_type']) ?></span><?php if (($order['order_type'] ?? '') === 'pickup' && !empty($order['pickup_branch'])): ?><span class="muted">الفرع: <?= e($order['pickup_branch']) ?></span><?php endif; ?><?php if (($order['order_type'] ?? '') === 'preorder' && !empty($order['preorder_expected_at'])): ?><span class="muted">الموعد: <?= e($order['preorder_expected_at']) ?></span><?php endif; ?></div></td>
                                <td><div class="line-stack"><strong><?= e($order['payment_method_name'] ?? '-') ?></strong><span class="muted"><?= e(payment_status_options()[$order['payment_status']] ?? $order['payment_status']) ?></span><?php if (order_can_confirm_payment($order)): ?><div class="payment-confirm-wrap"><button class="confirm-payment" type="submit" name="confirm_payment_order_id" value="<?= (int)$order['id'] ?>" formaction="list.php?<?= e(orders_list_query($filters, $result['page'])) ?>" formmethod="post" onclick="return confirm('تأكيد دفع هذا الطلب وتحويل حالته إلى مدفوع؟');">تأكيد الدفع</button></div><?php endif; ?></div></td>
                                <td><span class="badge <?= e(order_status_badge_variant($order['order_status'])) ?>"><?= e(order_status_label($order['order_status'])) ?></span></td>
                                <td><div class="line-stack"><span class="money"><?= number_format((float)$order['total_amount']) ?></span><span class="muted">د.ع</span></div></td>
                                <td><span class="muted"><?= e($order['province'] ?? '-') ?></span></td>
                                <td><span class="muted"><?= e($order['created_at']) ?></span></td>
                                <td><div class="table-actions"><a href="view.php?id=<?= (int)$order['id'] ?>">عرض</a><a href="update.php?id=<?= (int)$order['id'] ?>">تعديل</a><a href="print.php?id=<?= (int)$order['id'] ?>" target="_blank">طباعة</a><a href="compact.php?id=<?= (int)$order['id'] ?>" target="_blank">موبايل</a></div></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </form>

        <?php if ($result['pages'] > 1): ?>
            <div class="pagination"><?php $prev = max(1, $result['page'] - 1); $next = min($result['pages'], $result['page'] + 1); ?><a href="?<?= e(orders_list_query($filters, $prev)) ?>">‹</a><?php for ($i = max(1, $result['page'] - 2); $i <= min($result['pages'], $result['page'] + 2); $i++): ?><?php if ($i === $result['page']): ?><span class="current"><?= (int)$i ?></span><?php else: ?><a href="?<?= e(orders_list_query($filters, $i)) ?>"><?= (int)$i ?></a><?php endif; ?><?php endfor; ?><a href="?<?= e(orders_list_query($filters, $next)) ?>">›</a></div>
        <?php endif; ?>
    </div>
</div>
<script>
const selectAll=document.getElementById('select-all');const orderChecks=Array.from(document.querySelectorAll('.order-check'));const bulkAction=document.getElementById('bulk_action');const bulkStatus=document.getElementById('bulk_status');if(selectAll){selectAll.addEventListener('change',()=>{orderChecks.forEach(cb=>cb.checked=selectAll.checked);});}orderChecks.forEach(cb=>cb.addEventListener('change',()=>{if(!selectAll)return;selectAll.checked=orderChecks.length>0&&orderChecks.every(item=>item.checked);}));function syncBulkStatus(){bulkStatus.classList.toggle('hidden',bulkAction.value!=='update_status');}bulkAction.addEventListener('change',syncBulkStatus);syncBulkStatus();document.getElementById('bulk-form').addEventListener('submit',function(e){const active=document.activeElement;if(active&&active.name==='confirm_payment_order_id'){return;}if(!bulkAction.value){e.preventDefault();alert('اختر الإجراء الجماعي أولاً.');return;}if(bulkAction.value==='update_status'&&!bulkStatus.value){e.preventDefault();alert('اختر الحالة الجديدة حتى يتم التحديث.');}});
</script>
<?php require_once '../includes/footer.php'; ?>
