<?php
try {
    header("Content-Type: application/json");

    include_once dirname(__DIR__, 2) . "/config/dbcon.php";
    include_once dirname(__DIR__, 2) . "/helpers/api_helper.php";

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(405, "Method Not Allowed");
        exit;
    }

    $input = json_decode(file_get_contents("php://input"), true);

    $id = $input['id'] ?? null;
    validateFeild($id, "Country Id");

    $stmt = $conn->prepare("
        SELECT id, state_name
        FROM states
        WHERE country_id = ?
          AND deleted_at IS NULL
        ORDER BY state_name ASC
    ");

    $stmt->execute([$id]);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    sendResponse(200, "States fetched successfully", $result);
    exit;

} catch (Throwable $e) {
    sendResponse(500, "Server Error", [
        "error" => $e->getMessage()
    ]);
    exit;
}
