<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $query = "SELECT 
                c.id,
                CONCAT(u.first_name, ' ', u.last_name) as name,
                u.email,
                u.phone,
                u.is_active,
                c.city,
                c.address,
                (SELECT COUNT(*) FROM client_cars WHERE client_id = c.id) as cars_count,
                (SELECT COUNT(*) FROM inspection_requests WHERE client_id = c.id) as inspections_count
              FROM clients c
              JOIN users u ON c.user_id = u.id
              WHERE u.is_active = 1
              ORDER BY u.first_name";
    
    $stmt = $db->prepare($query);
    $stmt->execute();
    
    $clients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $clients
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>