<?php

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

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

// 📥 GET JSON INPUT
$data = json_decode(file_get_contents("php://input"), true);

// 🧾 FETCH VALUES
$user_id = intval($data['user_id'] ?? 0);
$village_id = intval($data['village_id'] ?? 0);

// ❌ VALIDATION
if (!$user_id || !$village_id) {
    echo json_encode([
        "status" => false,
        "message" => "User ID and Village ID required"
    ]);
    exit;
}

// 🔍 CHECK USER EXISTS & BELONGS TO SAME VILLAGE
$checkQuery = "SELECT id FROM users 
               WHERE id = '$user_id' 
               AND village_id = '$village_id' 
               AND role = 'sub_admin' 
               AND status = 'pending'";

$checkResult = $conn->query($checkQuery);

if ($checkResult->num_rows === 0) {
    echo json_encode([
        "status" => false,
        "message" => "User not found or already processed"
    ]);
    exit;
}

// ✅ APPROVE USER
$updateQuery = "UPDATE users 
                SET status = 'approved' 
                WHERE id = '$user_id' 
                AND village_id = '$village_id'";

if ($conn->query($updateQuery)) {
    echo json_encode([
        "status" => true,
        "message" => "User approved successfully"
    ]);
} else {
    echo json_encode([
        "status" => false,
        "message" => "Database error: " . $conn->error
    ]);
}