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

// Cek login
cek_login();

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

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

// Inisialisasi variabel
$karyawan_id = '';
$tanggal = date('Y-m-d');
$jam_masuk = '';
$jam_keluar = '';
$status = 'hadir';
$keterangan = '';

// Ambil daftar karyawan
$query_karyawan = "SELECT * FROM karyawan WHERE status = 'aktif' ORDER BY nama ASC";
$result_karyawan = mysqli_query($conn, $query_karyawan);

// Proses tambah data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $karyawan_id = sanitize($_POST['karyawan_id']);
    $tanggal = sanitize($_POST['tanggal']);
    $jam_masuk = sanitize($_POST['jam_masuk']);
    $jam_keluar = sanitize($_POST['jam_keluar']);
    $status = sanitize($_POST['status']);
    $keterangan = sanitize($_POST['keterangan']);
    
    if (empty($karyawan_id) || empty($tanggal) || empty($status)) {
        $error = "Karyawan, tanggal, dan status harus diisi!";
    } else {
        $check_query = "SELECT * FROM absensi WHERE karyawan_id = $karyawan_id AND tanggal = '$tanggal'";
        $check_result = mysqli_query($conn, $check_query);
        
        if (mysqli_num_rows($check_result) > 0) {
            $error = "Karyawan ini sudah memiliki data absensi pada tanggal tersebut!";
        } else {
            $insert_query = "INSERT INTO absensi (karyawan_id, tanggal, jam_masuk, jam_keluar, status, keterangan) 
                             VALUES ($karyawan_id, '$tanggal', " . 
                             (!empty($jam_masuk) ? "'$jam_masuk'" : "NULL") . ", " . 
                             (!empty($jam_keluar) ? "'$jam_keluar'" : "NULL") . ", " . 
                             "'$status', '$keterangan')";
            
            if (mysqli_query($conn, $insert_query)) {
                header("Location: " . BASE_URL . "/modules/absensi/index.php?success=" . urlencode("Data absensi berhasil ditambahkan!"));
                exit();
            } else {
                $error = "Gagal menambahkan 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">Tambah Data Absensi</h2>
            <p class="text-slate-400">Menambahkan data kehadiran karyawan secara manual.</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; ?>
    
    <div class="glass-effect p-6 rounded-xl shadow-lg">
        <form method="POST" action="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="space-y-4">
                    <div>
                        <label for="karyawan_id" class="block text-slate-400 text-sm font-medium mb-2">Karyawan <span class="text-red-400">*</span></label>
                        <select name="karyawan_id" id="karyawan_id" 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="">Pilih Karyawan</option>
                            <?php while ($row = mysqli_fetch_assoc($result_karyawan)): ?>
                            <option value="<?php echo $row['id']; ?>" <?php echo ($karyawan_id == $row['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($row['nama']) . ' (' . htmlspecialchars($row['nik']) . ')'; ?>
                            </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label for="tanggal" class="block text-slate-400 text-sm font-medium mb-2">Tanggal <span class="text-red-400">*</span></label>
                        <input type="date" name="tanggal" id="tanggal" value="<?php echo htmlspecialchars($tanggal); ?>" 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>
                    </div>

                    <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 ($status == 'hadir') ? 'selected' : ''; ?>>Hadir</option>
                            <option value="izin" <?php echo ($status == 'izin') ? 'selected' : ''; ?>>Izin</option>
                            <option value="sakit" <?php echo ($status == 'sakit') ? 'selected' : ''; ?>>Sakit</option>
                            <option value="cuti" <?php echo ($status == 'cuti') ? 'selected' : ''; ?>>Cuti</option>
                            <option value="alpha" <?php echo ($status == 'alpha') ? 'selected' : ''; ?>>Alpha (Tanpa Keterangan)</option>
                        </select>
                    </div>
                </div>
                
                <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($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($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>
                        <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($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 Data
                </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;

        if (!isHadir) {
            jamMasukField.value = '';
            jamKeluarField.value = '';
        }
    }

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

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