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

    ::-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>

<div class="container-fluid py-4 px-3 sm:px-4 lg:px-6">
    <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-indigo-50 text-indigo-700 dark:bg-indigo-950/30 dark:text-indigo-400 border border-indigo-200 dark:border-indigo-800/50 shadow-sm">
                    <span class="w-2 h-2 rounded-full bg-indigo-600 animate-pulse"></span>
                    Penambahan Katalog Baru
                </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-plus-circle text-indigo-600 dark:text-indigo-400"></i> Tambah Produk Bengkel
            </h1>
            <p class="text-sm text-slate-500 mt-1">Daftarkan produk fabrikasi baru, konfigurasi ketersediaan stok, dan kalkulasi profitabilitas modal secara real-time.</p>
        </div>
        <div class="flex items-center gap-2 w-full md:w-auto justify-end">
            <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>
            <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 action="<?= base_url('owner/product/store') ?>" method="post" enctype="multipart/form-data" id="createProductForm">
        <?= 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" placeholder="Contoh: Shaft Pinion Custom Steel S45C" 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'] ?>"><?= 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" 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">
                        <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 Awal Stok <span class="text-rose-500">*</span></label>
                            <input type="number" name="stok" id="inputStock" class="form-control-custom" value="0" min="0" required>
                        </div>
                        <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">Ready Stock</option>
                                <option value="po">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">
                        <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" placeholder="Contoh: CNC-SHFT-001">
                        </div>
                        <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" placeholder="Contoh: 8991234567890">
                        </div>
                    </div>
                </div>

                <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>
                    <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 spesifikasi detail material, dimensi, maupun kegunaan fungsional produk..."></textarea>
                    </div>
                    <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: Sudut bevel 45 derajat, toleransi mikron ISO 2768, spindle feedrate optimal..."></textarea>
                    </div>
                </div>
            </div>

            <div class="col-12 col-lg-4">
                <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>
                    <div class="mb-3">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Harga Modal / HPP (Rp) <span class="text-rose-500">*</span></label>
                        <input type="number" name="harga_modal" id="inputModal" class="form-control-custom" value="0" min="0" required>
                    </div>
                    <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="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 Investasi Stok:</span>
                            <span id="calculatedAssetValuationText" class="font-extrabold text-indigo-600 dark:text-indigo-400">Rp 0</span>
                        </div>
                    </div>
                </div>

                <!-- Product Photo Uploader -->
                <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="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 Produk (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)">
                        <small class="text-[10px] text-slate-400 block mt-1.5 leading-tight">Mendukung format JPG, JPEG, PNG, WEBP.</small>
                    </div>
                </div>

                <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 Produk Baru
                    </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 Penambahan
                    </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', function() {
            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();
        });
        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() ?>
