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

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

<script src="https://cdn.tailwindcss.com"></script>
<script>
  tailwind.config = {
    darkMode: 'class',
    theme: {
      extend: {
        colors: {
          slate: { 950: '#0b1329' }
        }
      }
    }
  }
</script>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<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 cubic-bezier(0.16, 1, 0.3, 1);
    }
    
    .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);
    }

    /* Glow elements */
    .preview-invoice-container {
        border: 1px dashed rgba(99, 102, 241, 0.3);
        background: linear-gradient(135deg, rgba(99, 102, 241, 0.02) 0%, rgba(99, 102, 241, 0.05) 100%);
    }

    /* Custom Scrollbars */
    ::-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, html.dark h6 {
        color: #f8fafc !important;
    }
    html.dark .text-slate-500, html.dark .text-muted, html.dark .text-slate-400 {
        color: #94a3b8 !important;
    }
    html.dark .border-slate-100 {
        border-color: #334155 !important;
    }
    html.dark .bg-slate-50 {
        background-color: #0f172a !important;
    }
    html.dark .preview-invoice-container {
        border-color: rgba(129, 140, 248, 0.2);
        background: linear-gradient(135deg, rgba(129, 140, 248, 0.02) 0%, rgba(129, 140, 248, 0.05) 100%);
    }
</style>

<div class="container-fluid py-4 px-3 sm:px-4 lg:px-6">

    <!-- Flash Alerts System -->
    <?php if (session()->getFlashdata('success')): ?>
        <div id="alertSuccess" class="mb-4 p-4 rounded-xl border border-emerald-200 bg-emerald-50 dark:bg-emerald-950/30 dark:border-emerald-800/50 text-emerald-800 dark:text-emerald-400 flex justify-between items-center shadow-xs">
            <span class="text-sm font-semibold flex items-center gap-2">
                <i class="fas fa-circle-check text-emerald-600 dark:text-emerald-400 animate-bounce"></i>
                <?= esc(session()->getFlashdata('success')) ?>
            </span>
            <button onclick="document.getElementById('alertSuccess').style.display='none';" class="text-emerald-800 dark:text-emerald-400 opacity-60 hover:opacity-100">
                <i class="fas fa-times"></i>
            </button>
        </div>
    <?php endif ?>

    <?php if (session()->getFlashdata('error')): ?>
        <div id="alertError" class="mb-4 p-4 rounded-xl border border-rose-200 bg-rose-50 dark:bg-rose-950/30 dark:border-rose-800/50 text-rose-800 dark:text-rose-400 flex justify-between items-center shadow-xs">
            <span class="text-sm font-semibold flex items-center gap-2">
                <i class="fas fa-circle-exclamation text-rose-600 dark:text-rose-400"></i>
                <?= esc(session()->getFlashdata('error')) ?>
            </span>
            <button onclick="document.getElementById('alertError').style.display='none';" class="text-rose-800 dark:text-rose-400 opacity-60 hover:opacity-100">
                <i class="fas fa-times"></i>
            </button>
        </div>
    <?php endif ?>

    <!-- Main Header 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-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>
                    Sistem Manajemen Utama & Administrasi
                </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-gears text-indigo-600 dark:text-indigo-400"></i>
                Pengaturan Bisnis
            </h1>
            <p class="text-sm text-slate-500 mt-1">Kelola identitas resmi perusahaan, profil legal, NPWP, pembatasan logistik PO bulanan, serta identitas visual kuitansi.</p>
        </div>

        <!-- Utility Button Theme Changer -->
        <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>
        </div>
    </div>

    <form action="<?= site_url('owner/setting/update') ?>" method="post" enctype="multipart/form-data" id="settingForm">
        <?= csrf_field() ?>

        <div class="row g-4">
            <!-- Left Side: Profile & Corporate Metadata -->
            <div class="col-12 col-lg-8">
                <div class="form-section-card p-4 sm:p-5 shadow-xs">
                    <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="far fa-building text-indigo-500"></i>
                        Profil Perusahaan & Legalitas Resmi
                    </h3>

                    <div class="row g-3">
                        <!-- Company Name -->
                        <div class="col-12 col-md-6">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Nama Perusahaan <span class="text-rose-500">*</span></label>
                            <input type="text" required class="form-control-custom live-sync" name="company_name" id="syncCompanyName" value="<?= esc(old('company_name', $company['company_name'] ?? '')) ?>" placeholder="Contoh: PT. CNC Metalindo Teknik">
                        </div>

                        <!-- Owner Name -->
                        <div class="col-12 col-md-6">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Nama Owner / Pemilik</label>
                            <input type="text" class="form-control-custom" name="owner_name" value="<?= esc(old('owner_name', $company['owner_name'] ?? '')) ?>" placeholder="Nama lengkap pemilik">
                        </div>

                        <!-- Corporate Email -->
                        <div class="col-12 col-md-6">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Email Perusahaan</label>
                            <div class="relative rounded-xl shadow-xs">
                                <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none">
                                    <i class="far fa-envelope text-slate-400"></i>
                                </div>
                                <input type="email" class="form-control-custom pl-10 live-sync" name="email" id="syncEmail" value="<?= esc(old('email', $company['email'] ?? '')) ?>" placeholder="admin@perusahaan.com">
                            </div>
                        </div>

                        <!-- Phone Number -->
                        <div class="col-12 col-md-6">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Telepon / WhatsApp Resmi</label>
                            <div class="relative rounded-xl shadow-xs">
                                <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none">
                                    <i class="fas fa-phone-volume text-slate-400 text-xs"></i>
                                </div>
                                <input type="text" class="form-control-custom pl-10 live-sync" name="phone" id="syncPhone" value="<?= esc(old('phone', $company['phone'] ?? '')) ?>" placeholder="0812-XXXX-XXXX">
                            </div>
                        </div>

                        <!-- Corporate Address -->
                        <div class="col-12">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Alamat Kantor & Workshop</label>
                            <textarea class="form-control-custom" name="address" rows="3" placeholder="Alamat lengkap bengkel bubut / CNC..."><?= esc(old('address', $company['address'] ?? '')) ?></textarea>
                        </div>

                        <!-- NPWP -->
                        <div class="col-12 col-md-6">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">NPWP Perusahaan</label>
                            <div class="relative rounded-xl shadow-xs">
                                <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none">
                                    <i class="far fa-address-card text-slate-400"></i>
                                </div>
                                <input type="text" class="form-control-custom pl-10" name="npwp" value="<?= esc(old('npwp', $company['npwp'] ?? '')) ?>" placeholder="00.000.000.0-000.000">
                            </div>
                        </div>

                        <!-- Rekening Bank -->
                        <div class="col-12 col-md-6">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Rekening Bank (Untuk Kuitansi/Invoice)</label>
                            <textarea class="form-control-custom" name="rekening_bank" rows="1" placeholder="Contoh: BCA 123456789 a/n PT. CNC Metalindo"><?= esc(old('rekening_bank', $company['rekening_bank'] ?? '')) ?></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Side: Logistic Limit & Visual Identity -->
            <div class="col-12 col-lg-4">
                
                <!-- Card: PO Limits -->
                <div class="form-section-card p-4 shadow-xs mb-4">
                    <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-3 pb-2 border-b border-slate-100 dark:border-slate-800">
                        <i class="fas fa-sliders text-indigo-500 me-1.5"></i> Kapasitas PO Bulanan
                    </h3>
                    
                    <div class="mb-2">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Maksimal Unit Produk / Bulan <span class="text-rose-500">*</span></label>
                        <input type="number" required min="0" class="form-control-custom" name="monthly_po_limit" value="<?= esc(old('monthly_po_limit', $company['monthly_po_limit'] ?? 5)) ?>">
                        <small class="text-[10px] text-slate-400 block mt-2 leading-normal">
                            <i class="fas fa-info-circle text-indigo-500 mr-1"></i> Input angka <strong>0</strong> untuk kapasitas tanpa batas. Apabila kuota penuh, order baru admin akan dipenjadwalkan otomatis ke bulan berikutnya.
                        </small>
                    </div>
                </div>

                <!-- Card: Visual Identity -->
                <div class="form-section-card p-4 shadow-xs mb-4">
                    <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-3 pb-2 border-b border-slate-100 dark:border-slate-800">
                        <i class="fas fa-palette text-indigo-500 me-1.5"></i> Identitas Visual
                    </h3>

                    <!-- Logo Upload -->
                    <div class="mb-4">
                        <label class="block text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-2">Logo Resmi Perusahaan</label>
                        <input class="form-control-custom text-xs file:hidden cursor-pointer" type="file" id="logoUploadInput" name="logo" accept=".png,.jpg,.jpeg,.webp" onchange="previewLogoFile(this)">
                        
                        <!-- Visual Container for Active/New Logo preview -->
                        <div class="mt-2.5 p-2 bg-slate-50 dark:bg-slate-900 rounded-xl border border-slate-100 dark:border-slate-800/80 flex items-center gap-3">
                            <div class="w-12 h-12 rounded bg-white border flex items-center justify-center p-1 overflow-hidden" id="logoFrame">
                                <?php if (!empty($company['logo_url'])): ?>
                                    <img id="logoPreviewImage" class="max-h-full max-w-full object-contain" src="<?= base_url($company['logo_url']) ?>">
                                <?php else: ?>
                                    <img id="logoPreviewImage" class="max-h-full max-w-full object-contain" src="https://placehold.co/150x150/e2e8f0/475569?text=Logo">
                                <?php endif ?>
                            </div>
                            <div>
                                <span class="text-[10px] text-slate-400 block font-semibold uppercase tracking-wider">File Logo Aktif</span>
                                <span class="text-[10px] text-slate-500 block truncate max-w-[180px]"><?= !empty($company['logo_url']) ? esc(basename($company['logo_url'])) : 'Belum mengunggah logo' ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Favicon Upload -->
                    <div>
                        <label class="block text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-2">Favicon Browser</label>
                        <input class="form-control-custom text-xs file:hidden cursor-pointer" type="file" id="faviconUploadInput" name="favicon" accept=".ico,.png,.jpg,.jpeg,.webp" onchange="previewFaviconFile(this)">
                        
                        <div class="mt-2.5 p-2 bg-slate-50 dark:bg-slate-900 rounded-xl border border-slate-100 dark:border-slate-800/80 flex items-center gap-3">
                            <div class="w-8 h-8 rounded bg-white border flex items-center justify-center p-1.5 overflow-hidden" id="faviconFrame">
                                <img id="faviconPreviewImage" class="max-h-full max-w-full object-contain" src="<?= !empty($company['favicon_url']) ? base_url($company['favicon_url']) : 'https://placehold.co/50x50/e2e8f0/475569?text=F' ?>">
                            </div>
                            <div>
                                <span class="text-[10px] text-slate-400 block font-semibold uppercase tracking-wider">File Favicon</span>
                                <span class="text-[10px] text-slate-500 block truncate max-w-[180px]"><?= !empty($company['favicon_url']) ? esc(basename($company['favicon_url'])) : 'Rasio 1:1 (.ico / .png)' ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Live Kuitansi Simulation (Absolute Premium Add-on!) -->
                <div class="form-section-card p-4 shadow-xs preview-invoice-container mb-2">
                    <h4 class="text-[10px] font-bold text-indigo-600 dark:text-indigo-400 uppercase tracking-wider mb-2.5 flex items-center gap-1">
                        <span class="w-1.5 h-1.5 rounded-full bg-indigo-600 animate-ping"></span>
                        Simulasi Kepala Invoice
                    </h4>
                    <div class="p-3 bg-white dark:bg-slate-900 rounded-xl border border-slate-200/50 dark:border-slate-800 shadow-2xs space-y-1 text-[10px]">
                        <div class="flex justify-between items-start border-b border-slate-100 dark:border-slate-800 pb-2 mb-2">
                            <div>
                                <h6 class="font-extrabold text-slate-800 dark:text-slate-200 m-0 leading-tight" id="simName">PT. CNC Metalindo</h6>
                                <p class="text-[8px] text-slate-400 m-0" id="simEmail">admin@perusahaan.com</p>
                                <p class="text-[8px] text-slate-400 m-0" id="simPhone">0812-XXXX</p>
                            </div>
                            <!-- Small logo mock -->
                            <div class="w-8 h-8 flex items-center justify-center" id="simLogo">
                                <?php if (!empty($company['logo_url'])): ?>
                                    <img id="simLogoImg" class="max-h-full max-w-full object-contain" src="<?= base_url($company['logo_url']) ?>">
                                <?php else: ?>
                                    <i class="fas fa-cubes text-slate-300 text-sm"></i>
                                <?php endif ?>
                            </div>
                        </div>
                        <div class="flex justify-between font-mono text-[8px] text-slate-400 uppercase">
                            <span>No: INV/2026/012</span>
                            <span>Date: <?= date('d M Y') ?></span>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <!-- Submit Button Row Footer -->
        <div class="mt-6 form-section-card p-4 shadow-xs flex flex-col sm:flex-row justify-end items-center gap-2">
            <button type="submit" class="w-full sm:w-auto bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm rounded-xl px-6 py-3 shadow-md hover:shadow-lg transition-all border-0 flex items-center justify-center gap-2">
                <i class="fas fa-save animate-pulse"></i>
                Simpan Semua Pengaturan
            </button>
        </div>
    </form>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {

    // ==========================================
    // INSTANT LIVE INVOICE SIMULATION HEADER SYNC
    // ==========================================
    const inputName = document.getElementById('syncCompanyName');
    const inputEmail = document.getElementById('syncEmail');
    const inputPhone = document.getElementById('syncPhone');

    const simName = document.getElementById('simName');
    const simEmail = document.getElementById('simEmail');
    const simPhone = document.getElementById('simPhone');

    function syncInvoicePreview() {
        if(simName) simName.innerText = inputName.value.trim() !== "" ? inputName.value : "PT. CNC Metalindo";
        if(simEmail) simEmail.innerText = inputEmail.value.trim() !== "" ? inputEmail.value : "admin@perusahaan.com";
        if(simPhone) simPhone.innerText = inputPhone.value.trim() !== "" ? inputPhone.value : "0812-XXXX";
    }

    document.querySelectorAll('.live-sync').forEach(element => {
        element.addEventListener('input', syncInvoicePreview);
    });
    syncInvoicePreview();

    // ==========================================
    // REAL-TIME LOCAL FILES UPLOAD PREVIEWS
    // ==========================================
    window.previewLogoFile = function(input) {
        const preview = document.getElementById('logoPreviewImage');
        const simPreviewImg = document.getElementById('simLogoImg');
        const simContainer = document.getElementById('simLogo');

        if (input.files && input.files[0]) {
            const reader = new FileReader();

            reader.onload = function(e) {
                // Animate preview transition
                if (preview) {
                    preview.style.opacity = '0';
                    setTimeout(() => {
                        preview.setAttribute('src', e.target.result);
                        preview.style.opacity = '1';
                    }, 150);
                }

                // Sync directly to invoice simulation header
                if (simPreviewImg) {
                    simPreviewImg.setAttribute('src', e.target.result);
                } else if(simContainer) {
                    simContainer.innerHTML = `<img id="simLogoImg" class="max-h-full max-w-full object-contain" src="${e.target.result}">`;
                }
            }

            reader.readAsDataURL(input.files[0]);
        }
    };

    window.previewFaviconFile = function(input) {
        const preview = document.getElementById('faviconPreviewImage');

        if (input.files && input.files[0]) {
            const reader = new FileReader();

            reader.onload = function(e) {
                if (preview) {
                    preview.style.opacity = '0';
                    setTimeout(() => {
                        preview.setAttribute('src', e.target.result);
                        preview.style.opacity = '1';
                    }, 150);
                }
            }

            reader.readAsDataURL(input.files[0]);
        }
    };

    // ==========================================
    // SYSTEM DARK MODE CONTROLLER
    // ==========================================
    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";
        }
    };

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

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