<?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);

$request_id = intval($data['request_id'] ?? 0);
$user_id    = intval($data['user_id'] ?? 0);

if (!$request_id) {
    echo json_encode([
        "status" => false,
        "message" => "Request ID required"
    ]);
    exit;
}

/* 🔹 UPDATE STATUS */
$update = $conn->query("
    UPDATE suspicious_requests 
    SET 
        status = 'rejected_by_village',
        village_action_at = NOW()
    WHERE id = '$request_id'
");

if (!$update) {
    echo json_encode([
        "status" => false,
        "message" => "DB error"
    ]);
    exit;
}

/* 🔹 HISTORY */
$conn->query("
    INSERT INTO suspicious_history 
    (request_id, action_by, role, action, note)
    VALUES 
    ('$request_id', '$user_id', 'village_admin', 'rejected', 'Rejected by village admin')
");

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