<?php
// PHP LOGIC (BAGIAN ATAS TIDAK DIUBAH)
ob_start();

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

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

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

// Ambil data karyawan
$query = "SELECT * FROM karyawan WHERE id = $id";
$result = mysqli_query($conn, $query);

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

$karyawan = mysqli_fetch_assoc($result);

// Cek apakah karyawan memiliki user account
$has_user = false;
$user_data = null;
if (!empty($karyawan['user_id'])) {
    $query_user = "SELECT * FROM users WHERE id = {$karyawan['user_id']}";
    $result_user = mysqli_query($conn, $query_user);
    if (mysqli_num_rows($result_user) > 0) {
        $has_user = true;
        $user_data = mysqli_fetch_assoc($result_user);
    }
}

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

// Proses edit data (LOGIC INI TETAP SAMA)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nik = sanitize($_POST['nik']);
    $nama = sanitize($_POST['nama']);
    $jenis_kelamin = sanitize($_POST['jenis_kelamin']);
    $email = sanitize($_POST['email']);
    $telepon = sanitize($_POST['telepon']);
    $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;
    
    $check_nik = "SELECT * FROM karyawan WHERE nik = '$nik' AND id != $id";
    $result_nik = mysqli_query($conn, $check_nik);
    
    if (mysqli_num_rows($result_nik) > 0) {
        $error = "NIK sudah terdaftar pada karyawan lain!";
    } else {
        $foto = $karyawan['foto'];
        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) {
                $error = "Ukuran file terlalu besar. Maksimal 2MB.";
            } else {
                $upload_dir = FOTO_DIR;
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                if (move_uploaded_file($_FILES['foto']['tmp_name'], $upload_dir . $file_name)) {
                    if ($foto != 'default.jpg' && file_exists($upload_dir . $foto)) {
                        unlink($upload_dir . $foto);
                    }
                    $foto = $file_name;
                } else {
                    $error = "Gagal mengupload foto!";
                }
            }
        }
        
        if (empty($error)) {
            mysqli_begin_transaction($conn);
            try {
                $update_query = "UPDATE karyawan SET nik = '$nik', nama = '$nama', jenis_kelamin = '$jenis_kelamin', email = '$email', telepon = '$telepon', jabatan = '$jabatan', departemen = '$departemen', tanggal_masuk = '$tanggal_masuk', status = '$status', foto = '$foto', gaji_pokok = '$gaji_pokok', tunjangan = '$tunjangan', updated_at = NOW() WHERE id = $id";
                
                if (mysqli_query($conn, $update_query)) {
                    if ($create_user && !$has_user) {
                        $username = strtolower(str_replace(' ', '', $nik));
                        $default_password = $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_karyawan = "UPDATE karyawan SET user_id = $user_id WHERE id = $id";
                            mysqli_query($conn, $update_karyawan);
                        } else {
                            throw new Exception("Gagal membuat akun pengguna!");
                        }
                    }
                    mysqli_commit($conn);
                    $success = "Data karyawan berhasil diperbarui!";
                    // Refresh data setelah update berhasil
                     header("Location: " . $_SERVER['REQUEST_URI'] . "&success=" . urlencode($success));
                     exit();
                } else {
                    throw new Exception("Gagal memperbarui data karyawan!");
                }
            } catch (Exception $e) {
                mysqli_rollback($conn);
                $error = $e->getMessage();
                if ($foto != $karyawan['foto'] && isset($file_name) && file_exists($upload_dir . $file_name)) {
                    unlink($upload_dir . $file_name);
                }
            }
        }
    }
}
// Ambil pesan sukses dari URL jika ada
if(isset($_GET['success'])) {
    $success = htmlspecialchars($_GET['success']);
}
?>

<div class="main-content flex-1 p-8">
    <div class="flex justify-between items-center mb-6">
        </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; ?>

    <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 Edit Karyawan</h3>
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <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" value="<?php echo htmlspecialchars($karyawan['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" value="<?php echo htmlspecialchars($karyawan['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" <?php echo ($karyawan['jenis_kelamin'] == 'L') ? 'selected' : ''; ?>>Laki-laki</option>
                            <option value="P" <?php echo ($karyawan['jenis_kelamin'] == 'P') ? 'selected' : ''; ?>>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" value="<?php echo htmlspecialchars($karyawan['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" value="<?php echo htmlspecialchars($karyawan['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>
                <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" value="<?php echo htmlspecialchars($karyawan['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" value="<?php echo htmlspecialchars($karyawan['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" value="<?php echo htmlspecialchars($karyawan['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" <?php echo ($karyawan['status'] == 'aktif') ? 'selected' : ''; ?>>Aktif</option>
                            <option value="nonaktif" <?php echo ($karyawan['status'] == 'nonaktif') ? 'selected' : ''; ?>>Non-Aktif</option>
                        </select>
                    </div>
                </div>
                <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="<?php echo htmlspecialchars($karyawan['gaji_pokok']); ?>" 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="<?php echo htmlspecialchars($karyawan['tunjangan']); ?>" 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 class="block text-slate-400 text-sm font-medium mb-2">Foto Saat Ini</label>
                        <?php if (!empty($karyawan['foto']) && $karyawan['foto'] != 'default.jpg' && file_exists(FOTO_DIR . $karyawan['foto'])): ?>
                            <img src="<?php echo BASE_URL . '/uploads/foto/' . htmlspecialchars($karyawan['foto']); ?>" alt="Foto Karyawan" class="w-24 h-24 object-cover rounded-lg mb-2">
                        <?php else: ?>
                            <div class="w-24 h-24 bg-slate-700 rounded-lg flex items-center justify-center text-slate-500 mb-2">
                                <i class="fas fa-user fa-2x"></i>
                            </div>
                        <?php endif; ?>
                        <label for="foto" class="block text-slate-400 text-sm font-medium mb-2">Ganti 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">
                        <?php if (!$has_user): ?>
                            <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>
                        <?php else: ?>
                            <div class="bg-slate-700/50 p-3 rounded-lg border border-slate-600">
                                <h4 class="font-semibold text-sky-400 text-sm mb-1">Informasi Akun</h4>
                                <p class="text-xs text-slate-300">Username: <span class="font-medium"><?php echo htmlspecialchars($user_data['username']); ?></span></p>
                                <p class="text-xs text-slate-400 mt-1">Akun untuk karyawan ini sudah ada.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <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 Perubahan
            </button>
        </div>
    </form>
</div>

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