<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);


require 'Location.php';
use App\Location;

header('Content-Type: application/json; charset=utf-8');

try {
    $location = new Location(__DIR__ );
    
    $action = $_GET['action'] ?? '';
    $data = [];

    switch ($action) {
        case 'get_states':
            $countryId = (int)($_GET['country_id'] ?? 0);
            if ($countryId > 0) {
                $data = $location->getStatesByCountryId($countryId);
            }
            break;

        case 'get_cities':
            $stateId = (int)($_GET['state_id'] ?? 0);
            if ($stateId > 0) {
                $data = $location->getCitiesByStateId($stateId);
            }
            break;

        default:
            http_response_code(400);
            $data = ['error' => 'Invalid action'];
            break;
    }

    echo json_encode($data);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error: ' . $e->getMessage()]);
}