<?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
if (!cek_akses('karyawan', 'delete')) {
    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 masih memiliki data absensi atau penggajian
$query_absensi = "SELECT COUNT(*) as total FROM absensi WHERE karyawan_id = $id";
$result_absensi = mysqli_query($conn, $query_absensi);
$total_absensi = mysqli_fetch_assoc($result_absensi)['total'];

$query_gaji = "SELECT COUNT(*) as total FROM penggajian WHERE karyawan_id = $id";
$result_gaji = mysqli_query($conn, $query_gaji);
$total_gaji = mysqli_fetch_assoc($result_gaji)['total'];

if ($total_absensi > 0 || $total_gaji > 0) {
    header("Location: " . BASE_URL . "/modules/karyawan/index.php?error=" . urlencode("Karyawan tidak dapat dihapus karena masih memiliki data absensi atau penggajian!"));
    exit();
}

// Begin transaction
mysqli_begin_transaction($conn);

try {
    // Hapus data karyawan
    $delete_query = "DELETE FROM karyawan WHERE id = $id";
    
    if (mysqli_query($conn, $delete_query)) {
        // Hapus foto jika ada dan bukan default
        if (!empty($karyawan['foto']) && $karyawan['foto'] != 'default.jpg' && file_exists(FOTO_DIR . $karyawan['foto'])) {
            unlink(FOTO_DIR . $karyawan['foto']);
        }
        
        // Hapus QR Code jika ada
        if (!empty($karyawan['qrcode']) && file_exists(QR_DIR . $karyawan['qrcode'])) {
            unlink(QR_DIR . $karyawan['qrcode']);
        }
        
        // Hapus user account jika ada
        if (!empty($karyawan['user_id'])) {
            $delete_user = "DELETE FROM users WHERE id = {$karyawan['user_id']}";
            mysqli_query($conn, $delete_user);
        }
        
        // Commit transaction
        mysqli_commit($conn);
        
        header("Location: " . BASE_URL . "/modules/karyawan/index.php?success=" . urlencode("Data karyawan berhasil dihapus!"));
        exit();
    } else {
        throw new Exception("Gagal menghapus data karyawan!");
    }
} catch (Exception $e) {
    // Rollback transaction
    mysqli_rollback($conn);
    
    header("Location: " . BASE_URL . "/modules/karyawan/index.php?error=" . urlencode("Gagal menghapus data karyawan: " . $e->getMessage()));
    exit();
}
?>