<?php
include "../../include/auth.php"; // Authentication
include "../../include/lskfjwfe.php"; // Database connection

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

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

// Validate user ID
if (!isset($_POST['id']) || !is_numeric($_POST['id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid user ID']);
    exit();
}

$user_id = intval($_POST['id']);

// Ensure the user exists before deleting and fetch old data
$sql_check = "SELECT username, userrole FROM users WHERE id = ?";
$stmt_check = $db->prepare($sql_check);
$stmt_check->bind_param("i", $user_id);
$stmt_check->execute();
$result_check = $stmt_check->get_result();
if ($result_check->num_rows === 0) {
    die(json_encode(['success' => false, 'message' => 'User not found']));
}
$user_data = $result_check->fetch_assoc();
$deleted_username = $user_data['username'];
$deleted_userrole_id = $user_data['userrole'];
$stmt_check->close();

// Fetch role name for logging
$sql_role = "SELECT role_name FROM user_roles WHERE role_id = ?";
$stmt_role = $db2->prepare($sql_role);
$stmt_role->bind_param("i", $deleted_userrole_id);
$stmt_role->execute();
$result_role = $stmt_role->get_result();
$deleted_role_name = $result_role->fetch_assoc()['role_name'] ?? "Unknown";
$stmt_role->close();

// Debugging: Ensure correct values before logging
error_log("Debug: Deleting user - Username: $deleted_username, Role: $deleted_role_name");

// Delete user from database
$sql_delete = "DELETE FROM users WHERE id = ?";
$stmt_delete = $db->prepare($sql_delete);
$stmt_delete->bind_param("i", $user_id);
$delete_success = $stmt_delete->execute();

if ($delete_success) {
    // Log the deletion
    $admin_username = $_SESSION['username'];
    $log_action = "Deleted user";
    $log_message = "$deleted_username ($deleted_role_name) deleted by $admin_username";

    // Ensure UTF-8 encoding only for this query
    $db2->query("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");

    $log_sql = "INSERT INTO settings_log (username, action, setting_name, old_value, new_value, timestamp)
                VALUES (?, ?, 'User Deletion', ?, NULL, NOW())";

    $stmt_log = $db2->prepare($log_sql);
    if (!$stmt_log) {
        die(json_encode(['success' => false, 'message' => 'Log Statement Error: ' . $db2->error]));
    }

    $stmt_log->bind_param("sss", $admin_username, $log_action, $log_message);
    $execute_log = $stmt_log->execute();
    if (!$execute_log) {
        die(json_encode(['success' => false, 'message' => 'Log Execution Error: ' . $stmt_log->error]));
    }

    $stmt_log->close();

    echo json_encode(['success' => true, 'message' => 'User deleted successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to delete user']);
}
?>
