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

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

$districts = [];

try {
    $conn = db_connect();
    if ($conn) {
        // Get distinct districts for the selected province from Address table
        $sql = "SELECT DISTINCT Quan_Huyen 
                FROM Address 
                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) {
            $rowCount = 0;
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $rowCount++;
                $districtName = isset($row['Quan_Huyen']) ? trim((string)$row['Quan_Huyen']) : '';
                if ($districtName !== '' && !in_array($districtName, $districts, true)) {
                    $districts[] = $districtName;
                }
            }
            sqlsrv_free_stmt($stmt);
            error_log('get_districts.php - Found ' . $rowCount . ' rows, ' . count($districts) . ' unique districts for province: [' . $province . ']');
        } else {
            error_log('get_districts.php - Query returned false for province: [' . $province . ']');
        }
        db_disconnect($conn);
    } 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;
}

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

