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

$cp = isset($_GET['cp']) ? trim($_GET['cp']) : '';
if ($cp === '' || !is_numeric($cp)) {
    echo json_encode(['success' => false, 'message' => 'CP inválido']);
    exit;
}

if (!isset($conn) || !$conn) {
    echo json_encode(['success' => false, 'message' => 'Error de conexión a BD']);
    exit;
}

$cp = intval($cp);
$sql = "SELECT colonia FROM colonias_cp WHERE cp = ? ORDER BY colonia ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $cp);
$stmt->execute();
$result = $stmt->get_result();

$colonias = [];
while ($row = $result->fetch_assoc()) {
    $colonias[] = $row['colonia'];
}

$stmt->close();
$conn->close();

if (count($colonias) > 0) {
    echo json_encode(['success' => true, 'colonias' => $colonias]);
} else {
    echo json_encode(['success' => false, 'message' => 'No se encontraron colonias para el CP']);
}
