<?php
/**
 * API: جلب طلبات تسجيل المشرفين (للمدير فقط)
 * GET /api/admin/endpoints/get_supervisor_applications.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

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);
    
    // جلب طلبات المشرفين من جدول supervisors
    $query = "SELECT 
                s.id,
                s.user_id,
                s.full_name,
                s.email,
                s.phone,
                s.governorate,
                s.city,
                s.address,
                s.backup_phone,
                s.relationship,
                s.photo_path,
                s.skills,
                s.experience_years,
                s.qualification,
                s.specialization,
                s.achievements,
                s.certificates,
                s.expected_salary,
                s.available_from,
                s.cv_path,
                s.id_card_path,
                s.cert_files,
                s.status,
                s.created_at,
                s.updated_at,
                u.username,
                u.profile_image,
                u.is_active
              FROM supervisors s
              LEFT JOIN users u ON s.user_id = u.id
              ORDER BY 
                CASE WHEN s.status = 'pending' THEN 1 ELSE 2 END,
                s.created_at DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // فك تشفير ملفات الشهادات
    foreach ($applications as &$app) {
        if ($app['cert_files']) {
            $app['cert_files'] = json_decode($app['cert_files'], true);
        }
        // إضافة رابط كامل للملفات
        if ($app['cv_path']) {
            $app['cv_url'] = '/' . $app['cv_path'];
        }
        if ($app['id_card_path']) {
            $app['id_card_url'] = '/' . $app['id_card_path'];
        }
        if ($app['photo_path']) {
            $app['photo_url'] = '/' . $app['photo_path'];
        }
    }
    
    echo json_encode([
        'success' => true,
        'data' => $applications,
        'total' => count($applications),
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>