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

    /* Custom Webkit scrollbar */
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: #f1f5f9; }
    ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }

    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;
    }
    html.dark .bg-slate-50 {
        background-color: #0f172a !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-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>
                    Administrasi & Koreksi Keuangan Karyawan
                </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>
                <?= esc($title ?? 'Ubah Transaksi Gaji') ?>
            </h1>
            <p class="text-sm text-slate-500 mt-1">Ubah draf slip gaji, alokasi tunjangan, bonus lembur, serta sanksi potongan kasir karyawan bengkel secara real-time.</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/payroll') ?>" 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/payroll/update/'.$payroll['id_payroll']) ?>" method="post" id="editPayrollForm">
        <?= csrf_field() ?>

        <div class="row g-4">
            <!-- Left Panel: Pegawai & Periode -->
            <div class="col-12 col-lg-5">
                <div class="form-section-card p-4 sm:p-5 shadow-xs h-full">
                    <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-user-tie text-indigo-500"></i>
                        Penerima & Periode Kerja
                    </h3>

                    <!-- Karyawan Selection -->
                    <div class="mb-4">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Nama Karyawan <span class="text-rose-500">*</span></label>
                        <div class="relative">
                            <select name="id_user" class="form-control-custom appearance-none pr-10" required>
                                <option value="">-- Pilih Nama Karyawan --</option>
                                <?php if(!empty($users)): ?>
                                    <?php foreach($users as $user): ?>
                                        <option value="<?= $user['id_user'] ?>" <?= ($payroll['id_user'] == $user['id_user']) ? 'selected' : '' ?>>
                                            <?= esc($user['nama_lengkap']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-slate-500">
                                <i class="fas fa-chevron-down text-xs"></i>
                            </div>
                        </div>
                    </div>

                    <!-- Periode Kerja (Month-Year Input) -->
                    <div class="mb-2">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Periode Pembayaran <span class="text-rose-500">*</span></label>
                        <div class="relative rounded-xl shadow-xs">
                            <input type="month" name="periode" class="form-control-custom" value="<?= esc($payroll['periode'] ?? '') ?>" required>
                        </div>
                        <small class="text-[10px] text-slate-400 block mt-1.5 leading-tight">Pastikan memilih periode bulan yang sesuai untuk pencatatan rekonsiliasi upah tahunan.</small>
                    </div>
                </div>
            </div>

            <div class="col-12 col-lg-7">
                <div class="form-section-card p-4 sm:p-5 shadow-xs h-full bg-slate-50/50 dark:bg-slate-900/10">
                    <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-calculator text-indigo-500"></i>
                        Kalkulator Gaji & Alokasi Keuangan
                    </h3>

                    <div class="row g-3">
                        <!-- Gaji Pokok -->
                        <div class="col-12 col-sm-4 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Gaji Pokok (Rp) <span class="text-rose-500">*</span></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">
                                    <span class="text-slate-400 text-xs font-semibold">Rp</span>
                                </div>
                                <input type="number" name="gaji_pokok" id="gaji_pokok" class="form-control-custom pl-9 calc-input" value="<?= esc($payroll['gaji_pokok'] ?? 0) ?>" min="0" required>
                            </div>
                        </div>

                        <!-- Bonus -->
                        <div class="col-12 col-sm-4 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Bonus / Lembur (Rp)</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">
                                    <span class="text-slate-400 text-xs font-semibold">Rp</span>
                                </div>
                                <input type="number" name="bonus" id="bonus" class="form-control-custom pl-9 calc-input" value="<?= esc($payroll['bonus'] ?? 0) ?>" min="0" required>
                            </div>
                        </div>

                        <!-- Potongan -->
                        <div class="col-12 col-sm-4 mb-3">
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Potongan (Rp)</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">
                                    <span class="text-slate-400 text-xs font-semibold">Rp</span>
                                </div>
                                <input type="number" name="potongan" id="potongan" class="form-control-custom pl-9 calc-input" value="<?= esc($payroll['potongan'] ?? 0) ?>" min="0" required>
                            </div>
                        </div>
                    </div>

                    <div class="mb-2">
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Total Gaji Bersih (Take Home Pay)</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">
                                <span class="text-slate-500 text-xs font-bold">Rp</span>
                            </div>
                            <input type="number" name="total_gaji" id="total_gaji" class="form-control-custom pl-9 bg-slate-100 dark:bg-slate-950 font-extrabold text-indigo-600 dark:text-indigo-400" value="<?= esc($payroll['total_gaji'] ?? 0) ?>" readonly>
                        </div>
                        
                        <!-- Real-time formatted Rupiah Badge Feedback -->
                        <div class="mt-2.5 p-3 bg-white dark:bg-slate-950/50 rounded-xl border border-slate-100 dark:border-slate-800 flex justify-between items-center text-xs">
                            <span class="text-slate-400 font-medium">Format Terbilang:</span>
                            <span id="calculatedTotalText" class="font-extrabold text-indigo-600 dark:text-indigo-400">Rp 0</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="mt-6 form-section-card p-4 shadow-xs flex flex-col sm:flex-row justify-end items-center gap-2">
            <a href="<?= base_url('owner/payroll') ?>" class="w-full sm:w-auto 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 px-5 py-3 transition-all text-center decoration-none no-underline block">
                Batalkan
            </a>
            <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"></i>
                Simpan Perubahan Gaji
            </button>
        </div>
    </form>
</div>

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

    // ==========================================
    // PAYROLL CALCULATOR (POKOK + BONUS - POTONGAN)
    // ==========================================
    const pokokInput = document.getElementById('gaji_pokok');
    const bonusInput = document.getElementById('bonus');
    const potonganInput = document.getElementById('potongan');
    const totalInput = document.getElementById('total_gaji');
    const calculatedTotalText = document.getElementById('calculatedTotalText');

    function calculateSalary() {
        const pokok = parseFloat(pokokInput.value) || 0;
        const bonus = parseFloat(bonusInput.value) || 0;
        const potongan = parseFloat(potonganInput.value) || 0;
        
        // Rumus: Gaji Pokok + Bonus - Potongan
        const total = (pokok + bonus) - potongan;

        // Pasangkan hasil mentah ke input terproteksi (readonly)
        totalInput.value = Math.max(0, Math.round(total));

        // Format visual IDR Rupiah di bagian keterangan format terbilang
        calculatedTotalText.innerText = new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            maximumFractionDigits: 0
        }).format(total);
    }

    // Pasang listener real-time pada setiap elemen input kelas '.calc-input'
    document.querySelectorAll('.calc-input').forEach(input => {
        input.addEventListener('input', calculateSalary);
    });

    // Jalankan sekali saat inisiasi muatan DOM agar perhitungan awal benar
    calculateSalary();

    // ==========================================
    // 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";
        }
    };

    // Sinkronisasi status tema gelap berdasarkan preferensi sistem/localstorage
    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() ?>