<?= $this->extend('layouts/admin_layout') ?>

<?= $this->section('content') ?>

<style>
    /* ===== MODERN SAAS DESIGN SYSTEM TOKENS ===== */
    :root {
        --bg-body: #f8fafc;
        --bg-card: #ffffff;
        --bg-accent: #f1f5f9;
        --bg-input: #ffffff;
        --border-color: #e2e8f0;
        --border-hover: #cbd5e1;
        --text-main: #0f172a;
        --text-sub: #64748b;
        --primary: #4f46e5;
        --primary-hover: #4338ca;
        --primary-light: rgba(79, 70, 229, 0.08);
        --success: #10b981;
        --warning: #f59e0b;
        --danger: #ef4444;
        --info: #06b6d4;
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.05);
        --radius-lg: 16px;
        --radius-md: 12px;
        --radius-sm: 8px;
        --transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    }

    @media (prefers-color-scheme: dark) {
        :root {
            --bg-body: #0b0f19;
            --bg-card: #151e2e;
            --bg-accent: #1e293b;
            --bg-input: #0f172a;
            --border-color: #243044;
            --border-hover: #334155;
            --text-main: #f8fafc;
            --text-sub: #94a3b8;
            --primary-light: rgba(79, 70, 229, 0.18);
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
        }
    }

    [data-bs-theme="dark"] {
        --bg-body: #0b0f19;
        --bg-card: #151e2e;
        --bg-accent: #1e293b;
        --bg-input: #0f172a;
        --border-color: #243044;
        --border-hover: #334155;
        --text-main: #f8fafc;
        --text-sub: #94a3b8;
        --primary-light: rgba(79, 70, 229, 0.18);
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
    }

    body, .content-wrapper, .main-content, .content, .page-content, main, .order-dashboard-workspace {
        background-color: var(--bg-body) !important;
        color: var(--text-main) !important;
        transition: var(--transition);
    }

    /* Card Premium Styling */
    .card-premium {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-sm);
        transition: var(--transition);
    }

    /* Stat Cards Upgrade */
    .stat-card {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        padding: 1.25rem;
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .stat-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-lg);
        border-color: var(--border-hover);
    }

    .stat-card .stat-icon {
        width: 44px;
        height: 44px;
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }

    /* Table Container & Aesthetics */
    .table-container {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-md);
        overflow: hidden;
    }

    .custom-table {
        margin-bottom: 0;
        width: 100%;
        color: var(--text-main);
    }

    .custom-table thead {
        background: var(--bg-accent);
        border-bottom: 1px solid var(--border-color);
    }

    .custom-table thead th {
        font-size: 0.72rem;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        font-weight: 700;
        color: var(--text-sub);
        padding: 0.85rem 1rem;
        border: none;
    }

    .custom-table tbody tr {
        border-bottom: 1px solid var(--border-color);
        transition: var(--transition);
    }

    .custom-table tbody tr:last-child {
        border-bottom: none;
    }

    .custom-table tbody tr:hover {
        background-color: var(--bg-accent) !important;
    }

    .custom-table td {
        padding: 0.9rem 1rem !important;
        vertical-align: middle;
    }

    /* Avatar Initial */
    .avatar-circle {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: var(--primary-light);
        color: var(--primary);
        font-weight: 700;
        font-size: 0.85rem;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    /* Action Buttons */
    .btn-action-group .btn {
        padding: 0.35rem 0.6rem;
        font-size: 0.8rem;
        border-radius: var(--radius-sm);
        transition: var(--transition);
    }

    /* Soft Badges Custom */
    .badge-soft-success { background: rgba(16, 185, 129, 0.12); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); }
    .badge-soft-warning { background: rgba(245, 158, 11, 0.12); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.2); }
    .badge-soft-danger  { background: rgba(239, 68, 68, 0.12); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); }
    .badge-soft-primary { background: rgba(79, 70, 229, 0.12); color: #4f46e5; border: 1px solid rgba(79, 70, 229, 0.2); }
    .badge-soft-secondary { background: rgba(100, 116, 139, 0.12); color: #64748b; border: 1px solid rgba(100, 116, 139, 0.2); }

    /* Form Controls Override */
    .form-control, .form-select {
        background-color: var(--bg-input) !important;
        border-color: var(--border-color) !important;
        color: var(--text-main) !important;
        font-size: 0.85rem;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary) !important;
        box-shadow: 0 0 0 3px var(--primary-light) !important;
    }

    /* Pagination Styling */
    .pagination .page-link {
        border: 1px solid var(--border-color) !important;
        border-radius: var(--radius-sm) !important;
        margin: 0 2px;
        color: var(--text-sub);
        background: var(--bg-card);
        font-size: 0.8rem;
        font-weight: 500;
        padding: 0.4rem 0.75rem;
        transition: var(--transition);
    }

    .pagination .page-link:hover {
        background: var(--bg-accent);
        color: var(--primary);
    }

    .pagination .page-item.active .page-link {
        background: var(--primary) !important;
        color: #ffffff !important;
        border-color: var(--primary) !important;
        box-shadow: var(--shadow-sm);
    }

    .pagination .page-item.disabled .page-link {
        opacity: 0.5;
        background: var(--bg-card);
    }
</style>

<div class="container-fluid py-4 order-dashboard-workspace">
    
    <!-- PAGE HEADER -->
    <div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center mb-4 gap-3">
        <div>
            <h3 class="fw-bold mb-0 text-main"><?= esc($title ?? 'Order Management') ?></h3>
            <p class="text-sub small mb-0 mt-0.5">Monitoring operasional, pemesanan CNC, dan alur pembayaran kasir.</p>
        </div>
        <div>
            <a href="<?= base_url('admin/orders/create') ?>" class="btn btn-primary px-3.5 py-2 rounded-3 shadow-sm fw-semibold d-inline-flex align-items-center gap-2">
                <i class="bi bi-plus-lg fs-6"></i> Order Baru
            </a>
        </div>
    </div>

    <!-- FLASH MESSAGES -->
    <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show rounded-3 shadow-sm border-0 mb-4" role="alert">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-check-circle-fill fs-5"></i>
                <div><?= session()->getFlashdata('success') ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- STATISTIK RINGKASAN -->
    <div class="row g-3 mb-4">
        <!-- Total Order -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="stat-card shadow-sm d-flex align-items-center justify-content-between">
                <div>
                    <div class="small fw-bold text-uppercase text-sub mb-1" style="font-size: 0.7rem; letter-spacing: 0.05em;">Total Order</div>
                    <div class="h3 fw-bolder mb-0 text-main"><?= number_format((float)($totalOrder ?? 0)) ?></div>
                </div>
                <div class="stat-icon bg-primary-subtle text-primary">
                    <i class="bi bi-receipt"></i>
                </div>
            </div>
        </div>

        <!-- Belum Bayar -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="stat-card shadow-sm d-flex align-items-center justify-content-between">
                <div>
                    <div class="small fw-bold text-uppercase text-sub mb-1" style="font-size: 0.7rem; letter-spacing: 0.05em;">Belum Bayar</div>
                    <div class="h3 fw-bolder mb-0 text-danger"><?= number_format((float)($totalUnpaid ?? 0)) ?></div>
                </div>
                <div class="stat-icon bg-danger-subtle text-danger">
                    <i class="bi bi-exclamation-circle-fill"></i>
                </div>
            </div>
        </div>

        <!-- DP / Partial -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="stat-card shadow-sm d-flex align-items-center justify-content-between">
                <div>
                    <div class="small fw-bold text-uppercase text-sub mb-1" style="font-size: 0.7rem; letter-spacing: 0.05em;">DP / Partial</div>
                    <div class="h3 fw-bolder mb-0 text-warning"><?= number_format((float)($totalPartial ?? 0)) ?></div>
                </div>
                <div class="stat-icon bg-warning-subtle text-warning">
                    <i class="bi bi-pie-chart-fill"></i>
                </div>
            </div>
        </div>

        <!-- Lunas -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="stat-card shadow-sm d-flex align-items-center justify-content-between">
                <div>
                    <div class="small fw-bold text-uppercase text-sub mb-1" style="font-size: 0.7rem; letter-spacing: 0.05em;">Lunas (Paid)</div>
                    <div class="h3 fw-bolder mb-0 text-success"><?= number_format((float)($totalPaid ?? 0)) ?></div>
                </div>
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="bi bi-check-circle-fill"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- FILTER & TABLE AREA -->
    <div class="table-container p-3.5">
        
        <!-- Filter Action Bar -->
        <div class="row g-2 mb-3.5 align-items-center">
            <div class="col-12 col-md-5 col-lg-4">
                <div class="input-group">
                    <span class="input-group-text bg-transparent border-end-0 text-sub"><i class="bi bi-search"></i></span>
                    <input type="text" id="search" class="form-control border-start-0 ps-1 rounded-end-3" placeholder="Cari nomor order, customer, hp...">
                </div>
            </div>
            <div class="col-6 col-md-3 col-lg-2">
                <select id="filterType" class="form-select rounded-3">
                    <option value="">Semua Tipe</option>
                    <option value="ready">Ready Stock</option>
                    <option value="po">Pre-Order (PO)</option>
                </select>
            </div>
            <div class="col-6 col-md-3 col-lg-2">
                <select id="filterPayment" class="form-select rounded-3">
                    <option value="">Semua Pembayaran</option>
                    <option value="paid">Lunas (Paid)</option>
                    <option value="partial">Partial (DP)</option>
                    <option value="unpaid">Belum Bayar</option>
                </select>
            </div>
            <div class="col-12 col-md-1 col-lg-2 text-md-end">
                <button type="button" class="btn btn-outline-secondary btn-sm rounded-3 py-2 px-3 w-100 w-md-auto text-nowrap" onclick="resetFilters()" title="Reset Filter">
                    <i class="bi bi-arrow-counterclockwise"></i> Reset
                </button>
            </div>
        </div>

        <!-- Table Stream -->
        <div class="table-responsive">
            <table class="table custom-table align-middle" id="orderTable">
                <thead>
                    <tr>
                        <th class="ps-3">Order #</th>
                        <th>Pelanggan</th>
                        <th>Tipe</th>
                        <th>Rincian Finansial</th>
                        <th>Status Order</th>
                        <th class="text-end pe-3">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($orders) && is_array($orders)): foreach($orders as $order): ?>
                        <?php 
                            $phone = preg_replace('/[^0-9]/', '', $order['customer_phone'] ?? '');
                            $waLink = $phone ? 'https://wa.me/' . (str_starts_with($phone, '0') ? '62' . substr($phone, 1) : $phone) : null;
                            $initial = strtoupper(substr(trim($order['customer_name'] ?? 'C'), 0, 1));
                        ?>
                        <tr class="order-row">
                            <!-- Order Number & Target Date -->
                            <td class="ps-3">
                                <div class="fw-bold text-primary">#<?= esc($order['order_number']) ?></div>
                                <div class="small text-sub d-flex align-items-center gap-1 mt-0.5" style="font-size: 0.78rem;">
                                    <i class="bi bi-calendar3 opacity-75"></i> 
                                    <?= !empty($order['target_date']) ? esc($order['target_date']) : '-' ?>
                                </div>
                            </td>

                            <!-- Customer Info -->
                            <td>
                                <div class="d-flex align-items-center gap-2.5">
                                    <div class="avatar-circle"><?= $initial ?></div>
                                    <div>
                                        <div class="fw-semibold text-main" style="font-size: 0.88rem;"><?= esc($order['customer_name']) ?></div>
                                        <?php if($waLink): ?>
                                            <a href="<?= $waLink ?>" target="_blank" class="small text-sub text-decoration-none d-inline-flex align-items-center gap-1 hover-primary" style="font-size: 0.78rem;">
                                                <i class="bi bi-whatsapp text-success"></i> <?= esc($order['customer_phone']) ?>
                                            </a>
                                        <?php else: ?>
                                            <span class="small text-sub" style="font-size: 0.78rem;"><?= esc($order['customer_phone'] ?? '-') ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>

                            <!-- Order Type -->
                            <td>
                                <?php if(($order['order_type'] ?? '') === 'ready'): ?>
                                    <span class="badge badge-soft-success rounded-pill px-2.5 py-1 font-monospace">READY</span>
                                <?php else: ?>
                                    <span class="badge badge-soft-warning rounded-pill px-2.5 py-1 font-monospace">PO</span>
                                <?php endif; ?>
                            </td>

                            <!-- Financial Breakdown -->
                            <td>
                                <div class="fw-bold text-main" style="font-size: 0.85rem;">
                                    Rp <?= number_format((float)($order['total'] ?? 0), 0, ',', '.') ?>
                                </div>
                                <?php $remaining = (float)($order['remaining_amount'] ?? 0); ?>
                                <?php if($remaining > 0): ?>
                                    <div class="small text-danger fw-medium" style="font-size: 0.76rem;">
                                        Sisa: Rp <?= number_format($remaining, 0, ',', '.') ?>
                                    </div>
                                <?php else: ?>
                                    <div class="small text-success fw-medium" style="font-size: 0.76rem;">
                                        <i class="bi bi-check-all"></i> Lunas
                                    </div>
                                <?php endif; ?>
                            </td>

                            <!-- Status Payment & Order -->
                            <td>
                                <div class="d-flex flex-column align-items-start gap-1">
                                    <!-- Payment Status Pill -->
                                    <?php 
                                        $payStatus = strtolower($order['payment_status'] ?? 'unpaid');
                                        $payClass = $payStatus === 'paid' ? 'badge-soft-success' : ($payStatus === 'partial' ? 'badge-soft-warning' : 'badge-soft-danger');
                                        $payText  = $payStatus === 'paid' ? 'Paid' : ($payStatus === 'partial' ? 'Partial' : 'Unpaid');
                                    ?>
                                    <span class="badge <?= $payClass ?> rounded-pill px-2.5 py-0.5" style="font-size: 0.7rem;">
                                        <?= $payText ?>
                                    </span>

                                    <!-- Order Status Pill -->
                                    <span class="badge badge-soft-secondary rounded-pill px-2.5 py-0.5" style="font-size: 0.7rem;">
                                        <?= ucwords(str_replace('_', ' ', $order['order_status'] ?? 'draft')) ?>
                                    </span>
                                </div>
                            </td>

                            <!-- Action Buttons -->
                            <td class="text-end pe-3">
                                <div class="btn-group btn-action-group shadow-sm" role="group">
                                    <a href="<?= base_url('admin/orders/show/' . $order['id_order']) ?>" class="btn btn-outline-secondary" title="Detail Order">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                    <a href="<?= base_url('admin/orders/edit/' . $order['id_order']) ?>" class="btn btn-outline-secondary" title="Edit Order">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <a href="<?= base_url('admin/payments/create/' . $order['id_order']) ?>" class="btn btn-outline-success" title="Tambah Pembayaran">
                                        <i class="bi bi-wallet2"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; else: ?>
                        <tr id="emptyRowStatic">
                            <td colspan="6" class="text-center py-5 text-sub">
                                <i class="bi bi-inbox fs-2 d-block opacity-40 mb-2"></i>
                                Belum ada data order yang terdaftar.
                            </td>
                        </tr>
                    <?php endif; ?>

                    <!-- Dynamic JS Empty Search State -->
                    <tr id="noMatchingDataRow" class="d-none">
                        <td colspan="6" class="text-center py-5 text-sub">
                            <i class="bi bi-search fs-2 d-block opacity-40 mb-2"></i>
                            <strong>Tidak ada order yang cocok.</strong>
                            <p class="small text-sub mb-0 mt-1">Coba sesuaikan kata kunci pencarian atau reset filter Anda.</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- Table Footer Pagination -->
        <div class="p-3 border-top border-color d-flex flex-column flex-sm-row justify-content-between align-items-center gap-3">
            <div class="text-sub small" id="tableInfo">Menampilkan data order...</div>
            <nav aria-label="Order pagination">
                <ul class="pagination pagination-sm mb-0" id="paginationControls"></ul>
            </nav>
        </div>
    </div>
</div>

<!-- JAVASCRIPT ENGINE FOR SEARCH & PAGINATION -->
<script>
    const rowsPerPage = 10;
    let currentPage = 1;
    
    const rows = Array.from(document.querySelectorAll('#orderTable tbody tr.order-row'));
    const searchInput = document.getElementById('search');
    const typeSelect = document.getElementById('filterType');
    const paySelect = document.getElementById('filterPayment');
    const noMatchRow = document.getElementById('noMatchingDataRow');

    function renderTable(page = 1) {
        currentPage = page;
        const searchVal = searchInput.value.toLowerCase().trim();
        const typeVal = typeSelect.value.toLowerCase().trim();
        const payVal = paySelect.value.toLowerCase().trim();

        // Filtering logic
        const filteredRows = rows.filter(row => {
            const rowText = row.innerText.toLowerCase();
            const matchesSearch = searchVal === '' || rowText.includes(searchVal);
            
            // Cell 2 is Type, Cell 4 is Payment status
            const typeCellText = row.cells[2] ? row.cells[2].innerText.toLowerCase() : '';
            const payCellText = row.cells[4] ? row.cells[4].innerText.toLowerCase() : '';

            const matchesType = typeVal === '' || typeCellText.includes(typeVal);
            const matchesPay = payVal === '' || payCellText.includes(payVal);

            return matchesSearch && matchesType && matchesPay;
        });

        // Hide all data rows
        rows.forEach(r => r.style.display = 'none');

        // Toggle Empty Search Result
        if (filteredRows.length === 0 && rows.length > 0) {
            noMatchRow.classList.remove('d-none');
        } else {
            noMatchRow.classList.add('d-none');
        }

        // Calculate pagination slicing
        const totalItems = filteredRows.length;
        const totalPages = Math.ceil(totalItems / rowsPerPage) || 1;
        
        if (currentPage > totalPages) currentPage = totalPages;

        const startIdx = (currentPage - 1) * rowsPerPage;
        const endIdx = startIdx + rowsPerPage;

        filteredRows.slice(startIdx, endIdx).forEach(r => r.style.display = '');

        // Update Info Text
        const infoEl = document.getElementById('tableInfo');
        if (totalItems > 0) {
            const fromNum = startIdx + 1;
            const toNum = Math.min(endIdx, totalItems);
            infoEl.innerText = `Menampilkan ${fromNum} - ${toNum} dari ${totalItems} order`;
        } else {
            infoEl.innerText = 'Menampilkan 0 order';
        }

        // Render Pagination Control Buttons
        renderPagination(totalPages);
    }

    function renderPagination(totalPages) {
        const pagControls = document.getElementById('paginationControls');
        pagControls.innerHTML = '';

        if (totalPages <= 1) return;

        // Previous Button
        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        prevLi.innerHTML = `<button class="page-link" onclick="renderTable(${currentPage - 1})"><i class="bi bi-chevron-left"></i></button>`;
        pagControls.appendChild(prevLi);

        // Page Numbers
        for (let i = 1; i <= totalPages; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<button class="page-link" onclick="renderTable(${i})">${i}</button>`;
            pagControls.appendChild(li);
        }

        // Next Button
        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
        nextLi.innerHTML = `<button class="page-link" onclick="renderTable(${currentPage + 1})"><i class="bi bi-chevron-right"></i></button>`;
        pagControls.appendChild(nextLi);
    }

    function resetFilters() {
        searchInput.value = '';
        typeSelect.value = '';
        paySelect.value = '';
        renderTable(1);
    }

    // Event Listeners
    [searchInput, typeSelect, paySelect].forEach(el => {
        el.addEventListener('input', () => renderTable(1));
    });

    // Run Initial Lifecycle
    window.addEventListener('DOMContentLoaded', () => {
        renderTable(1);
    });
</script>

<?= $this->endSection() ?>