<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
require_post();
$adminUserId = as_int(get_post('admin_user_id'));
require_admin($adminUserId);
$userId = as_int(get_post('user_id'));
if ($adminUserId === $userId) respond(['success' => false, 'message' => 'You cannot delete your own account'], 400);

$conn = db();
$stmt = $conn->prepare('SELECT id, full_name, username FROM users WHERE id = ? LIMIT 1');
$stmt->bind_param('i', $userId);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
if (!$user) respond(['success' => false, 'message' => 'User not found'], 404);

$checkSales = $conn->prepare('SELECT COUNT(*) AS total FROM sales WHERE cashier_user_id = ?');
$checkSales->bind_param('i', $userId);
$checkSales->execute();
$salesCount = (int)(($checkSales->get_result()->fetch_assoc()['total'] ?? 0));
if ($salesCount > 0) {
    respond([
        'success' => false,
        'message' => 'Cannot delete this user because the account is already used in sales records.'
    ], 409);
}

$del = $conn->prepare('DELETE FROM users WHERE id = ?');
$del->bind_param('i', $userId);
if (!$del->execute()) {
    respond(['success' => false, 'message' => 'Unable to delete user: ' . $del->error], 500);
}
if ($del->affected_rows < 1) {
    respond(['success' => false, 'message' => 'User was not deleted'], 409);
}

log_activity($adminUserId, 'DELETE_USER', "Deleted user {$user['full_name']} ({$user['username']})");
respond(['success' => true, 'message' => 'User deleted']);
