<?php
if (!defined('LUNA_APP')) {
    define('LUNA_APP', true);
}

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

require_once __DIR__ . '/../config/database.php';

$province = isset($_GET['province']) ? trim((string)$_GET['province']) : '';

if ($province === '') {
    echo json_encode([
        'success' => false,
        'message' => 'Missing province parameter',
        'wards'   => [],
    ]);
    exit;
}

try {
    $conn = db_connect();
    if (!$conn) {
        echo json_encode([
            'success' => false,
            'message' => 'Database connection failed',
            'wards'   => [],
        ]);
        exit;
    }

    $sql = "SELECT DISTINCT Phuong_Xa 
            FROM AddressN 
            WHERE Tinh_TP = ? 
              AND Phuong_Xa IS NOT NULL 
              AND LTRIM(RTRIM(Phuong_Xa)) <> '' 
            ORDER BY Phuong_Xa ASC";
    $params = [$province];
    $stmt = sqlsrv_query($conn, $sql, $params);

    $wards = [];
    if ($stmt !== false) {
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            $name = isset($row['Phuong_Xa']) ? trim((string)$row['Phuong_Xa']) : '';
            if ($name !== '' && !in_array($name, $wards, true)) {
                $wards[] = $name;
            }
        }
        sqlsrv_free_stmt($stmt);
    }

    db_disconnect($conn);

    echo json_encode([
        'success' => true,
        'wards'   => $wards,
    ]);
} catch (Throwable $e) {
    error_log('get_new_wards.php error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Internal error',
        'wards'   => [],
    ]);
}


