<?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;
}

// Cache configuration
$cacheKey = 'wards_' . md5($district);
$cacheDir = sys_get_temp_dir() . '/luna_cache';
$cacheFile = $cacheDir . '/' . $cacheKey . '.json';
$cacheTime = 3600; // 1 hour cache

// Create cache directory if it doesn't exist
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

// Check cache first
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
    $cached = @json_decode(file_get_contents($cacheFile), true);
    if ($cached && isset($cached['wards']) && is_array($cached['wards'])) {
        echo json_encode($cached, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
}

$wards = [];

try {
    $conn = db_connect();
    if ($conn) {
        // Optimized query - using WITH (NOLOCK) for better performance on read operations
        // Keep LTRIM/RTRIM to handle potential whitespace in data
        $sql = "SELECT DISTINCT Phuong_Xa 
                FROM Address WITH (NOLOCK)
                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) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $wardName = isset($row['Phuong_Xa']) ? trim((string)$row['Phuong_Xa']) : '';
                if ($wardName !== '' && !in_array($wardName, $wards, true)) {
                    $wards[] = $wardName;
                }
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
        
        // Save to cache
        $result = ['success' => true, 'wards' => $wards];
        @file_put_contents($cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        
        echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    } 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;
}

