<?= $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-detail-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);
    }

    .card-premium:hover {
        border-color: var(--border-hover);
    }

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

    /* Code Pill for Order/Production 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.85rem;
        font-weight: 600;
        padding: 0.25rem 0.6rem;
        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); }

    /* WORKFLOW STEPPER TRACKER */
    .stepper-wrapper {
        position: relative;
        display: flex;
        justify-content: space-between;
        margin: 1.5rem 0 0.5rem;
    }

    .stepper-progress-bg {
        position: absolute;
        top: 20px;
        left: 0;
        right: 0;
        height: 3px;
        background: var(--border-color);
        z-index: 1;
    }

    .stepper-progress-bar {
        position: absolute;
        top: 20px;
        left: 0;
        height: 3px;
        background: var(--primary);
        z-index: 1;
        transition: width 0.4s ease;
    }

    .stepper-item {
        position: relative;
        z-index: 2;
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
    }

    .stepper-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: var(--bg-card);
        border: 2px solid var(--border-color);
        color: var(--text-sub);
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        font-size: 0.9rem;
        transition: var(--transition);
    }

    .stepper-item.completed .stepper-icon {
        background: var(--success);
        border-color: var(--success);
        color: #ffffff;
    }

    .stepper-item.active .stepper-icon {
        background: var(--primary);
        border-color: var(--primary);
        color: #ffffff;
        box-shadow: 0 0 0 4px var(--primary-light);
    }

    .stepper-label {
        font-size: 0.75rem;
        font-weight: 600;
        color: var(--text-sub);
        margin-top: 0.6rem;
        text-align: center;
        transition: var(--transition);
    }

    .stepper-item.active .stepper-label, 
    .stepper-item.completed .stepper-label {
        color: var(--text-main);
    }

    @media (max-width: 768px) {
        .stepper-wrapper {
            flex-direction: column;
            align-items: flex-start;
            gap: 1.25rem;
        }

        .stepper-progress-bg, .stepper-progress-bar {
            display: none;
        }

        .stepper-item {
            flex-direction: row;
            gap: 1rem;
            width: 100%;
        }

        .stepper-label {
            margin-top: 0;
            text-align: left;
            font-size: 0.85rem;
        }
    }
</style>

<div class="container-fluid py-4 production-detail-workspace">

    <?php if (empty($production)): ?>
        <!-- EMPTY / NOT FOUND STATE -->
        <div class="card-premium p-5 text-center my-4">
            <div class="py-4">
                <i class="bi bi-exclamation-triangle fs-1 text-warning d-block mb-3 opacity-75"></i>
                <h4 class="fw-bold text-main">Data Produksi Tidak Ditemukan</h4>
                <p class="text-sub small mb-4">Item produksi yang Anda cari mungkin telah dihapus atau ID tidak valid.</p>
                <a href="<?= site_url('admin/production') ?>" class="btn btn-primary rounded-3 px-4 py-2 fw-semibold">
                    <i class="bi bi-arrow-left me-1.5"></i> Kembali ke List Produksi
                </a>
            </div>
        </div>
    <?php else: ?>
        <?php
            // Validasi & Pemetaan Status Workflow Produksi
            $status = strtolower((string) ($production['status'] ?? 'waiting'));
            $validStatuses = ['waiting', 'design', 'cutting', 'assembly', 'finishing', 'qc', 'completed', 'cancelled'];
            $status = in_array($status, $validStatuses, true) ? $status : 'waiting';

            // Tahapan Workflow untuk Visual Stepper Tracker
            $workflowSteps = [
                'waiting'   => ['label' => 'Waiting', 'icon' => 'bi-hourglass-split'],
                'design'    => ['label' => 'Design', 'icon' => 'bi-palette'],
                'cutting'   => ['label' => 'Cutting', 'icon' => 'bi-scissors'],
                'assembly'  => ['label' => 'Assembly', 'icon' => 'bi-tools'],
                'finishing' => ['label' => 'Finishing', 'icon' => 'bi-paint-bucket'],
                'qc'        => ['label' => 'QC', 'icon' => 'bi-patch-check'],
                'completed' => ['label' => 'Selesai', 'icon' => 'bi-check-circle-fill']
            ];

            // Hitung Index Tahap Aktif
            $stepKeys = array_keys($workflowSteps);
            $currentIndex = array_search($status, $stepKeys);
            if ($currentIndex === false) $currentIndex = 0;

            // Hitung Persentase Progress Otomatis jika dari database bernilai 0
            $dbProgress = (float)($production['progress'] ?? 0);
            $calculatedProgress = round(($currentIndex / (count($stepKeys) - 1)) * 100);
            $progressPercent = $dbProgress > 0 ? $dbProgress : $calculatedProgress;

            // Calculated progress bar style width for tracker line
            $progressLineWidth = count($stepKeys) > 1 ? ($currentIndex / (count($stepKeys) - 1)) * 100 : 0;

            $statusMap = [
                'waiting'   => ['badge' => 'badge-soft-secondary', 'label' => 'Persiapan Produksi'],
                'design'    => ['badge' => 'badge-soft-info', 'label' => 'Proses Design'],
                'cutting'   => ['badge' => 'badge-soft-warning', 'label' => 'Proses Cutting'],
                'assembly'  => ['badge' => 'badge-soft-primary', 'label' => 'Proses Assembly'],
                'finishing' => ['badge' => 'badge-soft-primary', 'label' => 'Proses Finishing'],
                'qc'        => ['badge' => 'badge-soft-warning', 'label' => 'Quality Control (QC)'],
                'completed' => ['badge' => 'badge-soft-success', 'label' => 'Selesai Diproduksi'],
                'cancelled' => ['badge' => 'badge-soft-danger', 'label' => 'Dibatalkan'],
            ];

            $badgeInfo = $statusMap[$status] ?? ['badge' => 'badge-soft-secondary', 'label' => ucfirst($status)];
            $customerName = $order['customer_name'] ?? $production['customer_name'] ?? 'Pelanggan Umum';
            $customerInitial = strtoupper(substr(trim($customerName), 0, 1));
            $orderNumber = $order['order_number'] ?? $production['order_number'] ?? '-';
            $orderId = $order['id_order'] ?? $production['id_order'] ?? null;
        ?>

        <!-- PAGE HEADER -->
        <div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center mb-4 gap-3">
            <div>
                <div class="d-flex align-items-center gap-2 mb-1">
                    <h3 class="fw-bold mb-0 text-main">Detail Produksi</h3>
                    <span class="badge <?= $badgeInfo['badge'] ?> rounded-pill px-2.5 py-1">
                        <?= esc($badgeInfo['label']) ?>
                    </span>
                </div>
                <p class="text-sub small mb-0">Lacak alur pemrosesan pesanan dan status pembaruan workflow produksi.</p>
            </div>
            <div class="d-flex align-items-center gap-2">
                <a href="<?= site_url('admin/production') ?>" 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-arrow-left"></i> Kembali ke Dashboard
                </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; ?>

        <!-- WORKFLOW TRACKER STEPPER CARD -->
        <?php if ($status !== 'cancelled'): ?>
            <div class="card-premium p-4 mb-4">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="fw-bold text-main mb-0 d-flex align-items-center gap-2">
                        <i class="bi bi-bezier2 text-primary"></i> Pipeline Workflow Produksi
                    </h6>
                    <span class="small fw-bold text-primary font-monospace"><?= $progressPercent ?>% Selesai</span>
                </div>

                <div class="stepper-wrapper">
                    <div class="stepper-progress-bg"></div>
                    <div class="stepper-progress-bar" style="width: <?= $progressLineWidth ?>%;"></div>

                    <?php foreach ($workflowSteps as $key => $step): ?>
                        <?php 
                            $stepIndex = array_search($key, $stepKeys);
                            $class = '';
                            if ($stepIndex < $currentIndex) {
                                $class = 'completed';
                            } elseif ($stepIndex === $currentIndex) {
                                $class = 'active';
                            }
                        ?>
                        <div class="stepper-item <?= $class ?>">
                            <div class="stepper-icon">
                                <?php if ($stepIndex < $currentIndex): ?>
                                    <i class="bi bi-check-lg"></i>
                                <?php else: ?>
                                    <i class="bi <?= $step['icon'] ?>"></i>
                                <?php endif; ?>
                            </div>
                            <div class="stepper-label"><?= esc($step['label']) ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- DETAIL CONTENT GRID -->
        <div class="row g-4">
            
            <!-- LEFT PANEL: Ringkasan Produksi -->
            <div class="col-12 col-lg-8">
                <div class="card-premium p-4 h-100">
                    <h6 class="fw-bold text-main mb-3 pb-2 border-bottom border-color d-flex align-items-center gap-2">
                        <i class="bi bi-info-circle text-primary"></i> Informasi Item Produksi
                    </h6>

                    <div class="row g-3">
                        <div class="col-12 col-sm-6">
                            <div class="text-sub small fw-medium mb-1">Nomor Produksi</div>
                            <span class="code-pill text-primary d-inline-block">
                                <i class="bi bi-hash"></i><?= esc($production['production_number'] ?? '-') ?>
                            </span>
                        </div>

                        <div class="col-12 col-sm-6">
                            <div class="text-sub small fw-medium mb-1">Nomor Order Referensi</div>
                            <?php if ($orderId): ?>
                                <a href="<?= base_url('admin/orders/show/' . $orderId) ?>" class="code-pill text-main text-decoration-none hover-underline d-inline-block">
                                    #<?= esc($orderNumber) ?> <i class="bi bi-box-arrow-up-right ms-1 text-sub" style="font-size: 0.75rem;"></i>
                                </a>
                            <?php else: ?>
                                <span class="code-pill text-main d-inline-block">#<?= esc($orderNumber) ?></span>
                            <?php endif; ?>
                        </div>

                        <div class="col-12 col-sm-6">
                            <div class="text-sub small fw-medium mb-1">Status Produksi Saat Ini</div>
                            <span class="badge <?= $badgeInfo['badge'] ?> rounded-pill px-3 py-1.5 fw-semibold fs-7">
                                <?= esc($badgeInfo['label']) ?>
                            </span>
                        </div>

                        <div class="col-12 col-sm-6">
                            <div class="text-sub small fw-medium mb-1">Batch Produksi</div>
                            <div class="fw-semibold text-main font-monospace small d-flex align-items-center gap-1.5">
                                <i class="bi bi-calendar-event text-sub"></i>
                                <?= esc(date('m/Y', strtotime($batchMonth ?? $production['scheduled_month'] ?? $order['target_date'] ?? 'today'))) ?>
                            </div>
                        </div>
                    </div>

                    <hr class="my-4 border-color">

                    <!-- Visual Progress Bar Gauge -->
                    <div>
                        <div class="d-flex justify-content-between align-items-center mb-1.5">
                            <span class="text-sub small fw-medium">Indikator Kemajuan Produksi</span>
                            <span class="fw-bold text-main small font-monospace"><?= $progressPercent ?>%</span>
                        </div>
                        <div class="progress rounded-pill bg-accent" style="height: 10px;">
                            <div class="progress-bar bg-primary rounded-pill progress-bar-striped progress-bar-animated" role="progressbar" style="width: <?= $progressPercent ?>%;" aria-valuenow="<?= $progressPercent ?>" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- RIGHT PANEL: Customer & Workflow Control -->
            <div class="col-12 col-lg-4">
                <div class="d-flex flex-column gap-4">
                    
                    <!-- Customer Card -->
                    <div class="card-premium p-4">
                        <h6 class="fw-bold text-main mb-3 pb-2 border-bottom border-color d-flex align-items-center gap-2">
                            <i class="bi bi-person text-primary"></i> Data Pelanggan
                        </h6>
                        <div class="d-flex align-items-center gap-3">
                            <div class="avatar-circle"><?= $customerInitial ?></div>
                            <div>
                                <div class="fw-bold text-main" style="font-size: 0.95rem;"><?= esc($customerName) ?></div>
                                <div class="text-sub small">Pemilik Order #<?= esc($orderNumber) ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Control Panel -->
                    <div class="card-premium p-4">
                        <h6 class="fw-bold text-main mb-3 pb-2 border-bottom border-color d-flex align-items-center gap-2">
                            <i class="bi bi-sliders text-primary"></i> Kontrol Workflow
                        </h6>

                        <?php if (!in_array($status, ['completed', 'cancelled'], true)): ?>
                            <p class="text-sub small mb-3">
                                Klik tombol di bawah ini untuk memajukan status produksi pesanan ini ke tahap berikutnya dalam pipeline.
                            </p>
                            
                            <form method="post" action="<?= site_url('admin/production/advance/' . $production['id_production']) ?>" onsubmit="return confirm('Apakah Anda yakin ingin memajukan status produksi ke tahap berikutnya?');">
                                <?= csrf_field() ?>
                                <button class="btn btn-primary w-100 rounded-3 py-2.5 fw-semibold d-inline-flex align-items-center justify-content-center gap-2 shadow-sm" type="submit">
                                    <i class="bi bi-arrow-right-circle-fill fs-6"></i> Next Step (Lanjutkan Tahap)
                                </button>
                            </form>
                        <?php elseif ($status === 'completed'): ?>
                            <div class="alert alert-success border-0 rounded-3 d-flex align-items-center gap-2.5 mb-0" role="alert">
                                <i class="bi bi-check-circle-fill fs-5"></i>
                                <div class="small fw-semibold">Alur produksi telah selesai dikerjakan seluruhnya.</div>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-danger border-0 rounded-3 d-flex align-items-center gap-2.5 mb-0" role="alert">
                                <i class="bi bi-x-circle-fill fs-5"></i>
                                <div class="small fw-semibold">Item produksi ini telah dibatalkan.</div>
                            </div>
                        <?php endif; ?>

                        <?php if ($orderId): ?>
                            <a href="<?= base_url('admin/orders/show/' . $orderId) ?>" class="btn btn-outline-secondary w-100 rounded-3 py-2 fw-semibold d-inline-flex align-items-center justify-content-center gap-2 mt-2.5 fs-7">
                                <i class="bi bi-box-seam"></i> Lihat Detail Order
                            </a>
                        <?php endif; ?>
                    </div>

                </div>
            </div>

        </div>

    <?php endif; ?>

</div>

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