<?php
require 'db.php';
header('Content-Type: application/json');

if (isset($_GET['state_id']) && !empty($_GET['state_id'])) {
    $state_id = (int)$_GET['state_id'];
    
    // Debug: log the request
    error_log("Fetching localities for state_id: " . $state_id);
    
    $stmt = $mysqli1->prepare("SELECT id, name FROM localities WHERE state_id = ? ORDER BY name");
    $stmt->bind_param("i", $state_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $localities = [];
    while ($row = $result->fetch_assoc()) {
        $localities[] = $row;
    }
    
    // Debug: log the results
    error_log("Found " . count($localities) . " localities");
    
    echo json_encode($localities);
} else {
    echo json_encode([]);
}
?>