<?php

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

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

$data = json_decode(file_get_contents("php://input"), true);

$visitor_id = intval($data['visitor_id'] ?? 0);
$user_id    = intval($data['user_id'] ?? 0);
$note       = $conn->real_escape_string($data['note'] ?? '');

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

/* 🔹 GET USER ROLE */
$userQuery = $conn->query("SELECT role FROM users WHERE id = '$user_id'");
$user = $userQuery->fetch_assoc();

if (!$user) {
    echo json_encode(["status" => false, "message" => "User not found"]);
    exit;
}

$role = $user['role'];

/* =====================================================
   🔥 CASE 1: SUB ADMIN → REQUEST TO VILLAGE ADMIN
===================================================== */

if ($role == 'sub_admin') {

    $insert = $conn->query("
        INSERT INTO suspicious_requests 
        (visitor_id, requested_by, requested_role, reason, status)
        VALUES 
        ('$visitor_id', '$user_id', 'sub_admin', '$note', 'pending')
    ");

    if ($insert) {

        $request_id = $conn->insert_id;

        // 🔹 HISTORY
        $conn->query("
            INSERT INTO suspicious_history 
            (request_id, action_by, role, action, note)
            VALUES 
            ('$request_id', '$user_id', 'sub_admin', 'requested', '$note')
        ");

        echo json_encode([
            "status" => true,
            "message" => "Request sent to Village Admin"
        ]);
    } else {
        echo json_encode(["status" => false, "message" => "DB error"]);
    }
}

/* =====================================================
   🔥 CASE 2: VILLAGE ADMIN → DIRECT TO SUPER ADMIN
===================================================== */

elseif ($role == 'village_admin') {

    $insert = $conn->query("
        INSERT INTO suspicious_requests 
        (visitor_id, requested_by, requested_role, reason, status)
        VALUES 
        ('$visitor_id', '$user_id', 'village_admin', '$note', 'approved_by_village')
    ");

    if ($insert) {

        $request_id = $conn->insert_id;

        // 🔹 HISTORY
        $conn->query("
            INSERT INTO suspicious_history 
            (request_id, action_by, role, action, note)
            VALUES 
            ('$request_id', '$user_id', 'village_admin', 'forwarded_to_super_admin', '$note')
        ");

        echo json_encode([
            "status" => true,
            "message" => "Sent to Super Admin for approval"
        ]);
    } else {
        echo json_encode(["status" => false, "message" => "DB error"]);
    }
}

else {
    echo json_encode([
        "status" => false,
        "message" => "Invalid role"
    ]);
}