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

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