<?php
// api/get-inspectors.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// بيانات الاتصال بقاعدة البيانات
$host = 'localhost';
$dbname = 'digitals_autotester_db';
$username = 'digitals';
$password = 'bassam.bassam';

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في الاتصال بقاعدة البيانات']);
    exit;
}

// تحديد الفلتر (all, active)
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';

try {
    // التحقق من وجود جدول inspectors
    $checkTable = $pdo->query("SHOW TABLES LIKE 'inspectors'");
    $hasInspectorsTable = $checkTable->rowCount() > 0;
    
    if ($hasInspectorsTable) {
        // استعلام مع بيانات inspectors
        $query = "
            SELECT 
                u.id,
                u.full_name,
                u.email,
                u.phone,
                u.is_active,
                u.created_at,
                i.specialization,
                i.grade,
                i.governorate,
                i.area,
                i.max_daily_requests,
                i.current_requests,
                i.total_inspections,
                i.rating,
                i.available,
                i.years_experience,
                i.qualification
            FROM users u
            LEFT JOIN inspectors i ON u.id = i.user_id
            WHERE u.role = 'inspector'
        ";
        
        if ($filter === 'active') {
            $query .= " AND u.is_active = 1 AND i.available = 1";
        }
    } else {
        // استعلام بدون inspectors (احتياطي)
        $query = "SELECT id, full_name, email, phone, is_active, created_at 
                  FROM users 
                  WHERE role = 'inspector'";
        
        if ($filter === 'active') {
            $query .= " AND is_active = 1";
        }
    }
    
    $query .= " ORDER BY u.created_at DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $inspectors = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $inspectors,
        'count' => count($inspectors)
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في تنفيذ الاستعلام: ' . $e->getMessage()]);
}
?>