<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals";
$password = "bassam.bassam";

$email = isset($_GET['email']) ? $_GET['email'] : null;

if (!$email) {
    echo json_encode(['success' => false, 'message' => 'البريد الإلكتروني مطلوب']);
    exit();
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // جلب بيانات المشرف (مع ضمان عدم التكرار)
    $stmt = $pdo->prepare("SELECT * FROM supervisors WHERE email = ? ORDER BY id ASC LIMIT 1");
    $stmt->execute([$email]);
    $supervisor = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$supervisor) {
        echo json_encode(['success' => false, 'message' => 'المشرف غير موجود']);
        exit();
    }
    
    // جلب الصلاحيات
    $permStmt = $pdo->prepare("SELECT * FROM supervisor_permissions WHERE supervisor_id = ?");
    $permStmt->execute([$supervisor['id']]);
    $permissions = [];
    while ($row = $permStmt->fetch(PDO::FETCH_ASSOC)) {
        $permissions[$row['module']] = [
            'can_view' => (bool)$row['can_view'],
            'can_edit' => (bool)$row['can_edit'],
            'can_delete' => (bool)$row['can_delete'],
            'can_assign' => (bool)$row['can_assign'],
            'can_approve' => (bool)$row['can_approve']
        ];
    }
    
    // جلب المناطق (مع إزالة التكرار)
    $areaStmt = $pdo->prepare("SELECT DISTINCT area_name, governorate, city FROM supervisor_areas WHERE supervisor_id = ?");
    $areaStmt->execute([$supervisor['id']]);
    $areas = $areaStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب الفاحصين التابعين (مع إزالة التكرار)
    $inspStmt = $pdo->prepare("
        SELECT DISTINCT i.id, i.user_id, i.specialization, i.experience_years, 
               u.full_name, u.email, u.phone 
        FROM supervisor_inspectors si
        JOIN inspectors i ON si.inspector_id = i.id
        JOIN users u ON i.user_id = u.id
        WHERE si.supervisor_id = ?
    ");
    $inspStmt->execute([$supervisor['id']]);
    $inspectors = $inspStmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'supervisor' => $supervisor,
            'permissions' => $permissions,
            'areas' => $areas,
            'inspectors' => $inspectors
        ]
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>