<?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
cek_login();

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

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

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

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

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

$data = mysqli_fetch_assoc($result);
$error = '';
$success = '';

// Proses edit data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $jam_masuk = empty($_POST['jam_masuk']) ? null : sanitize($_POST['jam_masuk']);
    $jam_keluar = empty($_POST['jam_keluar']) ? null : sanitize($_POST['jam_keluar']);
    $status = sanitize($_POST['status']);
    $keterangan = sanitize($_POST['keterangan']);
    
    if (empty($status)) {
        $error = "Status harus dipilih!";
    } else {
        $update_query = "UPDATE absensi SET 
                        jam_masuk = " . ($jam_masuk ? "'$jam_masuk'" : "NULL") . ", 
                        jam_keluar = " . ($jam_keluar ? "'$jam_keluar'" : "NULL") . ", 
                        status = '$status', 
                        keterangan = '$keterangan',
                        updated_at = NOW() 
                        WHERE id = $id";
        
        if (mysqli_query($conn, $update_query)) {
            $success = "Data absensi berhasil diperbarui!";
            $result = mysqli_query($conn, $query); // Refresh data
            $data = mysqli_fetch_assoc($result);
        } else {
            $error = "Gagal memperbarui data absensi: " . mysqli_error($conn);
        }
    }
}
?>

<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 Absensi</h2>
            <p class="text-slate-400">Memperbarui data kehadiran karyawan.</p>
        </div>
        <a href="<?php echo BASE_URL; ?>/modules/absensi/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" role="alert">
        <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" role="alert">
        <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</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 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">Tanggal:</p>
                    <p class="font-medium text-slate-200"><?php echo tanggal_indo($data['tanggal']); ?></p>
                </div>
            </div>
        </div>
        
        <form method="POST" action="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="space-y-4">
                    <div>
                        <label for="jam_masuk" class="block text-slate-400 text-sm font-medium mb-2">Jam Masuk</label>
                        <input type="time" name="jam_masuk" id="jam_masuk" value="<?php echo htmlspecialchars($data['jam_masuk']); ?>" 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">
                        <p class="text-slate-500 text-xs mt-1">Kosongkan jika tidak hadir.</p>
                    </div>
                    <div>
                        <label for="jam_keluar" class="block text-slate-400 text-sm font-medium mb-2">Jam Keluar</label>
                        <input type="time" name="jam_keluar" id="jam_keluar" value="<?php echo htmlspecialchars($data['jam_keluar']); ?>" 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">
                        <p class="text-slate-500 text-xs mt-1">Kosongkan jika belum pulang.</p>
                    </div>
                </div>
                
                <div class="space-y-4">
                    <div>
                        <label for="status" class="block text-slate-400 text-sm font-medium mb-2">Status <span class="text-red-400">*</span></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" required>
                            <option value="hadir" <?php echo ($data['status'] == 'hadir') ? 'selected' : ''; ?>>Hadir</option>
                            <option value="izin" <?php echo ($data['status'] == 'izin') ? 'selected' : ''; ?>>Izin</option>
                            <option value="sakit" <?php echo ($data['status'] == 'sakit') ? 'selected' : ''; ?>>Sakit</option>
                            <option value="cuti" <?php echo ($data['status'] == 'cuti') ? 'selected' : ''; ?>>Cuti</option>
                            <option value="alpha" <?php echo ($data['status'] == 'alpha') ? 'selected' : ''; ?>>Alpha (Tanpa Keterangan)</option>
                        </select>
                    </div>
                    <div>
                        <label for="keterangan" class="block text-slate-400 text-sm font-medium mb-2">Keterangan</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>
            </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>
    function toggleTimeInputs() {
        const status = document.getElementById('status').value;
        const jamMasukField = document.getElementById('jam_masuk');
        const jamKeluarField = document.getElementById('jam_keluar');
        const isHadir = status === 'hadir';

        jamMasukField.disabled = !isHadir;
        jamKeluarField.disabled = !isHadir;
        
        // Don't clear values on edit page, just disable
    }

    document.getElementById('status').addEventListener('change', toggleTimeInputs);
    document.addEventListener('DOMContentLoaded', toggleTimeInputs);
</script>


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