<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$staff_id = (int) ($_POST['staff_id'] ?? 0);

if ($staff_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid staff ID']);
    exit();
}

$current_user_id = (int) ($_SESSION['user_id'] ?? 0);

// Check if staff exists
$check_stmt = mysqli_prepare($conn, "SELECT id, name FROM staff_distribution_list WHERE id = ? AND deleted_at IS NULL");
if (!$check_stmt) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit();
}

mysqli_stmt_bind_param($check_stmt, "i", $staff_id);
mysqli_stmt_execute($check_stmt);
$check_result = mysqli_stmt_get_result($check_stmt);
$existing_staff = mysqli_fetch_assoc($check_result);

if (!$existing_staff) {
    echo json_encode(['success' => false, 'message' => 'Staff record not found']);
    exit();
}

// Soft delete
$stmt = mysqli_prepare($conn, "UPDATE staff_distribution_list SET deleted_at = NOW(), deleted_by = ? WHERE id = ?");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit();
}

mysqli_stmt_bind_param($stmt, "ii", $current_user_id, $staff_id);

if (mysqli_stmt_execute($stmt)) {
    logActivity(
        $conn,
        $current_user_id,
        'delete_staff',
        'Hapus kakitangan: ' . $existing_staff['name'] . ' (ID: ' . $staff_id . ')'
    );
    echo json_encode(['success' => true, 'message' => 'Staff record deleted successfully']);
    exit();
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to delete staff record']);
    exit();
}
