<?php 
if ($mod == ''){
    header('location:../404');
    echo 'kosong';
}else{
    include_once 'mod/sw-header.php';
    include 'sw-config.php'; // koneksi db

    if(!isset($_COOKIE['COOKIES_MEMBER'])){
        header("location:index");
    }else{

        // 🔹 Ambil nama user dari tabel employees
        $employees_name = "";
        if (isset($_COOKIE['COOKIES_MEMBER'])) {
            $id_login = intval($_COOKIE['COOKIES_MEMBER']); 
            $qUser = $connection->query("SELECT employees_name FROM employees WHERE id = '$id_login' LIMIT 1");
            if ($qUser && $qUser->num_rows > 0) {
                $rowUser = $qUser->fetch_assoc();
                $employees_name = $rowUser['employees_name'];
            }
        }

        $logFile = __DIR__ . "/izin.log";

        // Proses Simpan
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $tanggal     = $_POST['tanggal'];
            $nama        = $employees_name; // 🔹 otomatis dari login
            $jenis_izin  = $_POST['jenis_izin'];
            $keterangan  = $_POST['keterangan'];
            $status      = $_POST['status'];

            // Upload Foto
            $foto = "";
            if(isset($_FILES['foto']) && $_FILES['foto']['error'] == 0){
                $target = "uploads/".basename($_FILES['foto']['name']);
                if(move_uploaded_file($_FILES['foto']['tmp_name'], $target)){
                    $foto = $_FILES['foto']['name'];
                }
            }

            // Query Insert
            $sql = "INSERT INTO izin 
                    (tanggal, nama, jenis_izin, keterangan, status, foto, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())";

            $stmt = $connection->prepare($sql);
            if(!$stmt){
                file_put_contents($logFile, date("Y-m-d H:i:s")." - Query Error: ".$connection->error.PHP_EOL, FILE_APPEND);
                die("Query Error: " . $connection->error);
            }

            $stmt->bind_param("ssssss", $tanggal, $nama, $jenis_izin, $keterangan, $status, $foto);

            if ($stmt->execute()) {
                echo '<div class="alert alert-success m-3">✅ Data izin berhasil disimpan</div>';
                file_put_contents($logFile, date("Y-m-d H:i:s")." - Data izin tersimpan: ".$nama." (".$tanggal.")".PHP_EOL, FILE_APPEND);

                echo '<meta http-equiv="refresh" content="2;url=?mod=izin">';
            } else {
                echo '<div class="alert alert-danger m-3">❌ Gagal simpan: '.$stmt->error.'</div>';
                file_put_contents($logFile, date("Y-m-d H:i:s")." - ERROR simpan: ".$stmt->error.PHP_EOL, FILE_APPEND);
            }
            $stmt->close();
        }

        // Form Input
        echo '
        <!-- App Capsule -->
        <div id="appCapsule">
            <div class="section mt-3 text-center">
                <h3>📝 Formulir Izin</h3>
            </div>

            <div class="section mt-2 mb-2">
                <div class="card">
                    <div class="card-body">
                        <form action="" method="POST" enctype="multipart/form-data">

                            <!-- Tanggal -->
                            <div class="form-group boxed">
                                <div class="input-wrapper">
                                    <label class="label">Tanggal</label>
                                    <input type="date" name="tanggal" class="form-control" required>
                                </div>
                            </div>

                            <!-- Nama (otomatis dari login employees) -->
                            <div class="form-group boxed">
                                <div class="input-wrapper">
                                    <label class="label">Nama</label>
                                    <input type="text" class="form-control" value="'.htmlspecialchars($employees_name).'" readonly>
                                    <input type="hidden" name="nama" value="'.htmlspecialchars($employees_name).'">
                                </div>
                            </div>

                            <!-- Jenis Izin -->
                            <div class="form-group boxed">
                                <div class="input-wrapper">
                                    <label class="label">Jenis Izin</label>
                                    <select class="form-control custom-select" name="jenis_izin" required>
                                        <option value="Sakit">Sakit</option>
                                        <option value="Izin">Izin</option>
                                        <option value="Cuti">Cuti</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Keterangan -->
                            <div class="form-group boxed">
                                <div class="input-wrapper">
                                    <label class="label">Keterangan</label>
                                    <textarea name="keterangan" class="form-control"></textarea>
                                </div>
                            </div>

                            <!-- Status -->
                            <div class="form-group boxed">
                                <div class="input-wrapper">
                                    <label class="label">Status</label>
                                    <select class="form-control custom-select" name="status" required>
                                        <option value="Pending">Pending</option>
                                        <option value="Disetujui">Disetujui</option>
                                        <option value="Ditolak">Ditolak</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Foto -->
                            <div class="form-group boxed">
                                <div class="input-wrapper">
                                    <label class="label">Upload Foto (opsional)</label>
                                    <input type="file" name="foto" class="form-control">
                                </div>
                            </div>

                            <hr>
                            <button type="submit" class="btn btn-primary btn-block">✅ Simpan</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <!-- * App Capsule -->
        ';
    }
    include_once 'mod/sw-footer.php';
}
?>
