<?php
require_once '../db_connect.php';

header('Content-Type: application/json');

$action = isset($_GET['action']) ? $_GET['action'] : '';

switch($action) {
    case 'regions':
        $result = mysqli_query($conn, "SELECT id, name FROM regions ORDER BY name");
        $regions = [];
        while($row = mysqli_fetch_assoc($result)) {
            $regions[] = $row;
        }
        echo json_encode(['success' => true, 'data' => $regions]);
        break;

    case 'districts':
        $region_id = isset($_GET['region_id']) ? intval($_GET['region_id']) : 0;
        if($region_id > 0) {
            $result = mysqli_query($conn, "SELECT id, name FROM districts WHERE region_id = $region_id ORDER BY name");
            $districts = [];
            while($row = mysqli_fetch_assoc($result)) {
                $districts[] = $row;
            }
            echo json_encode(['success' => true, 'data' => $districts]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Region ID required']);
        }
        break;

    case 'villages':
        $district_id = isset($_GET['district_id']) ? intval($_GET['district_id']) : 0;
        if($district_id > 0) {
            $result = mysqli_query($conn, "SELECT id, name FROM villages WHERE district_id = $district_id ORDER BY name");
            $villages = [];
            while($row = mysqli_fetch_assoc($result)) {
                $villages[] = $row;
            }
            echo json_encode(['success' => true, 'data' => $villages]);
        } else {
            echo json_encode(['success' => false, 'message' => 'District ID required']);
        }
        break;

    case 'add_village':
        session_start();
        if(!isset($_SESSION['user_id'])) {
            echo json_encode(['success' => false, 'message' => 'Not authenticated']);
            exit;
        }

        $district_id = isset($_POST['district_id']) ? intval($_POST['district_id']) : 0;
        $village_name = isset($_POST['name']) ? mysqli_real_escape_string($conn, trim($_POST['name'])) : '';
        $user_id = $_SESSION['user_id'];

        if($district_id > 0 && !empty($village_name)) {
            // Check if village already exists
            $check = mysqli_query($conn, "SELECT id FROM villages WHERE district_id = $district_id AND name = '$village_name'");
            if(mysqli_num_rows($check) > 0) {
                $existing = mysqli_fetch_assoc($check);
                echo json_encode(['success' => true, 'data' => ['id' => $existing['id'], 'name' => $village_name], 'message' => 'Village already exists']);
            } else {
                mysqli_query($conn, "INSERT INTO villages (district_id, name, added_by) VALUES ($district_id, '$village_name', $user_id)");
                $new_id = mysqli_insert_id($conn);
                echo json_encode(['success' => true, 'data' => ['id' => $new_id, 'name' => $village_name], 'message' => 'Village added']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'District ID and village name required']);
        }
        break;

    case 'village_details':
        $village_id = isset($_GET['village_id']) ? intval($_GET['village_id']) : 0;
        if($village_id > 0) {
            $result = mysqli_query($conn, "
                SELECT v.id, v.name, v.district_id, d.name as district_name, d.region_id, r.name as region_name
                FROM villages v
                JOIN districts d ON v.district_id = d.id
                JOIN regions r ON d.region_id = r.id
                WHERE v.id = $village_id
            ");
            if($row = mysqli_fetch_assoc($result)) {
                echo json_encode(['success' => true, 'data' => $row]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Village not found']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Village ID required']);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
