<?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 = $_GET['q'] ?? '';
    
    if (strlen($query) < 2) {
        echo json_encode(['success' => true, 'data' => []]);
        return;
    }
    
    $searchTerm = "%$query%";
    $results = [];
    
    // البحث في المستخدمين
    $userQuery = "SELECT 
                    id,
                    CONCAT(first_name, ' ', last_name) as title,
                    email as subtitle,
                    'user' as type,
                    'fa-user' as icon
                  FROM users
                  WHERE first_name LIKE :search OR last_name LIKE :search OR email LIKE :search OR phone LIKE :search
                  LIMIT 5";
    $userStmt = $db->prepare($userQuery);
    $userStmt->execute(['search' => $searchTerm]);
    $users = $userStmt->fetchAll(PDO::FETCH_ASSOC);
    $results = array_merge($results, $users);
    
    // البحث في طلبات الفحص
    $requestQuery = "SELECT 
                        ir.id,
                        ir.request_number as title,
                        CONCAT('عميل: ', u.first_name, ' ', u.last_name) as subtitle,
                        'inspection' as type,
                        'fa-clipboard-list' as icon
                      FROM inspection_requests ir
                      JOIN clients c ON ir.client_id = c.id
                      JOIN users u ON c.user_id = u.id
                      WHERE ir.request_number LIKE :search
                      LIMIT 5";
    $requestStmt = $db->prepare($requestQuery);
    $requestStmt->execute(['search' => $searchTerm]);
    $requests = $requestStmt->fetchAll(PDO::FETCH_ASSOC);
    $results = array_merge($results, $requests);
    
    // البحث في المراكز
    $centerQuery = "SELECT 
                        id,
                        name as title,
                        CONCAT(city, ' - ', address) as subtitle,
                        'center' as type,
                        'fa-building' as icon
                      FROM inspection_centers
                      WHERE name LIKE :search OR city LIKE :search OR address LIKE :search
                      LIMIT 5";
    $centerStmt = $db->prepare($centerQuery);
    $centerStmt->execute(['search' => $searchTerm]);
    $centers = $centerStmt->fetchAll(PDO::FETCH_ASSOC);
    $results = array_merge($results, $centers);
    
    echo json_encode([
        'success' => true,
        'data' => $results
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>