<?php
$page_title = 'Edit Karyawan';
require_once('includes/load.php');

// Tingkat akses yang diperlukan: Level 2
page_require_level(4);

// Mendapatkan ID karyawan dari URL
$employee_id = (int)$_GET['id'];
if (!$employee_id) {
    $session->msg('d', 'ID Karyawan tidak ditemukan.');
    redirect('employees.php');
}

// Mengambil data karyawan yang akan diedit
$employee = find_by_id('employees', $employee_id);
if (!$employee) {
    $session->msg('d', 'Data Karyawan tidak ditemukan.');
    redirect('employees.php');
}

// Mengambil semua data departemen dan karyawan
$departments = find_all('departments');
$all_employees = find_all('employees');

if (isset($_POST['edit_employee'])) {
    // Mendefinisikan field-field yang wajib diisi
    $req_fields = array('first_name', 'last_name', 'email', 'hire_date', 'job_title', 'department_id');
    validate_fields($req_fields);

    // Validasi tambahan untuk department_id
    if (empty($_POST['department_id']) || $_POST['department_id'] == 0) {
        $errors[] = "Departemen harus dipilih";
    }

    // Validasi format email
    if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Format email tidak valid";
    }

    // Validasi email unik (kecuali email lama)
    if (!empty($_POST['email']) && $employee['email'] !== remove_junk($_POST['email'])) {
        $email_new = remove_junk($db->escape($_POST['email']));
        $check_email = $db->query("SELECT COUNT(*) as count FROM employees WHERE email = '{$email_new}' AND id != '{$employee_id}'");
        $email_exists = $db->fetch_assoc($check_email);
        if ($email_exists['count'] > 0) {
            $errors[] = "Email sudah terdaftar";
        }
    }

    // Validasi tanggal tidak boleh lebih dari hari ini
    if (!empty($_POST['hire_date'])) {
        $today = date('Y-m-d');
        if ($_POST['hire_date'] > $today) {
            $errors[] = "Tanggal masuk tidak boleh lebih dari hari ini";
        }
    }

    // Validasi format nomor telepon (opsional)
    if (!empty($_POST['phone_number']) && !preg_match("/^[0-9\s\-\(\)\+]+$/", $_POST['phone_number'])) {
        $errors[] = "Format nomor telepon tidak valid.";
    }

    if (empty($errors)) {
        // Membersihkan dan mengamankan data yang diterima dari form
        $first_name = remove_junk($db->escape($_POST['first_name']));
        $last_name = remove_junk($db->escape($_POST['last_name']));
        $email = remove_junk($db->escape($_POST['email']));
        $phone = !empty($_POST['phone_number']) ? remove_junk($db->escape($_POST['phone_number'])) : null;
        $kontak_darurat = !empty($_POST['kontak_darurat']) ? remove_junk($db->escape($_POST['kontak_darurat'])) : null;
        $hire_date = remove_junk($db->escape($_POST['hire_date']));
        $job_title = remove_junk($db->escape($_POST['job_title']));
        $department = (int)$_POST['department_id'];
        $manager = !empty($_POST['manager_id']) ? (int)$_POST['manager_id'] : null;

        // Gunakan prepared statements untuk keamanan
        $query = "UPDATE employees SET
                    first_name = ?,
                    last_name = ?,
                    email = ?,
                    phone_number = ?,
                    kontak_darurat = ?,
                    hire_date = ?,
                    job_title = ?,
                    department_id = ?,
                    manager_id = ?,
                    updated_at = NOW()
                  WHERE id = ?";

        $stmt = $db->prepare($query);

        if ($stmt) {
            // Perbaikan pada bind_param untuk menangani nilai NULL
            $stmt->bind_param(
                "sssssssiis",
                $first_name,
                $last_name,
                $email,
                $phone,
                $kontak_darurat,
                $hire_date,
                $job_title,
                $department,
                $manager,
                $employee_id
            );

            if ($stmt->execute()) {
                $session->msg('s', "Karyawan berhasil diperbarui!");
                redirect('employees.php', false);
            } else {
                $session->msg('d', 'Gagal memperbarui karyawan. Error: ' . $db->get_error());
                redirect('edit_employee.php?id=' . $employee_id, false);
            }
            $stmt->close();
        } else {
            $session->msg('d', 'Gagal mempersiapkan query. Error: ' . $db->get_error());
            redirect('edit_employee.php?id=' . $employee_id, false);
        }
    } else {
        // Jika ada error validasi, tampilkan pesan error
        $session->msg("d", $errors);
        redirect('edit_employee.php?id=' . $employee_id, false);
    }
}
?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-edit"></span>
                    <span>Formulir Edit Karyawan</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="edit_employee.php?id=<?php echo (int)$employee['id']; ?>" class="clearfix">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="first_name">Nama Depan *</label>
                                <input type="text" class="form-control" name="first_name" placeholder="Nama Depan" required
                                    value="<?php echo isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name']) : htmlspecialchars($employee['first_name']); ?>">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="last_name">Nama Belakang *</label>
                                <input type="text" class="form-control" name="last_name" placeholder="Nama Belakang" required
                                    value="<?php echo isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name']) : htmlspecialchars($employee['last_name']); ?>">
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="email">Email *</label>
                        <input type="email" class="form-control" name="email" placeholder="contoh@domain.com" required
                            value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : htmlspecialchars($employee['email']); ?>">
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="phone_number">Nomor Telepon</label>
                                <input type="text" class="form-control" name="phone_number" placeholder="081234567890"
                                    value="<?php echo isset($_POST['phone_number']) ? htmlspecialchars($_POST['phone_number']) : htmlspecialchars($employee['phone_number']); ?>">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="hire_date">Tanggal Masuk *</label>
                                <input type="date" class="form-control" name="hire_date" required max="<?php echo date('Y-m-d'); ?>"
                                    value="<?php echo isset($_POST['hire_date']) ? htmlspecialchars($_POST['hire_date']) : htmlspecialchars($employee['hire_date']); ?>">
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="kontak_darurat">Kontak Darurat</label>
                        <input type="text" class="form-control" name="kontak_darurat" placeholder="Nama & Nomor Kontak Darurat"
                            value="<?php echo isset($_POST['kontak_darurat']) ? htmlspecialchars($_POST['kontak_darurat']) : htmlspecialchars($employee['kontak_darurat']); ?>">
                    </div>

                    <div class="form-group">
                        <label for="job_title">Jabatan *</label>
                        <input type="text" class="form-control" name="job_title" placeholder="Misal: Staf IT" required
                            value="<?php echo isset($_POST['job_title']) ? htmlspecialchars($_POST['job_title']) : htmlspecialchars($employee['job_title']); ?>">
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="department_id">Departemen *</label>
                                <select class="form-control" name="department_id" required>
                                    <option value="">Pilih Departemen</option>
                                    <?php foreach ($departments as $dept): ?>
                                        <option value="<?php echo (int)$dept['department_id']?>"
                                            <?php
                                            // Menentukan departemen yang dipilih
                                            $selected_department = isset($_POST['department_id']) ? (int)$_POST['department_id'] : (int)$employee['department_id'];
                                            if ($selected_department === (int)$dept['department_id']) {
                                                echo 'selected';
                                            }
                                            ?>>
                                            <?php echo htmlspecialchars($dept['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="manager_id">Manajer (Opsional)</label>
                                <select class="form-control" name="manager_id">
                                    <option value="">Tidak ada Manajer</option>
                                    <?php foreach ($all_employees as $emp): ?>
                                        <?php if ($emp['id'] != $employee['id']): // Tidak bisa menjadi manajer bagi dirinya sendiri ?>
                                            <option value="<?php echo (int)$emp['id']; ?>"
                                                <?php
                                                // Menentukan manajer yang dipilih
                                                $selected_manager = isset($_POST['manager_id']) ? (int)$_POST['manager_id'] : (int)$employee['manager_id'];
                                                if ($selected_manager === (int)$emp['id']) {
                                                    echo 'selected';
                                                }
                                                ?>>
                                                <?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?>
                                                (<?php echo htmlspecialchars($emp['job_title']); ?>)
                                            </option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <small class="text-muted">* Field wajib diisi</small>
                    </div>

                    <div class="form-group">
                        <button type="submit" name="edit_employee" class="btn btn-warning">
                            <span class="glyphicon glyphicon-refresh"></span> Perbarui Karyawan
                        </button>
                        <a href="employees.php" class="btn btn-default">
                            <span class="glyphicon glyphicon-chevron-left"></span> Kembali
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>