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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

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

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

if (empty($district)) {
    echo json_encode(['success' => false, 'message' => 'Quận/Huyện không được để trống', 'wards' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// Debug: Log the district value being searched
error_log('get_wards.php - Searching for district: [' . $district . '] (length: ' . strlen($district) . ')');

$wards = [];

try {
    $conn = db_connect();
    if ($conn) {
        // Get distinct wards for the selected district from Address table
        $sql = "SELECT DISTINCT Phuong_Xa 
                FROM Address 
                WHERE LTRIM(RTRIM(Quan_Huyen)) = LTRIM(RTRIM(?))
                  AND Phuong_Xa IS NOT NULL 
                  AND LTRIM(RTRIM(Phuong_Xa)) <> '' 
                ORDER BY Phuong_Xa ASC";
        $params = [$district];
        $stmt = sqlsrv_query($conn, $sql, $params);
        
        if ($stmt === false) {
            $errors = sqlsrv_errors();
            $errorMsg = 'Query failed';
            if ($errors) {
                $errorMsg = $errors[0]['message'];
            }
            error_log('get_wards.php - SQL Error: ' . $errorMsg);
            echo json_encode(['success' => false, 'message' => 'Lỗi khi truy vấn dữ liệu: ' . $errorMsg, 'wards' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            db_disconnect($conn);
            exit;
        }
        
        if ($stmt !== false) {
            $rowCount = 0;
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $rowCount++;
                $wardName = isset($row['Phuong_Xa']) ? trim((string)$row['Phuong_Xa']) : '';
                if ($wardName !== '' && !in_array($wardName, $wards, true)) {
                    $wards[] = $wardName;
                }
            }
            sqlsrv_free_stmt($stmt);
            error_log('get_wards.php - Found ' . $rowCount . ' rows, ' . count($wards) . ' unique wards for district: [' . $district . ']');
        } else {
            error_log('get_wards.php - Query returned false for district: [' . $district . ']');
        }
        db_disconnect($conn);
    } else {
        echo json_encode(['success' => false, 'message' => 'Không thể kết nối database', 'wards' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
} catch (Throwable $e) {
    error_log('get_wards.php - Exception: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Lỗi khi tải dữ liệu: ' . $e->getMessage(), 'wards' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

echo json_encode(['success' => true, 'wards' => $wards], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

