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

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

<!-- Tailwind CSS Engine for utility classes -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
    tailwind.config = {
        darkMode: 'class',
        theme: {
            extend: {
                colors: {
                    slate: { 950: '#0b1329' }
                }
            }
        }
    }
</script>

<!-- Bootstrap 5 CSS for grid system and core layout -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<!-- Fonts & Icons -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    body {
        font-family: 'Inter', sans-serif !important;
        background-color: #f8fafc;
        transition: background-color 0.3s ease, color 0.3s ease;
    }

    /* Form Design Tokens */
    .form-section-card {
        background: #ffffff;
        border: 1px solid rgba(226, 232, 240, 0.8);
        border-radius: 1.25rem;
        transition: all 0.3s ease;
    }

    .form-control-custom {
        display: block;
        width: 100%;
        padding: 0.625rem 0.875rem;
        font-size: 0.875rem;
        font-weight: 400;
        line-height: 1.5;
        color: #1e293b;
        background-color: #ffffff;
        background-clip: padding-box;
        border: 1px solid #cbd5e1;
        appearance: none;
        border-radius: 0.75rem;
        transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    }

    .form-control-custom:focus {
        color: #0f172a;
        background-color: #ffffff;
        border-color: #6366f1;
        outline: 0;
        box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.12);
    }

    /* Style for Custom CNC Switch */
    .switch-premium {
        position: relative;
        display: inline-block;
        width: 48px;
        height: 24px;
    }

    .switch-premium input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    .slider-premium {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #cbd5e1;
        transition: .3s;
        border-radius: 24px;
    }

    .slider-premium:before {
        position: absolute;
        content: "";
        height: 18px;
        width: 18px;
        left: 3px;
        bottom: 3px;
        background-color: white;
        transition: .3s;
        border-radius: 50%;
    }

    input:checked + .slider-premium {
        background-color: #6366f1;
    }

    input:checked + .slider-premium:before {
        transform: translateX(24px);
    }

    /* Scrollbar */
    ::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }

    ::-webkit-scrollbar-track {
        background: #f1f5f9;
    }

    ::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 4px;
    }

    /* Dark Mode Global Overrides */
    html.dark body {
        background-color: #0b1329 !important;
        color: #f8fafc !important;
    }

    html.dark .form-section-card {
        background-color: #1e293b !important;
        border-color: #334155 !important;
        color: #f1f5f9 !important;
    }

    html.dark .form-control-custom {
        background-color: #0f172a !important;
        border-color: #475569 !important;
        color: #f1f5f9 !important;
    }

    html.dark .form-control-custom:focus {
        border-color: #818cf8;
        box-shadow: 0 0 0 4px rgba(129, 140, 248, 0.15);
    }

    html.dark .text-slate-900, html.dark h1, html.dark h2, html.dark h3, html.dark h4, html.dark h5 {
        color: #f8fafc !important;
    }

    html.dark .text-slate-500, html.dark .text-muted {
        color: #94a3b8 !important;
    }

    html.dark .border-slate-100 {
        border-color: #334155 !important;
    }
</style>

<?php
// Resolving existing supplier name for default input text values
$currentSupplierName = '';
if (!empty($product['id_supplier']) && !empty($suppliers)) {
    foreach ($suppliers as $s) {
        if ($s['id_supplier'] == $product['id_supplier']) {
            $currentSupplierName = $s['nama_supplier'];
            break;
        }
    }
}
?>

<div class="container-fluid py-4 px-3 sm:px-4 lg:px-6">
    <!-- Header & Action Deck -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 pb-6 border-b border-slate-200 dark:border-slate-700">
        <div>
            <div class="flex items-center gap-2 mb-2">
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400 border border-amber-200 dark:border-amber-800/50 shadow-sm">
                    <span class="w-2 h-2 rounded-full bg-amber-500 animate-pulse"></span> Koreksi Data Katalog
                </span>
            </div>
            <h1 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight flex items-center gap-2">
                <i class="fas fa-edit text-indigo-600 dark:text-indigo-400"></i> Edit Produk Bengkel
            </h1>
            <p class="text-sm text-slate-500 mt-1">Ubah rincian spesifikasi teknis, harga modal vendor, dan konfigurasi margin barang kustom.</p>
        </div>
        <!-- Utility Action Buttons -->
        <div class="flex items-center gap-2 w-full md:w-auto justify-end">
            <!-- Theme Changer Button -->
            <button type="button" onclick="toggleDarkMode()" class="bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-200 border border-slate-200 dark:border-slate-600 rounded-xl p-2.5 shadow-sm transition-all flex items-center justify-center" title="Ubah Tema Gelap/Terang">
                <i id="themeIcon" class="fas fa-moon text-lg"></i>
            </button>
            <!-- Go Back Link -->
            <a href="<?= base_url('owner/product') ?>" class="bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-200 border border-slate-200 dark:border-slate-600 font-semibold text-sm rounded-xl px-4 py-2.5 shadow-sm transition-all flex items-center gap-2 decoration-none no-underline">
                <i class="fas fa-arrow-left text-slate-400"></i>
                <span>Kembali</span>
            </a>
        </div>
    </div>

    <!-- Form Wrapper -->
    <form action="<?= base_url('owner/product/update/'.$product['id_product']) ?>" method="post" enctype="multipart/form-data" id="editProductForm">
        <?= csrf_field() ?>

        <div class="row g-4">
            <!-- Left Panel: Core Form Data -->
            <div class="col-12 col-lg-8">
                <div class="form-section-card p-4 sm:p-5 shadow-xs mb-4">
                    <h3 class="text-base font-bold text-slate-900 mb-4 pb-2 border-b border-slate-100 flex items-center gap-2">
                        <i class="fas fa-circle-info text-indigo-500"></i> Informasi Dasar Produk
                    </h3>

                    <!-- Product Name -->
                    <div class="mb-3">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Nama Produk <span class="text-rose-500">*</span></label>
                        <input type="text" name="nama_product" class="form-control-custom" value="<?= esc($product['nama_product'] ?? '') ?>" placeholder="Contoh: Gearbox Custom CNC Type-B" required>
                    </div>

                    <div class="row">
                        <!-- Category Input -->
                        <div class="col-12 col-md-6 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Kategori Produk <span class="text-xs text-slate-400 font-normal">(Opsional)</span></label>
                            <select name="id_category" id="input_category" class="form-control-custom">
                                <option value="">Pilih kategori...</option>
                                <?php foreach ($categories as $c): ?>
                                    <option value="<?= (int) $c['id_category'] ?>" <?= (int) ($product['id_category'] ?? 0) === (int) $c['id_category'] ? 'selected' : '' ?>><?= esc($c['nama_kategori']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Supplier Input (Manual Text Input with Auto-complete Datalist) -->
                        <div class="col-12 col-md-6 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Pemasok / Vendor <span class="text-xs text-slate-400 font-normal">(Opsional)</span></label>
                            <input type="text" name="id_supplier" id="input_supplier" list="supplier_list" class="form-control-custom" value="<?= esc($currentSupplierName) ?>" placeholder="Ketik atau pilih supplier/vendor..." autocomplete="off">
                            <datalist id="supplier_list">
                                <?php if (!empty($suppliers)): ?>
                                    <?php foreach ($suppliers as $s): ?>
                                        <option value="<?= esc($s['nama_supplier']) ?>"></option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </datalist>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Stock Level -->
                        <div class="col-12 col-sm-6 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Kuantitas Stok <span class="text-rose-500">*</span></label>
                            <input type="number" name="stok" id="inputStock" class="form-control-custom" value="<?= $product['stok'] ?? 0 ?>" min="0" required>
                        </div>

                        <!-- Stock Type (Database Field: stock_type) -->
                        <div class="col-12 col-sm-6 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Status Ketersediaan <span class="text-rose-500">*</span></label>
                            <select name="stock_type" id="stockType" class="form-control-custom" required>
                                <option value="ready" <?= strtolower((string) ($product['stock_type'] ?? 'ready')) !== 'po' ? 'selected' : '' ?>>Ready Stock</option>
                                <option value="po" <?= strtolower((string) ($product['stock_type'] ?? 'ready')) === 'po' ? 'selected' : '' ?>>Pre-Order (PO)</option>
                            </select>
                            <small id="stockTypeHint" class="text-[10px] text-slate-400 block mt-1.5 leading-tight">Stok wajib diisi untuk produk ready stock.</small>
                        </div>
                    </div>

                    <div class="row">
                        <!-- SKU Code -->
                        <div class="col-12 col-sm-6 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Kode SKU (Internal)</label>
                            <input type="text" name="sku" class="form-control-custom" value="<?= esc($product['sku'] ?? '') ?>" placeholder="Contoh: CNC-GEAR-001">
                        </div>

                        <!-- Barcode Data -->
                        <div class="col-12 col-sm-6 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Kode Barcode / EAN</label>
                            <input type="text" name="barcode" class="form-control-custom" value="<?= esc($product['barcode'] ?? '') ?>" placeholder="Contoh: 8991234567890">
                        </div>
                    </div>
                </div>

                <!-- Textarea Segment -->
                <div class="form-section-card p-4 sm:p-5 shadow-xs mb-4">
                    <h3 class="text-base font-bold text-slate-900 mb-4 pb-2 border-b border-slate-100 flex items-center gap-2">
                        <i class="fas fa-file-text text-indigo-500"></i> Spesifikasi & Keterangan
                    </h3>
                    <!-- Description -->
                    <div class="mb-3">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Deskripsi Detail Produk</label>
                        <textarea name="description" rows="3" class="form-control-custom" placeholder="Tuliskan deskripsi lengkap mengenai kegunaan dan bahan produk..."><?= esc($product['description'] ?? '') ?></textarea>
                    </div>
                    <!-- Technical Notes -->
                    <div class="mb-3">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Catatan Teknis / Fabrikasi CNC</label>
                        <textarea name="technical_notes" rows="3" class="form-control-custom" placeholder="Contoh: Toleransi mikro 0.05mm, Kecepatan Spindle optimal 8000 RPM..."><?= esc($product['technical_notes'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <!-- Right Panel: Financial Dimensions & Visuals -->
            <div class="col-12 col-lg-4">
                <!-- Opsi Fabrikasi Custom & Status Switch -->
                <div class="form-section-card p-4 shadow-xs mb-4">
                    <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4 pb-2 border-b border-slate-100">Klasifikasi Katalog</h3>
                    
                    <!-- Custom Product Toggle -->
                    <div class="flex items-center justify-between mb-4">
                        <div>
                            <span class="text-sm font-bold text-slate-800 dark:text-slate-100 block">Jasa Custom CNC</span>
                            <small class="text-xs text-slate-400">Gunakan untuk pengerjaan mesin khusus.</small>
                        </div>
                        <label class="switch-premium">
                            <input type="checkbox" name="is_custom" value="1" id="is_custom_switch" <?= ($product['is_custom'] ?? 0) == 1 ? 'checked' : '' ?>>
                            <span class="slider-premium"></span>
                        </label>
                    </div>

                    <!-- Active/Inactive Status Selection -->
                    <div class="mb-2">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Status Produk</label>
                        <select name="status" class="form-control-custom">
                            <option value="active" <?= ($product['status'] ?? '') == 'active' ? 'selected' : '' ?>>Aktif</option>
                            <option value="inactive" <?= ($product['status'] ?? '') == 'inactive' ? 'selected' : '' ?>>Nonaktif (Sembunyikan)</option>
                        </select>
                    </div>
                </div>

                <!-- Financial Deck & Real-time Profit Markup Calculator -->
                <div class="form-section-card p-4 shadow-xs mb-4 bg-indigo-50/40 dark:bg-slate-900/40 border-indigo-100/50">
                    <h3 class="text-xs font-bold text-indigo-600 dark:text-indigo-400 uppercase tracking-wider mb-4 pb-2 border-b border-indigo-100/40">
                        <i class="fas fa-calculator me-1"></i> Kalkulator Finansial
                    </h3>
                    
                    <!-- Harga Modal (HPP) -->
                    <div class="mb-3">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Harga Modal (Rp) <span class="text-rose-500">*</span></label>
                        <input type="number" name="harga_modal" id="inputModal" class="form-control-custom" value="<?= $product['harga_modal'] ?? 0 ?>" min="0" required>
                    </div>

                    <!-- Harga Jual -->
                    <div class="mb-3">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Harga Jual (Rp) <span class="text-rose-500">*</span></label>
                        <input type="number" name="harga" id="inputJual" class="form-control-custom" value="<?= $product['harga'] ?? 0 ?>" min="0" required>
                    </div>

                    <!-- Calculated Feedback Widgets -->
                    <div class="p-3 bg-white dark:bg-slate-950/50 rounded-xl border border-slate-100 dark:border-slate-800 flex flex-col gap-2 mt-4 shadow-xs">
                        <div class="flex justify-between items-center text-xs">
                            <span class="text-slate-400 font-medium">Profit Per Item:</span>
                            <span id="calculatedProfitText" class="font-bold text-slate-800 dark:text-slate-200">Rp 0</span>
                        </div>
                        <div class="flex justify-between items-center text-xs">
                            <span class="text-slate-400 font-medium">Margin Keuntungan:</span>
                            <span id="calculatedMarginBadge" class="inline-flex px-2 py-0.5 rounded font-extrabold text-[10px] bg-slate-100 text-slate-700">0.0%</span>
                        </div>
                        <div class="flex justify-between items-center text-xs border-t border-dashed border-slate-200 dark:border-slate-800 pt-2 mt-1">
                            <span class="text-slate-400 font-medium">Valuasi Stok Modal:</span>
                            <span id="calculatedAssetValuationText" class="font-extrabold text-indigo-600 dark:text-indigo-400">Rp 0</span>
                        </div>
                    </div>
                </div>

                <!-- Product Photo Segment & Live Preview Canvas -->
                <div class="form-section-card p-4 shadow-xs mb-4">
                    <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4 pb-2 border-b border-slate-100">Berkas Visual Produk</h3>
                    <div class="relative w-full aspect-square bg-slate-50 dark:bg-slate-900 rounded-2xl overflow-hidden shadow-inner border border-slate-200 dark:border-slate-700 mb-4 flex items-center justify-center">
                        <img id="imagePreview" src="<?= !empty($product['product_photo']) ? base_url('uploads/products/'.$product['product_photo']) : 'https://placehold.co/400x400/cbd5e1/1e293b?text=Visual' ?>" class="w-full h-full object-cover transition-opacity duration-300" alt="Pratinjau Foto Produk" onerror="this.onerror=null; this.src='https://placehold.co/400x400/cbd5e1/1e293b?text=Visual';">
                    </div>
                    <div class="mb-2">
                        <label class="block text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-2">Unggah Foto Baru (Maks 5MB)</label>
                        <input type="file" name="product_photo" id="fileInputPhoto" class="form-control-custom text-xs file:hidden cursor-pointer" accept=".jpg,.jpeg,.png,.webp" onchange="previewSelectedImage(this)">
                        <?php if(!empty($product['product_photo'])): ?>
                            <div class="mt-2.5 p-2 bg-slate-50 dark:bg-slate-900 rounded-xl border border-slate-100 dark:border-slate-800 flex items-center gap-2">
                                <i class="fas fa-image text-slate-400 text-xs"></i>
                                <span class="text-[10px] text-slate-400 block truncate" title="<?= esc($product['product_photo']) ?>">
                                    Berkas aktif: <?= esc($product['product_photo']) ?>
                                </span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Submit Button Deck -->
                <div class="form-section-card p-4 shadow-xs flex flex-col gap-2">
                    <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm rounded-xl py-3 shadow-md hover:shadow-lg transition-all border-0 flex items-center justify-center gap-2">
                        <i class="fas fa-save"></i> Simpan Pembaruan
                    </button>
                    <a href="<?= base_url('owner/product') ?>" class="w-full bg-slate-100 hover:bg-slate-200 dark:bg-slate-700 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200 font-semibold text-xs rounded-xl py-2.5 transition-all text-center decoration-none no-underline block">
                        Batalkan Perubahan
                    </a>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const inputModal = document.getElementById('inputModal');
        const inputJual = document.getElementById('inputJual');
        const inputStock = document.getElementById('inputStock');
        const stockType = document.getElementById('stockType');
        const stockTypeHint = document.getElementById('stockTypeHint');
        const profitText = document.getElementById('calculatedProfitText');
        const marginBadge = document.getElementById('calculatedMarginBadge');
        const valuationText = document.getElementById('calculatedAssetValuationText');

        function calculateFinancialMetrics() {
            const modal = parseFloat(inputModal.value) || 0;
            const jual = parseFloat(inputJual.value) || 0;
            const stock = parseInt(inputStock.value) || 0;

            const profit = jual - modal;
            const formatRupiah = (val) => {
                return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(val);
            };

            profitText.innerText = formatRupiah(profit);
            if(profit < 0) {
                profitText.className = "font-bold text-rose-500 animate-pulse";
            } else {
                profitText.className = "font-bold text-slate-800 dark:text-slate-200";
            }

            let marginPercent = 0;
            if(modal > 0) {
                marginPercent = (profit / modal) * 100;
            }
            marginBadge.innerText = (marginPercent >= 0 ? '+' : '') + marginPercent.toFixed(1) + '%';

            if(profit < 0) {
                marginBadge.className = "inline-flex px-2 py-0.5 rounded font-extrabold text-[10px] bg-rose-50 text-rose-600 border border-rose-200/50";
            } else if(marginPercent >= 40) {
                marginBadge.className = "inline-flex px-2 py-0.5 rounded font-extrabold text-[10px] bg-emerald-50 text-emerald-600 border border-emerald-200/50 dark:bg-emerald-950/20 dark:text-emerald-400 dark:border-emerald-800/40";
            } else {
                marginBadge.className = "inline-flex px-2 py-0.5 rounded font-extrabold text-[10px] bg-indigo-50 text-indigo-600 border border-indigo-200/50 dark:bg-indigo-950/20 dark:text-indigo-400 dark:border-indigo-800/40";
            }

            const valuation = stock * modal;
            valuationText.innerText = formatRupiah(valuation);
        }

        inputModal.addEventListener('input', calculateFinancialMetrics);
        inputJual.addEventListener('input', calculateFinancialMetrics);
        inputStock.addEventListener('input', calculateFinancialMetrics);
        stockType.addEventListener('change', syncStockForAvailability);

        function syncStockForAvailability() {
            const isPo = stockType.value === 'po';
            inputStock.disabled = isPo;
            inputStock.required = !isPo;

            if (isPo) {
                inputStock.value = '';
                inputStock.placeholder = 'Tidak berlaku untuk produk PO';
                stockTypeHint.textContent = 'Produk PO tidak memakai stok ready dan akan disimpan dengan stok 0.';
            } else {
                inputStock.value = inputStock.value || '0';
                inputStock.placeholder = '';
                stockTypeHint.textContent = 'Stok wajib diisi untuk produk ready stock.';
            }

            calculateFinancialMetrics();
        }

        syncStockForAvailability();
        calculateFinancialMetrics();

        window.previewSelectedImage = function(input) {
            const preview = document.getElementById('imagePreview');
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.style.opacity = '0';
                    setTimeout(() => {
                        preview.setAttribute('src', e.target.result);
                        preview.style.opacity = '1';
                    }, 200);
                }
                reader.readAsDataURL(input.files[0]);
            }
        };

        window.toggleDarkMode = function() {
            const html = document.documentElement;
            const icon = document.getElementById('themeIcon');
            if (html.classList.contains('dark')) {
                html.classList.remove('dark');
                localStorage.setItem('theme', 'light');
                icon.className = "fas fa-moon text-lg";
            } else {
                html.classList.add('dark');
                localStorage.setItem('theme', 'dark');
                icon.className = "fas fa-sun text-lg text-amber-400";
            }
        };

        if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            document.getElementById('themeIcon').className = "fas fa-sun text-lg text-amber-400";
        }
    });
</script>

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