<?php
ob_start();

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('karyawan', 'add')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

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

// Proses tambah data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validasi input
    $nik = sanitize($_POST['nik']);
    $nama = sanitize($_POST['nama']);
    $jenis_kelamin = sanitize($_POST['jenis_kelamin']);
    $tempat_lahir = sanitize($_POST['tempat_lahir']);
    $tanggal_lahir = sanitize($_POST['tanggal_lahir']);
    $alamat = sanitize($_POST['alamat']);
    $telepon = sanitize($_POST['telepon']);
    $email = sanitize($_POST['email']);
    $jabatan = sanitize($_POST['jabatan']);
    $departemen = sanitize($_POST['departemen']);
    $tanggal_masuk = sanitize($_POST['tanggal_masuk']);
    $status = sanitize($_POST['status']);
    $gaji_pokok = sanitize($_POST['gaji_pokok']);
    $tunjangan = sanitize($_POST['tunjangan']);
    $create_user = isset($_POST['create_user']) ? true : false;
    
    // Cek NIK apakah sudah ada
    $check_nik = "SELECT * FROM karyawan WHERE nik = '$nik'";
    $result_nik = mysqli_query($conn, $check_nik);
    
    if (mysqli_num_rows($result_nik) > 0) {
        $error = "NIK sudah terdaftar!";
    } else {
        // Upload foto jika ada
        $foto = 'default.jpg';
        if ($_FILES['foto']['name']) {
            $allowed_types = ['image/jpeg', 'image/jpg', 'image/png'];
            $file_type = $_FILES['foto']['type'];
            $file_size = $_FILES['foto']['size'];
            $file_name = time() . '_' . $_FILES['foto']['name'];
            
            if (!in_array($file_type, $allowed_types)) {
                $error = "Tipe file tidak didukung. Gunakan format JPG, JPEG, atau PNG.";
            } elseif ($file_size > 2097152) { // 2MB
                $error = "Ukuran file terlalu besar. Maksimal 2MB.";
            } else {
                $upload_dir = FOTO_DIR;
                
                // Buat direktori jika belum ada
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                if (move_uploaded_file($_FILES['foto']['tmp_name'], $upload_dir . $file_name)) {
                    $foto = $file_name;
                } else {
                    $error = "Gagal mengupload foto!";
                }
            }
        }
        
        // Jika tidak ada error pada upload
        if (empty($error)) {
            // Begin transaction
            mysqli_begin_transaction($conn);
            
            try {
                // Insert data karyawan
                $insert_query = "INSERT INTO karyawan (nik, nama, jenis_kelamin, tempat_lahir, tanggal_lahir, alamat, telepon, email, jabatan, departemen, tanggal_masuk, status, foto, gaji_pokok, tunjangan) 
                                 VALUES ('$nik', '$nama', '$jenis_kelamin', '$tempat_lahir', '$tanggal_lahir', '$alamat', '$telepon', '$email', '$jabatan', '$departemen', '$tanggal_masuk', '$status', '$foto', '$gaji_pokok', '$tunjangan')";
                
                if (mysqli_query($conn, $insert_query)) {
                    $karyawan_id = mysqli_insert_id($conn);
                    
                    // Buat user account jika dipilih
                    if ($create_user) {
                        $username = strtolower(str_replace(' ', '', $nik));
                        $default_password = $nik; // Default password sama dengan NIK
                        $hashed_password = password_hash($default_password, PASSWORD_DEFAULT);
                        $role = 'karyawan';
                        
                        $insert_user = "INSERT INTO users (username, password, nama, role) VALUES ('$username', '$hashed_password', '$nama', '$role')";
                        
                        if (mysqli_query($conn, $insert_user)) {
                            $user_id = mysqli_insert_id($conn);
                            
                            // Update user_id di tabel karyawan
                            $update_karyawan = "UPDATE karyawan SET user_id = $user_id WHERE id = $karyawan_id";
                            mysqli_query($conn, $update_karyawan);
                        } else {
                            throw new Exception("Gagal membuat akun pengguna!");
                        }
                    }
                    
                    // Commit transaction
                    mysqli_commit($conn);
                    
                    $success = "Data karyawan berhasil ditambahkan!";
                    
                    // Redirect setelah berhasil
                    header("Location: " . BASE_URL . "/modules/karyawan/index.php?success=" . urlencode($success));
                    exit();
                } else {
                    throw new Exception("Gagal menyimpan data karyawan!");
                }
            } catch (Exception $e) {
                // Rollback transaction
                mysqli_rollback($conn);
                $error = $e->getMessage();
                
                // Hapus file foto jika upload berhasil tapi insert gagal
                if ($foto != 'default.jpg' && file_exists($upload_dir . $file_name)) {
                    unlink($upload_dir . $file_name);
                }
            }
        }
    }
}
?>

<!-- Main Content -->
<div class="main-content flex-1 p-8">
    <div class="flex justify-between items-center mb-6">
    <!-- Judul halaman sudah diatur oleh JavaScript di footer.php, atau bisa di-set manual jika perlu -->
</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; ?>

<form method="POST" action="" enctype="multipart/form-data" class="space-y-6">
    <div class="glass-effect p-6 rounded-xl shadow-lg">
        <h3 class="text-xl font-semibold text-white mb-6 border-b border-slate-700/50 pb-4">Formulir Karyawan Baru</h3>
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Kolom 1: Data Pribadi -->
            <div class="space-y-4">
                <div>
                    <label for="nik" class="block text-slate-400 text-sm font-medium mb-2">NIK <span class="text-red-400">*</span></label>
                    <input type="text" name="nik" id="nik" 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="nama" class="block text-slate-400 text-sm font-medium mb-2">Nama Lengkap <span class="text-red-400">*</span></label>
                    <input type="text" name="nama" id="nama" 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="jenis_kelamin" class="block text-slate-400 text-sm font-medium mb-2">Jenis Kelamin <span class="text-red-400">*</span></label>
                    <select name="jenis_kelamin" id="jenis_kelamin" 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 Jenis Kelamin</option>
                        <option value="L">Laki-laki</option>
                        <option value="P">Perempuan</option>
                    </select>
                </div>
                 <div>
                    <label for="email" class="block text-slate-400 text-sm font-medium mb-2">Email</label>
                    <input type="email" name="email" id="email" 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="telepon" class="block text-slate-400 text-sm font-medium mb-2">No. Telepon</label>
                    <input type="text" name="telepon" id="telepon" 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: Data Kepegawaian -->
            <div class="space-y-4">
                <div>
                    <label for="jabatan" class="block text-slate-400 text-sm font-medium mb-2">Jabatan <span class="text-red-400">*</span></label>
                    <input type="text" name="jabatan" id="jabatan" 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="departemen" class="block text-slate-400 text-sm font-medium mb-2">Departemen</label>
                    <input type="text" name="departemen" id="departemen" 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="tanggal_masuk" class="block text-slate-400 text-sm font-medium mb-2">Tanggal Masuk <span class="text-red-400">*</span></label>
                    <input type="date" name="tanggal_masuk" id="tanggal_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" required>
                </div>
                <div>
                    <label for="status" class="block text-slate-400 text-sm font-medium mb-2">Status Karyawan <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="aktif">Aktif</option>
                        <option value="nonaktif">Non-Aktif</option>
                    </select>
                </div>
            </div>
            <!-- Kolom 3: Gaji & Foto -->
            <div class="space-y-4">
                 <div>
                    <label for="gaji_pokok" class="block text-slate-400 text-sm font-medium mb-2">Gaji Pokok <span class="text-red-400">*</span></label>
                    <input type="number" name="gaji_pokok" id="gaji_pokok" value="0" 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="tunjangan" class="block text-slate-400 text-sm font-medium mb-2">Tunjangan</label>
                    <input type="number" name="tunjangan" id="tunjangan" value="0" 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="foto" class="block text-slate-400 text-sm font-medium mb-2">Foto</label>
                    <input type="file" name="foto" id="foto" class="w-full text-sm text-slate-400 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-sky-600/50 file:text-sky-300 hover:file:bg-sky-600/70" accept="image/jpeg,image/jpg,image/png">
                    <p class="text-slate-500 text-xs mt-1">Opsional. Format: JPG, PNG. Maks: 2MB</p>
                </div>
                 <div class="pt-2">
                    <div class="flex items-center">
                        <input type="checkbox" name="create_user" id="create_user" class="h-4 w-4 rounded border-gray-300 text-sky-600 focus:ring-sky-500">
                        <label for="create_user" class="ml-2 block text-sm text-slate-300">Buat akun pengguna</label>
                    </div>
                    <p class="text-slate-500 text-xs mt-1">Username & Password default adalah NIK.</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Tombol Aksi -->
    <div class="flex justify-end gap-4">
        <a href="<?php echo BASE_URL; ?>/modules/karyawan/index.php" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors">
            Batal
        </a>
        <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>

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

?>