<?php
require_once __DIR__ . "/../includes/admin_auth.php"; // Must be first
require_once '../includes/db.php';
require_once '../includes/mailer.php';

// ==========================
// VALIDATE REQUEST
// ==========================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: manage_users.php");
    exit;
}

$user_id = intval($_POST['user_id'] ?? 0);
$action = $_POST['action'] ?? '';
$redirect = $_POST['redirect'] ?? 'manage_users.php';

if (!$user_id || !$action) {
    header("Location: $redirect");
    exit;
}

// ==========================
// FETCH USER
// ==========================
$stmt = $conn->prepare("SELECT full_name, email, status FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    header("Location: $redirect");
    exit;
}

// ==========================
// PROCESS ACTION
// ==========================
$new_status = $user['status'];
$message = "";

switch ($action) {

    case 'activate':
        $new_status = 'active';
        $message = "Your account has been activated.";
        break;

    case 'suspend':
        $new_status = 'suspended';
        $message = "Your account has been suspended. Please contact support.";
        break;

    case 'deactivate':
        $new_status = 'deactivated';
        $message = "Your account has been deactivated.";
        break;

    case 'delete':
        $new_status = 'deleted';
        $message = "Your account has been removed.";
        break;

    default:
        header("Location: $redirect");
        exit;
}

// ==========================
// UPDATE USER STATUS
// ==========================
$update = $conn->prepare("UPDATE users SET status = ? WHERE id = ?");
$update->bind_param("si", $new_status, $user_id);
$update->execute();

// ==========================
// SEND EMAIL NOTIFICATION
// ==========================
sendMail(
    $user['email'],
    "Account Status Update",
    "Hello {$user['full_name']},\n\n{$message}\n\nRegards,\nDemoBank"
);

// ==========================
// LOG ACTION (optional)
// ==========================
$log = $conn->prepare("
    INSERT INTO security_logs (type, message)
    VALUES ('user_action', ?)
");

$logMsg = "Admin changed user ID {$user_id} status to {$new_status}";
$log->bind_param("s", $logMsg);
$log->execute();

// ==========================
// REDIRECT BACK
// ==========================
header("Location: $redirect");
exit;