<?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');

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

if (empty($province)) {
    echo json_encode(['success' => false, 'message' => 'Tỉnh/Thành phố không được để trống', 'districts' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// Cache configuration
$cacheKey = 'districts_' . md5($province);
$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['districts']) && is_array($cached['districts'])) {
        echo json_encode($cached, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
}

$districts = [];

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 Quan_Huyen 
                FROM Address WITH (NOLOCK)
                WHERE LTRIM(RTRIM(Tinh_TP)) = LTRIM(RTRIM(?))
                  AND Quan_Huyen IS NOT NULL 
                  AND LTRIM(RTRIM(Quan_Huyen)) <> '' 
                ORDER BY Quan_Huyen ASC";
        $params = [$province];
        $stmt = sqlsrv_query($conn, $sql, $params);
        
        if ($stmt === false) {
            $errors = sqlsrv_errors();
            $errorMsg = 'Query failed';
            if ($errors) {
                $errorMsg = $errors[0]['message'];
            }
            error_log('get_districts.php - SQL Error: ' . $errorMsg);
            echo json_encode(['success' => false, 'message' => 'Lỗi khi truy vấn dữ liệu: ' . $errorMsg, 'districts' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            db_disconnect($conn);
            exit;
        }
        
        if ($stmt !== false) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $districtName = isset($row['Quan_Huyen']) ? trim((string)$row['Quan_Huyen']) : '';
                if ($districtName !== '' && !in_array($districtName, $districts, true)) {
                    $districts[] = $districtName;
                }
            }
            sqlsrv_free_stmt($stmt);
        }
        db_disconnect($conn);
        
        // Save to cache
        $result = ['success' => true, 'districts' => $districts];
        @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', 'districts' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
} catch (Throwable $e) {
    error_log('get_districts.php - Exception: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Lỗi khi tải dữ liệu: ' . $e->getMessage(), 'districts' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

