<?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("فشل الاتصال بقاعدة البيانات");
    }
    
    $center_id = $_GET['center_id'] ?? null;
    
    $query = "SELECT 
                i.id,
                CONCAT(u.first_name, ' ', u.last_name) as name,
                u.email,
                u.phone,
                i.rating_avg,
                i.total_reviews,
                i.status,
                ic.name as center_name,
                ic.id as center_id,
                (SELECT COUNT(*) FROM inspection_requests WHERE inspector_id = i.id AND DATE(created_at) = CURDATE()) as today_tasks
              FROM inspectors i
              JOIN users u ON i.user_id = u.id
              LEFT JOIN inspection_centers ic ON i.center_id = ic.id
              WHERE i.status = 'available' AND u.is_active = 1";
    
    if ($center_id) {
        $query .= " AND i.center_id = :center_id";
    }
    
    $query .= " ORDER BY i.rating_avg DESC, today_tasks ASC";
    
    $stmt = $db->prepare($query);
    
    if ($center_id) {
        $stmt->bindValue(':center_id', $center_id);
    }
    
    $stmt->execute();
    $inspectors = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $inspectors
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>