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

// Cek login
cek_login();

// Cek akses admin
if ($_SESSION['role'] != 'admin') {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

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

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

// Tidak bisa hapus diri sendiri
if ($id == $_SESSION['user_id']) {
    header("Location: " . BASE_URL . "/modules/users/index.php?error=" . urlencode("Anda tidak dapat menghapus akun sendiri!"));
    exit();
}

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

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

// Cek apakah user digunakan di tabel karyawan
$query_karyawan = "SELECT COUNT(*) as total FROM karyawan WHERE user_id = $id";
$result_karyawan = mysqli_query($conn, $query_karyawan);
$used_in_karyawan = mysqli_fetch_assoc($result_karyawan)['total'] > 0;

// Jika digunakan, set user_id di tabel karyawan menjadi NULL
if ($used_in_karyawan) {
    $update_karyawan = "UPDATE karyawan SET user_id = NULL WHERE user_id = $id";
    mysqli_query($conn, $update_karyawan);
}

// Hapus user
$delete_query = "DELETE FROM users WHERE id = $id";
if (mysqli_query($conn, $delete_query)) {
    header("Location: " . BASE_URL . "/modules/users/index.php?success=" . urlencode("User berhasil dihapus!"));
} else {
    header("Location: " . BASE_URL . "/modules/users/index.php?error=" . urlencode("Gagal menghapus user: " . mysqli_error($conn)));
}
exit();
?>