<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/sidebar.php';

// Cek login & akses
cek_login();
if (!cek_akses('penggajian', 'edit')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Cek ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: " . BASE_URL . "/modules/penggajian/index.php?error=" . urlencode("ID tidak valid!"));
    exit();
}

$id = (int)$_GET['id'];

// Ambil data
$query = "SELECT p.*, k.nama as nama_karyawan, k.nik, k.jabatan 
          FROM penggajian p JOIN karyawan k ON p.karyawan_id = k.id WHERE p.id = $id";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 0) {
    header("Location: " . BASE_URL . "/modules/penggajian/index.php?error=" . urlencode("Data penggajian tidak ditemukan!"));
    exit();
}
$data = mysqli_fetch_assoc($result);

if ($data['status'] == 'dibayar') {
    header("Location: " . BASE_URL . "/modules/penggajian/index.php?error=" . urlencode("Data gaji sudah dibayar, tidak dapat diedit!"));
    exit();
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $bonus = sanitize($_POST['bonus']) ?: 0;
    $potongan_manual = sanitize($_POST['potongan_manual']) ?: 0;
    $keterangan = sanitize($_POST['keterangan']);
    $status = sanitize($_POST['status']);
    $tanggal_bayar = empty($_POST['tanggal_bayar']) ? NULL : sanitize($_POST['tanggal_bayar']);
    
    $potongan_absensi = $data['potongan']; // Potongan asli dari absensi
    $potongan_total = $potongan_absensi + $potongan_manual;
    $total_gaji = $data['gaji_pokok'] + $data['tunjangan'] + $bonus - $potongan_total;
    
    mysqli_begin_transaction($conn);
    try {
        $update_query = "UPDATE penggajian SET bonus=$bonus, potongan=$potongan_total, total_gaji=$total_gaji, status='$status', keterangan='$keterangan', tanggal_bayar=" . ($tanggal_bayar ? "'$tanggal_bayar'" : "NULL") . ", updated_at=NOW() WHERE id=$id";
        
        if (mysqli_query($conn, $update_query)) {
            // Hapus dan insert ulang potongan manual
            mysqli_query($conn, "DELETE FROM detail_potongan WHERE penggajian_id=$id AND jenis_potongan='manual'");
            if ($potongan_manual > 0) {
                $insert_manual = "INSERT INTO detail_potongan (penggajian_id, jenis_potongan, nominal, keterangan) VALUES ($id, 'manual', $potongan_manual, '$keterangan')";
                mysqli_query($conn, $insert_manual);
            }
            
            mysqli_commit($conn);
            header("Location: " . $_SERVER['PHP_SELF'] . "?id=$id&success=" . urlencode("Data penggajian berhasil diperbarui!"));
            exit();
        } else {
            throw new Exception("Gagal memperbarui data penggajian!");
        }
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error = $e->getMessage();
    }
}

// Ambil pesan dari URL
if(isset($_GET['success'])) $success = htmlspecialchars($_GET['success']);

// Ambil potongan manual
$potongan_manual = 0;
$query_potongan_manual = "SELECT nominal FROM detail_potongan WHERE penggajian_id = $id AND jenis_potongan = 'manual'";
$result_potongan_manual = mysqli_query($conn, $query_potongan_manual);
if($row_pm = mysqli_fetch_assoc($result_potongan_manual)) {
    $potongan_manual = $row_pm['nominal'];
}
?>

<!-- Main Content -->
<div class="main-content flex-1 p-8">
    <div class="flex justify-between items-center mb-6">
        <div>
            <h2 class="text-3xl font-bold text-white">Edit Data Penggajian</h2>
            <p class="text-slate-400">Sesuaikan bonus, potongan, dan status pembayaran.</p>
        </div>
        <a href="<?php echo BASE_URL; ?>/modules/penggajian/index.php" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors">Kembali</a>
    </div>

    <?php if (!empty($error)): ?><div class="bg-red-500/20 border border-red-500/30 text-red-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3"><i class="fas fa-exclamation-circle"></i><span><?php echo htmlspecialchars($error); ?></span></div><?php endif; ?>
    <?php if (!empty($success)): ?><div class="bg-green-500/20 border border-green-500/30 text-green-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3"><i class="fas fa-check-circle"></i><span><?php echo htmlspecialchars($success); ?></span></div><?php endif; ?>
    
    <div class="glass-effect p-6 rounded-xl shadow-lg">
        <div class="bg-slate-700/50 p-4 rounded-lg border border-slate-600/80 mb-6">
            <h3 class="text-lg font-semibold text-white mb-3">Informasi Karyawan & Periode</h3>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div><p class="text-slate-400">NIK:</p><p class="font-medium text-slate-200"><?php echo htmlspecialchars($data['nik']); ?></p></div>
                <div><p class="text-slate-400">Nama:</p><p class="font-medium text-slate-200"><?php echo htmlspecialchars($data['nama_karyawan']); ?></p></div>
                <div><p class="text-slate-400">Jabatan:</p><p class="font-medium text-slate-200"><?php echo htmlspecialchars($data['jabatan']); ?></p></div>
                <div><p class="text-slate-400">Periode:</p><p class="font-medium text-slate-200"><?php echo date('F Y', mktime(0, 0, 0, $data['periode_bulan'], 1, $data['periode_tahun'])); ?></p></div>
            </div>
        </div>
        
        <form method="POST" action="">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Kolom 1: Pendapatan -->
                <div class="space-y-4">
                    <h4 class="text-lg font-semibold text-white">Pendapatan</h4>
                    <div>
                        <label class="block text-slate-400 text-sm font-medium mb-2">Gaji Pokok</label>
                        <input type="text" value="<?php echo format_rupiah($data['gaji_pokok']); ?>" class="w-full border border-slate-700 bg-slate-800/60 text-slate-300 rounded-lg px-3 py-2.5" readonly>
                    </div>
                    <div>
                        <label class="block text-slate-400 text-sm font-medium mb-2">Tunjangan</label>
                        <input type="text" value="<?php echo format_rupiah($data['tunjangan']); ?>" class="w-full border border-slate-700 bg-slate-800/60 text-slate-300 rounded-lg px-3 py-2.5" readonly>
                    </div>
                    <div>
                        <label for="bonus" class="block text-slate-400 text-sm font-medium mb-2">Bonus</label>
                        <input type="number" name="bonus" id="bonus" value="<?php echo htmlspecialchars($data['bonus']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                    </div>
                </div>
                
                <!-- Kolom 2: Potongan & Status -->
                <div class="space-y-4">
                    <h4 class="text-lg font-semibold text-white">Potongan & Status</h4>
                    <div>
                        <label class="block text-slate-400 text-sm font-medium mb-2">Potongan Absensi</label>
                        <input type="text" value="<?php echo format_rupiah($data['potongan'] - $potongan_manual); ?>" class="w-full border border-slate-700 bg-slate-800/60 text-slate-300 rounded-lg px-3 py-2.5" readonly>
                         <p class="text-slate-500 text-xs mt-1">Otomatis dari keterlambatan & alpha.</p>
                    </div>
                    <div>
                        <label for="potongan_manual" class="block text-slate-400 text-sm font-medium mb-2">Potongan Manual</label>
                        <input type="number" name="potongan_manual" id="potongan_manual" value="<?php echo htmlspecialchars($potongan_manual); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                    </div>
                     <div>
                        <label for="status" class="block text-slate-400 text-sm font-medium mb-2">Status Pembayaran</label>
                        <select name="status" id="status" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                            <option value="draft" <?php echo ($data['status'] == 'draft') ? 'selected' : ''; ?>>Draft</option>
                            <option value="disetujui" <?php echo ($data['status'] == 'disetujui') ? 'selected' : ''; ?>>Disetujui</option>
                            <option value="dibayar" <?php echo ($data['status'] == 'dibayar') ? 'selected' : ''; ?>>Dibayar</option>
                        </select>
                    </div>
                </div>

                <!-- Kolom 3: Keterangan & Total -->
                <div class="space-y-4">
                     <h4 class="text-lg font-semibold text-white">Keterangan & Total</h4>
                    <div>
                        <label for="tanggal_bayar" class="block text-slate-400 text-sm font-medium mb-2">Tanggal Bayar</label>
                        <input type="date" name="tanggal_bayar" id="tanggal_bayar" value="<?php echo htmlspecialchars($data['tanggal_bayar']); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                    </div>
                    <div>
                        <label for="keterangan" class="block text-slate-400 text-sm font-medium mb-2">Keterangan (Potongan Manual)</label>
                        <textarea name="keterangan" id="keterangan" rows="3" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5"><?php echo htmlspecialchars($data['keterangan']); ?></textarea>
                    </div>
                    <div class="bg-slate-800/50 p-4 rounded-lg border border-slate-700">
                        <h4 class="font-semibold text-sky-300 mb-1">Take Home Pay</h4>
                        <p id="total_gaji_display" class="text-3xl font-bold text-white"><?php echo format_rupiah($data['total_gaji']); ?></p>
                    </div>
                </div>
            </div>
            
            <div class="mt-8 border-t border-slate-700/50 pt-6 flex justify-end">
                <button type="submit" class="bg-sky-600 hover:bg-sky-700 text-white font-bold py-2.5 px-6 rounded-lg transition-colors flex items-center gap-2"><i class="fas fa-save"></i> Simpan Perubahan</button>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const bonusEl = document.getElementById('bonus');
        const potonganManualEl = document.getElementById('potongan_manual');
        const statusEl = document.getElementById('status');
        const tanggalBayarEl = document.getElementById('tanggal_bayar');

        const gajiPokok = <?php echo $data['gaji_pokok']; ?>;
        const tunjangan = <?php echo $data['tunjangan']; ?>;
        const potonganAbsensi = <?php echo $data['potongan'] - $potongan_manual; ?>;
        
        const formatter = new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 });

        function hitungTotalGaji() {
            const bonus = parseFloat(bonusEl.value) || 0;
            const potonganManual = parseFloat(potonganManualEl.value) || 0;
            const totalGaji = gajiPokok + tunjangan + bonus - potonganAbsensi - potonganManual;
            document.getElementById('total_gaji_display').textContent = formatter.format(totalGaji);
        }

        function handleStatusChange() {
            if (this.value === 'dibayar' && !tanggalBayarEl.value) {
                const today = new Date().toISOString().split('T')[0];
                tanggalBayarEl.value = today;
            }
        }

        bonusEl.addEventListener('input', hitungTotalGaji);
        potonganManualEl.addEventListener('input', hitungTotalGaji);
        statusEl.addEventListener('change', handleStatusChange);
    });
</script>

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/footer.php';
?>