<?php
declare(strict_types=1);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../security/auth_guard_api.php';

$stateId = isset($_GET['state_id']) ? (int)$_GET['state_id'] : 0;

if ($stateId <= 0) {
    Response::error('Invalid state id', 422);
}

$db = Database::getInstance();

/**
 * Ensure state exists and is active
 */
$stmt = $db->prepare("
    SELECT id
    FROM states
    WHERE id = :id AND status = 'Active'
");
$stmt->execute(['id' => $stateId]);

if (!$stmt->fetch()) {
    Response::error('State not found or inactive', 404);
}

/**
 * Load active cities for state
 */
$stmt = $db->prepare("
    SELECT id, city_name, status
    FROM cities
    WHERE state_id = :state_id
      AND status = 'Active'
    ORDER BY city_name ASC
");

$stmt->execute(['state_id' => $stateId]);
$cities = $stmt->fetchAll(PDO::FETCH_ASSOC);

Response::success('Cities loaded', $cities);
