<?php
// get_communes.php
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/db.php';

if (!isset($_GET['wilaya_id']) || !is_numeric($_GET['wilaya_id'])) {
    echo json_encode([]);
    exit;
}

$wilaya_id = (int) $_GET['wilaya_id'];
$wilaya_code = str_pad($wilaya_id, 2, '0', STR_PAD_LEFT);

try {
    // التحقق من وجود الجدول
    $check_table = $pdo->query("SHOW TABLES LIKE 'algeria_cities'");
    if ($check_table->rowCount() == 0) {
        echo json_encode([]);
        exit;
    }
    
    $stmt = $pdo->prepare("
        SELECT id, commune_name, commune_name_ascii 
        FROM algeria_cities 
        WHERE wilaya_code = ? 
        ORDER BY commune_name_ascii ASC
    ");
    
    $stmt->execute([$wilaya_code]);
    $communes = $stmt->fetchAll();
    
    // تنظيف البيانات
    foreach ($communes as &$commune) {
        // التأكد من وجود الأسماء
        if (empty($commune['commune_name'])) {
            $commune['commune_name'] = $commune['commune_name_ascii'];
        }
        if (empty($commune['commune_name_ascii'])) {
            $commune['commune_name_ascii'] = $commune['commune_name'];
        }
        
        // إزالة أي علامات استفهام
        $commune['commune_name'] = preg_replace('/\?+/', '', $commune['commune_name']);
        $commune['commune_name_ascii'] = preg_replace('/\?+/', '', $commune['commune_name_ascii']);
    }
    
    echo json_encode($communes, JSON_UNESCAPED_UNICODE);
    
} catch (PDOException $e) {
    echo json_encode([]);
}
?>