<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

require_once("../config/db.php");

$visitor_id = $_POST['visitor_id'] ?? '';
$user_id    = $_POST['user_id'] ?? '';
$reason     = $_POST['reason'] ?? '';

if (!$visitor_id || !$user_id || !$reason) {
    echo json_encode([
        "status" => false,
        "message" => "Missing fields"
    ]);
    exit;
}

$query = "INSERT INTO suspicious_requests 
          (visitor_id, requested_by, reason, status, created_at)
          VALUES 
          ('$visitor_id', '$user_id', '$reason', 'pending', NOW())";

if ($conn->query($query)) {

    $request_id = $conn->insert_id;

    $history = "INSERT INTO suspicious_history 
                (request_id, role, action, created_at)
                VALUES 
                ('$request_id', 'sub_admin', 'requested', NOW())";

    $conn->query($history);

    echo json_encode([
        "status" => true,
        "message" => "Request created successfully"
    ]);

} else {

    echo json_encode([
        "status" => false,
        "message" => "DB Error: " . $conn->error
    ]);
}