<?php

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

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

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

if (!$request_id || !isset($_FILES['document'])) {
    echo json_encode([
        "status" => false,
        "message" => "Missing data"
    ]);
    exit;
}

/* 🔹 FILE UPLOAD */
$upload_dir = "../../uploads/suspicious_docs/";

if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

$file_name = time() . "_" . basename($_FILES["document"]["name"]);
$target_file = $upload_dir . $file_name;

if (!move_uploaded_file($_FILES["document"]["tmp_name"], $target_file)) {
    echo json_encode([
        "status" => false,
        "message" => "Upload failed"
    ]);
    exit;
}

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

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

/* 🔹 GET USER (FOR HISTORY) */
$user_id = 0;

if (isset($_POST['user_id'])) {
    $user_id = intval($_POST['user_id']);
}

/* 🔹 HISTORY LOG */
$conn->query("
    INSERT INTO suspicious_history 
    (request_id, action_by, role, action, note)
    VALUES 
    ('$request_id', '$user_id', 'village_admin', 'approved', 'Forwarded to super admin')
");

echo json_encode([
    "status" => true,
    "message" => "Sent to Super Admin successfully"
]);