<?php include __DIR__ . '/../header.php'; ?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<!-- ══════════════════════════════════════════════════
     PAGE HEADER
══════════════════════════════════════════════════ -->
<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold">
            <i class="bi bi-receipt me-2 text-primary"></i>
            <?= __('orders.title','Orders Management') ?>
        </h3>
        <p class="text-muted mb-0 small"><?= __('orders.quick_view','Quick view of all orders') ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="/admin/orders/bulk-confirm" class="btn btn-primary btn-sm">
            <i class="bi bi-send-check me-1"></i>
            <?= __('bulk_confirm.nav_button', 'Bulk Confirmation') ?>
        </a>
        <a href="/admin/orders/export" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-filetype-csv me-1"></i>
            <?= __('orders.export_csv','Export CSV') ?>
        </a>
    </div>
</div>

<?php
use Core\App\Support\OrderPricing;
/* ── Status config ── */
$statuses = [
    'all'       => ['label' => __('orders.all','All'),        'color' => 'secondary', 'icon' => 'bi-list-ul'],
    'pending'   => ['label' => __('orders.pending','Pending'), 'color' => 'warning',   'icon' => 'bi-hourglass-split'],
    'confirmed' => ['label' => __('orders.confirmed','Confirmed'),'color'=>'success',  'icon' => 'bi-check-circle-fill'],
    'rejected'  => ['label' => __('orders.rejected','Rejected'), 'color' => 'danger',  'icon' => 'bi-x-circle-fill'],
    'returned'  => ['label' => __('orders.returned','Returned'), 'color' => 'info',    'icon' => 'bi-arrow-return-left'],
];

/* ── Count per status (from current page items) ── */
$counts = ['all' => (int)($totalOrders ?? count($orders ?? []))];
foreach ($orders ?? [] as $o) {
    $s = $o['order_status'];
    $counts[$s] = ($counts[$s] ?? 0) + 1;
}
$currentPage  = (int)($currentPage ?? 1);
$totalPages   = (int)($totalPages ?? 1);
?>

<!-- ══════════════════════════════════════════════════
     STATUS KPI TABS
══════════════════════════════════════════════════ -->
<?php
$_cardTopColors = [
    'pending'   => '#ffc107',
    'confirmed' => '#198754',
    'rejected'  => '#dc3545',
    'returned'  => '#0dcaf0',
];
?>
<div class="row g-3 mb-4">
    <?php foreach ($statuses as $key => $s):
        if ($key === 'all') continue;
        $_topColor = $_cardTopColors[$key] ?? '#6c757d';
    ?>
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm h-100 filter-card" data-filter="<?= $key ?>"
             style="cursor:pointer;transition:box-shadow .2s;border-top:3px solid <?= $_topColor ?> !important">
            <div class="card-body px-4 py-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-<?= $s['color'] ?>-subtle"
                         style="width:42px;height:42px">
                        <i class="bi <?= $s['icon'] ?> fs-5 text-<?= $s['color'] ?>"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1"><?= $counts[$key] ?? 0 ?></div>
                <div class="text-muted small"><?= $s['label'] ?></div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- ══════════════════════════════════════════════════
     FILTER BAR
══════════════════════════════════════════════════ -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-3">
        <div class="d-flex flex-wrap gap-2 align-items-center">
            <span class="text-muted small fw-semibold me-1"><?= __('orders.filter_by','Filter:') ?></span>
            <?php foreach ($statuses as $key => $s): ?>
            <button type="button"
                    class="btn btn-sm btn-outline-<?= $s['color'] ?> filter-btn <?= $key === 'all' ? 'active' : '' ?>"
                    data-filter="<?= $key ?>">
                <i class="bi <?= $s['icon'] ?> me-1"></i>
                <?= $s['label'] ?>
                <span class="badge bg-<?= $s['color'] ?> ms-1 rounded-pill"><?= $counts[$key] ?? 0 ?></span>
            </button>
            <?php endforeach; ?>

            <div class="ms-auto d-flex gap-2">
                <input type="text" id="orderSearch" class="form-control form-control-sm"
                       style="width:200px"
                       placeholder="<?= __('orders.search_placeholder','Search name or phone...') ?>">
            </div>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════
     ORDERS TABLE
══════════════════════════════════════════════════ -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-semibold">
            <i class="bi bi-table me-2 text-muted"></i>
            <span id="tableTitle"><?= __('orders.all','All Orders') ?></span>
        </h6>
        <span class="badge bg-secondary rounded-pill" id="tableCount"><?= $counts['all'] ?></span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0" id="ordersTable">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3">#</th>
                        <th><?= __('orders.customer','Customer') ?></th>
                        <th><?= __('orders.order_summary','Order') ?></th>
                        <th><?= __('orders.status','Status') ?></th>
                        <th><?= __('orders.created_at','Date') ?></th>
                        <th class="text-center pe-3"><?= __('orders.actions','Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!empty($orders)):
                    usort($orders, fn($a,$b) => strtotime($b['created_at']) <=> strtotime($a['created_at']));
                    foreach ($orders as $order):
                        $extra         = is_array($order['extra']) ? $order['extra'] : (json_decode($order['extra'],true) ?? []);
                        $pricing       = OrderPricing::pricing($order);
                        $currency      = $pricing['currency'] ?? '';
                        $productTotal  = $pricing['products_total'] ?? 0;
                        $shippingPrice = $pricing['shipping_price'] ?? 0;
                        $total         = $pricing['total'] ?? OrderPricing::effectiveTotal($order);
                        $status        = $order['order_status'];
                        $isNew         = $status === 'pending';
                        $trackingNumber= $extra['shipping']['tracking'] ?? null;
                        $stockDeducted = !empty($extra['inventory']['stock_deducted']) && empty($extra['inventory']['stock_restored']);
                        $shippingProvider = $extra['shipping']['provider'] ?? null;

                        $statusCfg = [
                            'pending'   => ['color'=>'warning', 'icon'=>'bi-hourglass-split',   'label'=>__('orders.pending','Pending')],
                            'confirmed' => ['color'=>'success', 'icon'=>'bi-check-circle-fill',  'label'=>__('orders.confirmed','Confirmed')],
                            'rejected'  => ['color'=>'danger',  'icon'=>'bi-x-circle-fill',      'label'=>__('orders.rejected','Rejected')],
                            'returned'  => ['color'=>'info',    'icon'=>'bi-arrow-return-left',  'label'=>__('orders.returned','Returned')],
                        ];
                        $sc = $statusCfg[$status] ?? ['color'=>'secondary','icon'=>'bi-circle','label'=>$status];
                ?>
                <tr data-status="<?= $status ?>"
                    data-search="<?= htmlspecialchars(strtolower($order['full_name'].' '.$order['phone'])) ?>">

                    <!-- # -->
                    <td class="ps-3">
                        <a href="/admin/orders/view/<?= (int)$order['id'] ?>"
                           class="fw-bold text-decoration-none text-primary">
                            #<?= (int)$order['id'] ?>
                        </a>
                        <?php if ($isNew): ?>
                            <span class="badge bg-danger ms-1" style="font-size:.65rem">
                                <?= __('orders.new','NEW') ?>
                            </span>
                        <?php endif; ?>
                    </td>

                    <!-- Customer -->
                    <td>
                        <div class="fw-semibold small"><?= htmlspecialchars($order['full_name']) ?></div>
                        <div class="text-muted" style="font-size:.75rem"><?= htmlspecialchars($order['phone']) ?></div>
                    </td>

                    <!-- Summary -->
                    <td>
                        <?php $_productName = $extra['product']['name'] ?? null; ?>
                        <?php if ($_productName): ?>
                        <div class="fw-semibold small text-dark mb-1" style="max-width:180px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" title="<?= htmlspecialchars($_productName) ?>">
                            <?= htmlspecialchars($_productName) ?>
                        </div>
                        <?php endif; ?>
                        <div class="fw-bold small text-primary"><?= number_format((float)$total) ?> <span class="text-muted fw-normal"><?= $currency ?></span></div>
                        <div class="text-muted" style="font-size:.72rem">
                            <?= __('orders.product_price','Product') ?>: <?= number_format((float)$productTotal) ?>
                            &nbsp;·&nbsp;
                            <?= __('orders.shipping','Shipping') ?>: <?= number_format((float)$shippingPrice) ?>
                        </div>
                        <?php if ($trackingNumber): ?>
                        <span class="badge bg-primary-subtle text-primary border border-primary-subtle mt-1" style="font-size:.68rem">
                            <i class="bi bi-truck me-1"></i><?= htmlspecialchars($trackingNumber) ?>
                        </span>
                        <?php endif; ?>
                    </td>

                    <!-- Status -->
                    <td>
                        <span class="badge bg-<?= $sc['color'] ?>-subtle text-<?= $sc['color'] ?> border border-<?= $sc['color'] ?>-subtle px-2 py-1">
                            <i class="bi <?= $sc['icon'] ?> me-1"></i>
                            <?= $sc['label'] ?>
                        </span>
                    </td>

                    <!-- Date -->
                    <td class="text-muted" style="font-size:.78rem;white-space:nowrap">
                        <?= date('d/m/Y', strtotime($order['created_at'])) ?><br>
                        <span class="text-muted"><?= date('H:i', strtotime($order['created_at'])) ?></span>
                    </td>

                    <!-- Actions -->
                    <td class="text-center pe-3">
                        <div class="d-flex gap-1 justify-content-center flex-nowrap">
                            <a href="/admin/orders/view/<?= (int)$order['id'] ?>"
                               class="btn btn-sm btn-outline-primary" title="<?= __('orders.view','View') ?>">
                                <i class="bi bi-eye"></i>
                            </a>

                            <?php if ($status === 'pending'): ?>
                                <a href="/admin/orders/prepare-shipping/<?= (int)$order['id'] ?>"
                                   class="btn btn-sm btn-success" title="<?= __('orders.confirm_and_ship','Confirm & Ship') ?>">
                                    <i class="bi bi-truck me-1"></i><?= __('orders.confirm_and_ship','Confirm') ?>
                                </a>
                                <form method="POST" action="/admin/orders/status/<?= (int)$order['id'] ?>"
                                      onsubmit="return confirm('<?= __('orders.confirm_reject','Reject this order?') ?>')">
                                    <?= \Core\System\Csrf::field() ?>
                                    <input type="hidden" name="status" value="rejected">
                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="<?= __('orders.reject','Reject') ?>">
                                        <i class="bi bi-x-lg"></i>
                                    </button>
                                </form>
                            <?php elseif ($status === 'confirmed' && !$trackingNumber): ?>
                                <a href="/admin/orders/prepare-shipping/<?= (int)$order['id'] ?>"
                                   class="btn btn-sm btn-outline-success" title="<?= __('orders.prepare_shipping','Prepare Shipping') ?>">
                                    <i class="bi bi-truck"></i>
                                </a>
                            <?php endif; ?>

                            <?php if (($trackingNumber || $stockDeducted) && !in_array($status, ['returned','rejected'], true)): ?>
                                <button type="button" class="btn btn-sm btn-outline-secondary" disabled title="<?= __('orders.delete_requires_return','Shipped orders cannot be deleted before they are returned or rejected.') ?>">
                                    <i class="bi bi-lock"></i>
                                </button>
                            <?php else: ?>
                            <form method="post" action="/admin/orders/delete/<?= (int)$order['id'] ?>" class="d-inline" onsubmit="return confirm('<?= __('orders.confirm_delete','Delete this order?') ?>')">
                                <?= \Core\System\Csrf::field() ?>
                                <button type="submit" class="btn btn-sm btn-outline-danger" title="<?= __('orders.delete','Delete') ?>">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </td>

                </tr>
                <?php endforeach; else: ?>
                <tr>
                    <td colspan="6" class="text-center text-muted py-5">
                        <i class="bi bi-inbox display-4 d-block mb-2 opacity-50"></i>
                        <?= __('orders.no_orders','No orders found') ?>
                    </td>
                </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</div>
</section>
</div>

<script>
(function () {
    const btnFilters  = document.querySelectorAll('.filter-btn');
    const cardFilters = document.querySelectorAll('.filter-card');
    const rows        = document.querySelectorAll('#ordersTable tbody tr');
    const searchInput = document.getElementById('orderSearch');
    const tableTitle  = document.getElementById('tableTitle');
    const tableCount  = document.getElementById('tableCount');

    const labels = <?= json_encode(array_map(fn($s) => $s['label'], $statuses)) ?>;

    let activeFilter = 'all';

    function applyFilters() {
        const q = searchInput.value.toLowerCase().trim();
        let visible = 0;

        rows.forEach(function(row) {
            const statusMatch = activeFilter === 'all' || row.dataset.status === activeFilter;
            const searchMatch = !q || (row.dataset.search || '').includes(q);
            const show = statusMatch && searchMatch;
            row.style.display = show ? '' : 'none';
            if (show) visible++;
        });

        tableCount.textContent = visible;
        tableTitle.textContent = labels[activeFilter] || '<?= __('orders.all','All Orders') ?>';
    }

    btnFilters.forEach(function(btn) {
        btn.addEventListener('click', function() {
            btnFilters.forEach(b => b.classList.remove('active'));
            cardFilters.forEach(c => {
                c.style.borderLeftColor = 'transparent';
                c.style.boxShadow = '';
            });
            this.classList.add('active');
            activeFilter = this.dataset.filter;

            // highlight matching card
            cardFilters.forEach(c => {
                if (c.dataset.filter === activeFilter) {
                    c.style.borderLeftColor = 'var(--bs-primary)';
                    c.style.boxShadow = '0 4px 16px rgba(0,0,0,.08)';
                }
            });

            applyFilters();
        });
    });

    cardFilters.forEach(function(card) {
        card.addEventListener('click', function() {
            const f = this.dataset.filter;
            btnFilters.forEach(b => {
                b.classList.toggle('active', b.dataset.filter === f);
            });
            cardFilters.forEach(c => {
                c.style.borderLeftColor = c.dataset.filter === f ? 'var(--bs-primary)' : 'transparent';
                c.style.boxShadow = c.dataset.filter === f ? '0 4px 16px rgba(0,0,0,.08)' : '';
            });
            activeFilter = f;
            applyFilters();
        });
    });

    searchInput.addEventListener('input', applyFilters);
})();
</script>

<?php if (($totalPages ?? 1) > 1): ?>
<div class="d-flex justify-content-center align-items-center gap-2 py-3 px-4">
    <?php
    $baseUrl = '/admin/orders';
    $qs = $_GET;
    ?>
    <?php if ($currentPage > 1): ?>
        <?php $qs['page'] = $currentPage - 1; ?>
        <a href="<?= $baseUrl . '?' . http_build_query($qs) ?>" class="btn btn-sm btn-outline-secondary">
            &laquo; <?= __('pagination.prev', 'Previous') ?>
        </a>
    <?php endif; ?>

    <span class="text-muted small">
        <?= __('pagination.page_of', 'Page') ?> <?= $currentPage ?> / <?= $totalPages ?>
        &nbsp;(<?= number_format($totalOrders ?? 0) ?> <?= __('orders.total_count', 'orders') ?>)
    </span>

    <?php if ($currentPage < $totalPages): ?>
        <?php $qs['page'] = $currentPage + 1; ?>
        <a href="<?= $baseUrl . '?' . http_build_query($qs) ?>" class="btn btn-sm btn-outline-secondary">
            <?= __('pagination.next', 'Next') ?> &raquo;
        </a>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php include __DIR__ . '/../footer.php'; ?>