<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/send_email.php';
require_once __DIR__ . '/../../config/csrf.php'; // CSRF helper

try {
    // Admin check
    if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
        throw new Exception("Access denied. Admins only.");
    }

    // POST request check
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception("Invalid request method. Must be POST.");
    }

    // CSRF validation
    if (!isset($_POST['csrf_token']) || !verify_csrf_token($_POST['csrf_token'])) {
        throw new Exception("Invalid CSRF token.");
    }

    // Validate user ID
    if (!isset($_POST['id']) || !is_numeric($_POST['id'])) {
        throw new Exception("Missing or invalid user ID.");
    }

    $user_id = (int)$_POST['id'];
    $admin_username = $_SESSION['username'];
    $admin_id = $_SESSION['user_id'];

    // Prevent deleting self
    if ($user_id === $admin_id) {
        throw new Exception("You cannot delete your own account.");
    }

    // Fetch user
    $stmt = $pdo->prepare("SELECT full_name, username, email, role FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        throw new Exception("User not found.");
    }

    // Soft delete
    $deleteStmt = $pdo->prepare(
        "UPDATE users SET status = 'deleted', email = CONCAT(email, '.deleted_', UNIX_TIMESTAMP()) WHERE id = ?"
    );
    $deleteStmt->execute([$user_id]);

    // Send email to systems team
    send_email(
        "systems@digivortlimited.com",
        "Systems Team",
        "User Account Deleted: {$user['username']}",
        "<p>User <b>{$user['username']}</b> has been deleted by admin <b>{$admin_username}</b>.</p>
        <p><b>Full Name:</b> {$user['full_name']}<br>
        <b>Email:</b> {$user['email']}<br>
        <b>Role:</b> {$user['role']}<br>
        <b>Deleted At:</b> " . date('Y-m-d H:i:s') . "</p>"
    );

    // Redirect with success
    header("Location: ../users/?success=user_deleted");
    exit;

} catch (Exception $e) {
    // Simple readable error
    echo "<h2>Deletion failed</h2>";
    echo "<p>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p><a href='../users/'>Go back to Users</a></p>";
    exit;
}
