<?= $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, .production-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;
    }

    /* Code Pill for Production / Order Numbers */
    .code-pill {
        background: var(--bg-accent);
        border: 1px solid var(--border-color);
        color: var(--text-main);
        font-family: var(--bs-font-monospace);
        font-size: 0.8rem;
        font-weight: 600;
        padding: 0.2rem 0.5rem;
        border-radius: var(--radius-sm);
    }

    /* 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-info      { background: rgba(6, 182, 212, 0.12); color: #06b6d4; border: 1px solid rgba(6, 182, 212, 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 production-workspace">

    <?php 
        // Akumulasi Statistik Workflow Produksi
        $totalProd    = !empty($productions) && is_array($productions) ? count($productions) : 0;
        $countInProg  = 0;
        $countQc      = 0;
        $countDone    = 0;

        if (!empty($productions) && is_array($productions)) {
            foreach ($productions as $p) {
                $st = strtolower((string)($p['status'] ?? 'waiting'));
                if (in_array($st, ['waiting', 'design', 'cutting', 'assembly', 'finishing'])) {
                    $countInProg++;
                } elseif ($st === 'qc') {
                    $countQc++;
                } elseif ($st === 'completed') {
                    $countDone++;
                }
            }
        }

        // Configuration Map Status Workflow
        $statusMap = [
            'waiting'   => ['label' => 'Waiting', 'badge' => 'badge-soft-secondary', 'icon' => 'bi-hourglass-split'],
            'design'    => ['label' => 'Design', 'badge' => 'badge-soft-info', 'icon' => 'bi-palette'],
            'cutting'   => ['label' => 'Cutting', 'badge' => 'badge-soft-warning', 'icon' => 'bi-scissors'],
            'assembly'  => ['label' => 'Assembly', 'badge' => 'badge-soft-primary', 'icon' => 'bi-tools'],
            'finishing' => ['label' => 'Finishing', 'badge' => 'badge-soft-primary', 'icon' => 'bi-paint-bucket'],
            'qc'        => ['label' => 'Quality Control', 'badge' => 'badge-soft-warning', 'icon' => 'bi-patch-check'],
            'completed' => ['label' => 'Completed', 'badge' => 'badge-soft-success', 'icon' => 'bi-check-circle-fill'],
            'cancelled' => ['label' => 'Cancelled', 'badge' => 'badge-soft-danger', 'icon' => 'bi-x-circle-fill'],
        ];
    ?>

    <!-- 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">Sistem Manajemen Produksi</h3>
            <p class="text-sub small mb-0 mt-0.5">Monitoring alur kerja, tahapan pemrosesan pesanan, dan tenggat waktu produksi.</p>
        </div>
        <div>
            <a href="<?= site_url('admin/orders') ?>" class="btn btn-outline-secondary px-3.5 py-2 rounded-3 shadow-sm fw-semibold d-inline-flex align-items-center gap-2 fs-7">
                <i class="bi bi-box-seam"></i> Kelola Order
            </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><?= esc(session()->getFlashdata('success')) ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger 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-exclamation-triangle-fill fs-5"></i>
                <div><?= esc(session()->getFlashdata('error')) ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- STATISTIK WORKFLOW -->
    <div class="row g-3 mb-4">
        <!-- Total Produksi -->
        <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 Produksi</div>
                    <div class="h4 fw-bolder mb-0 text-main"><?= number_format($totalProd) ?></div>
                </div>
                <div class="stat-icon bg-primary-subtle text-primary">
                    <i class="bi bi-gear-wide-connected"></i>
                </div>
            </div>
        </div>

        <!-- Dalam Proses -->
        <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;">Dalam Pemrosesan</div>
                    <div class="h4 fw-bolder mb-0 text-info"><?= number_format($countInProg) ?></div>
                </div>
                <div class="stat-icon bg-info-subtle text-info">
                    <i class="bi bi-cpu"></i>
                </div>
            </div>
        </div>

        <!-- Tahap QC -->
        <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;">Tahap QC</div>
                    <div class="h4 fw-bolder mb-0 text-warning"><?= number_format($countQc) ?></div>
                </div>
                <div class="stat-icon bg-warning-subtle text-warning">
                    <i class="bi bi-patch-check"></i>
                </div>
            </div>
        </div>

        <!-- Selesai -->
        <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;">Selesai Diproduksi</div>
                    <div class="h4 fw-bolder mb-0 text-success"><?= number_format($countDone) ?></div>
                </div>
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="bi bi-check2-circle"></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-6 col-lg-5">
                <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="searchProduction" class="form-control border-start-0 ps-1 rounded-end-3" placeholder="Cari No. Produksi, Order #, Pelanggan...">
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-3">
                <select id="filterStatus" class="form-select rounded-3">
                    <option value="">Semua Tahap Produksi</option>
                    <option value="waiting">Persiapan</option>
                    <option value="design">Design</option>
                    <option value="cutting">Cutting</option>
                    <option value="assembly">Assembly</option>
                    <option value="finishing">Finishing</option>
                    <option value="qc">Quality Control (QC)</option>
                    <option value="completed">Completed (Selesai)</option>
                    <option value="cancelled">Cancelled (Dibatalkan)</option>
                </select>
            </div>
            <div class="col-6 col-md-2 col-lg-2 ms-auto text-end">
                <button type="button" class="btn btn-outline-secondary btn-sm rounded-3 py-2 px-3 w-100 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="productionTable">
                <thead>
                    <tr>
                        <th class="ps-3" style="width: 50px;">#</th>
                        <th>Nomor Produksi</th>
                        <th>Order</th>
                        <th>Pelanggan</th>
                        <th>Batch Produksi</th>
                        <th>Tahap Produksi</th>
                        <th class="text-end pe-3">Aksi Workflow</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($productions) && is_array($productions)): foreach($productions as $i => $production): ?>
                        <?php 
                            $status = strtolower((string) ($production['status'] ?? 'waiting'));
                            $validStatuses = ['waiting', 'design', 'cutting', 'assembly', 'finishing', 'qc', 'completed', 'cancelled'];
                            $status = in_array($status, $validStatuses, true) ? $status : 'waiting';
                            
                            $badgeInfo = $statusMap[$status] ?? ['label' => ucfirst($status), 'badge' => 'badge-soft-secondary', 'icon' => 'bi-gear'];
                            $customerInitial = strtoupper(substr(trim($production['customer_name'] ?? 'C'), 0, 1));
                            $batchDate = $production['scheduled_month'] ?? $production['target_date'] ?? date('Y-m-d');
                            $isFutureBatch = date('Y-m-01', strtotime($batchDate)) > date('Y-m-01');
                        ?>
                        <tr class="production-row">
                            <td class="ps-3 text-sub small fw-medium"><?= $i + 1 ?></td>
                            
                            <!-- Nomor Produksi -->
                            <td>
                                <span class="code-pill text-primary">
                                    <i class="bi bi-hash"></i><?= esc($production['production_number'] ?? '-') ?>
                                </span>
                            </td>

                            <!-- Nomor Order -->
                            <td>
                                <span class="fw-semibold text-main">
                                    #<?= esc($production['order_number'] ?? '-') ?>
                                </span>
                            </td>

                            <!-- Customer Info -->
                            <td>
                                <div class="d-flex align-items-center gap-2.5">
                                    <div class="avatar-circle"><?= $customerInitial ?></div>
                                    <div class="fw-semibold text-main" style="font-size: 0.88rem;">
                                        <?= esc($production['customer_name'] ?? 'Pelanggan Umum') ?>
                                    </div>
                                </div>
                            </td>

                            <!-- Target Date -->
                            <td>
                                <div class="d-flex align-items-center gap-1.5 text-main font-monospace small">
                                    <i class="bi bi-calendar-event text-sub"></i>
                                    <?= esc(date('m/Y', strtotime($batchDate))) ?>
                                </div>
                                <div class="text-sub" style="font-size: 0.72rem;">
                                    <?= number_format((int) ($production['batch_quantity'] ?? 0)) ?> unit
                                </div>
                            </td>

                            <!-- Status Workflow Badge -->
                            <td>
                                <span class="badge <?= $badgeInfo['badge'] ?> rounded-pill px-2.5 py-1 d-inline-flex align-items-center gap-1.5">
                                    <i class="bi <?= $badgeInfo['icon'] ?>"></i>
                                    <span><?= esc($badgeInfo['label']) ?></span>
                                </span>
                            </td>

                            <!-- Action / Next Step -->
                            <td class="text-end pe-3">
                                <?php if (!in_array($status, ['completed', 'cancelled'], true) && !$isFutureBatch): ?>
                                    <form method="post" action="<?= site_url('admin/production/advance/' . $production['id_production']) ?>" class="d-inline" onsubmit="return confirm('Lanjutkan item produksi ke tahap berikutnya?');">
                                        <?= csrf_field() ?>
                                        <button class="btn btn-primary btn-sm rounded-3 fw-semibold px-3 py-1.5 fs-7 d-inline-flex align-items-center gap-1.5 shadow-sm" type="submit">
                                            <i class="bi bi-arrow-right-circle-fill"></i> Next Step
                                        </button>
                                    </form>
                                <?php elseif ($isFutureBatch): ?>
                                    <span class="badge badge-soft-warning rounded-pill px-3 py-1.5 small fw-semibold">
                                        <i class="bi bi-calendar-week me-1"></i> Menunggu Batch
                                    </span>
                                <?php else: ?>
                                    <span class="badge badge-soft-success rounded-pill px-3 py-1.5 small fw-semibold">
                                        <i class="bi bi-check-all me-1"></i> Selesai
                                    </span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; else: ?>
                        <tr id="emptyRowStatic">
                            <td colspan="7" class="text-center py-5 text-sub">
                                <i class="bi bi-box-seam fs-2 d-block opacity-40 mb-2"></i>
                                Belum ada data produksi yang berjalan.
                            </td>
                        </tr>
                    <?php endif; ?>

                    <!-- Dynamic JS Empty Search State -->
                    <tr id="noMatchingDataRow" class="d-none">
                        <td colspan="7" class="text-center py-5 text-sub">
                            <i class="bi bi-search fs-2 d-block opacity-40 mb-2"></i>
                            <strong>Tidak ada data produksi 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 produksi...</div>
            <nav aria-label="Production 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('#productionTable tbody tr.production-row'));
    const searchInput = document.getElementById('searchProduction');
    const statusSelect = document.getElementById('filterStatus');
    const noMatchRow = document.getElementById('noMatchingDataRow');

    function renderTable(page = 1) {
        currentPage = page;
        const searchVal = searchInput.value.toLowerCase().trim();
        const statusVal = statusSelect.value.toLowerCase().trim();

        // Filtering logic
        const filteredRows = rows.filter(row => {
            const rowText = row.innerText.toLowerCase();
            const matchesSearch = searchVal === '' || rowText.includes(searchVal);
            
            // Cell index 5 corresponds to Status/Tahap Produksi column
            const statusCellText = row.cells[5] ? row.cells[5].innerText.toLowerCase() : '';
            const matchesStatus = statusVal === '' || statusCellText.includes(statusVal);

            return matchesSearch && matchesStatus;
        });

        // 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} item produksi`;
        } else {
            infoEl.innerText = 'Menampilkan 0 item produksi';
        }

        // 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 = '';
        statusSelect.value = '';
        renderTable(1);
    }

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

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

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