<?php
session_start();
require_once '../config.php';

// Check if admin is authenticated
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit();
}

// Check session timeout (2 hours)
if (isset($_SESSION['login_time']) && (time() - $_SESSION['login_time']) > 7200) {
    session_destroy();
    header('Location: admin_login.php?timeout=1');
    exit();
}

// Validate and sanitize agent ID
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $agentId = (int) $_GET['id'];

    // Delete the agent
    $stmt = mysqli_prepare($conn, "DELETE FROM agents WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $agentId);
    mysqli_stmt_execute($stmt);

    // Check if any row was deleted
    if (mysqli_stmt_affected_rows($stmt) > 0) {
        // Log the deletion
        error_log("Agent deleted: ID " . $agentId . " by admin " . $_SESSION['admin_username']);
        
        // Redirect back to admin dashboard with success message
        header("Location: ../index.php?deleted=1");
        exit();
    } else {
        // Redirect with error message
        header("Location: ../index.php?error=agent_not_found");
        exit();
    }

    mysqli_stmt_close($stmt);
} else {
    header("Location: ../index.php?error=invalid_id");
    exit();
}
?>
