<?php
include_once '../config/connect.php';

// Check if the request is POST and the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['blocked_agent'])) {
    // Validate and sanitize inputs
    if (empty($_POST['agent_identifier'])) {
        header("Location: ../index?page=Blocked&msg=48"); // Missing agent name
        exit();
    }

    if (!isset($_POST['agent_status']) || !in_array($_POST['agent_status'], ['active', 'blocked'])) {
        header("Location: ../index?page=Blocked&msg=48"); // Invalid status
        exit();
    }

    $agent_identifier = trim((string)($_POST['agent_identifier'] ?? ''));
    $agent_status = mysqli_real_escape_string($call, $_POST['agent_status']);
    $targetAgent = agent_find_by_identifier($call, $agent_identifier);

    if ($targetAgent === null) {
        header("Location: ../index?page=Blocked&msg=48");
        exit();
    }

    $agent_name = mysqli_real_escape_string($call, agent_public_name($targetAgent));

    // Prepare and execute the query
    $query = "UPDATE tb_agent SET agent_status = ? WHERE agent_name = ?";
    $stmt = mysqli_prepare($call, $query);
    
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "ss", $agent_status, $agent_name);
        $result = mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);

        if ($result) {
            header("Location: ../index?page=Blocked&msg=49"); // Success
            exit();
        } else {
            header("Location: ../index?page=Blocked&msg=48"); // Database error
            exit();
        }
    } else {
        header("Location: ../index?page=Blocked&msg=48"); // Statement preparation failed
        exit();
    }
} else {
    // Not a POST request or form not submitted
    header("Location: ../index?page=Blocked");
    exit();
}
