<?php
/**
 * API: تقديم طلب تسجيل مشرف جديد
 * POST /api/supervisor/endpoints/supervisor-request.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, 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";

// إنشاء مجلدات التحميل
$uploadBaseDir = __DIR__ . '/../../uploads/';
$uploadDirs = [
    $uploadBaseDir,
    $uploadBaseDir . 'profile/',
    $uploadBaseDir . 'cv/',
    $uploadBaseDir . 'id_cards/',
    $uploadBaseDir . 'certificates/'
];

foreach ($uploadDirs as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
}

// قراءة البيانات المرسلة
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    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);
    
    // بدء المعاملة
    $pdo->beginTransaction();
    
    // التحقق من وجود البريد الإلكتروني أو رقم الهاتف
    $check = $pdo->prepare("SELECT id FROM users WHERE email = ? OR phone = ?");
    $check->execute([$input['email'], $input['phone']]);
    if ($check->rowCount() > 0) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'البريد الإلكتروني أو رقم الهاتف مسجل بالفعل']);
        exit;
    }
    
    // توليد رقم طلب فريد
    $requestNumber = 'SUP-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
    $hashedPassword = password_hash($input['password'], PASSWORD_DEFAULT);
    
    // توليد اسم مستخدم مؤقت
    $baseUsername = strtolower(preg_replace('/[^a-z0-9]/', '', explode('@', $input['email'])[0]));
    if (empty($baseUsername)) $baseUsername = 'supervisor';
    $username = $baseUsername . '_' . rand(100, 999);
    
    // ============================================
    // 1. إدراج المستخدم في جدول users (بدون تفعيل)
    // ============================================
    $userStmt = $pdo->prepare("INSERT INTO users (
        username, full_name, email, phone, password, role, 
        governorate, area, address, backup_phone, relationship, 
        request_number, is_active, created_at
    ) VALUES (
        ?, ?, ?, ?, ?, 'pending', 
        ?, ?, ?, ?, ?, 
        ?, 0, NOW()
    )");
    
    $userStmt->execute([
        $username,
        $input['fullName'],
        $input['email'],
        $input['phone'],
        $hashedPassword,
        $input['governorate'],
        $input['city'] ?? null,
        $input['address'] ?? null,
        $input['backupPhone'] ?? null,
        $input['relationship'] ?? null,
        $requestNumber
    ]);
    $userId = $pdo->lastInsertId();
    
    // ============================================
    // 2. حفظ الملفات
    // ============================================
    $cvPath = null;
    $idCardPath = null;
    $photoPath = null;
    $certFilesJson = null;
    
    if (!empty($input['cvFile'])) {
        $cvPath = saveBase64File($input['cvFile'], 'cv', $userId);
    }
    if (!empty($input['idCard'])) {
        $idCardPath = saveBase64File($input['idCard'], 'id_cards', $userId);
    }
    if (!empty($input['photo'])) {
        $photoPath = saveBase64File($input['photo'], 'profile', $userId);
    }
    
    // حفظ الشهادات
    $certFiles = [];
    if (!empty($input['certFiles']) && is_array($input['certFiles'])) {
        foreach ($input['certFiles'] as $cert) {
            $certPath = saveBase64File($cert['data'], 'certificates', $userId);
            if ($certPath) {
                $certFiles[] = ['name' => $cert['name'], 'path' => $certPath];
            }
        }
        $certFilesJson = json_encode($certFiles);
    }
    
    // ============================================
    // 3. إدراج في جدول supervisor_requests
    // ============================================
    $requestStmt = $pdo->prepare("INSERT INTO supervisor_requests (
        request_number, user_id, full_name, email, phone, governorate, city, address, 
        backup_phone, relationship, photo_path,
        skills, experience_years, qualification, specialization, 
        achievements, certificates, expected_salary, available_from,
        cv_path, id_card_path, cert_files, status
    ) VALUES (
        :request_number, :user_id, :full_name, :email, :phone, :governorate, :city, :address,
        :backup_phone, :relationship, :photo_path,
        :skills, :experience_years, :qualification, :specialization,
        :achievements, :certificates, :expected_salary, :available_from,
        :cv_path, :id_card_path, :cert_files, 'pending'
    )");
    
    $requestStmt->execute([
        ':request_number' => $requestNumber,
        ':user_id' => $userId,
        ':full_name' => $input['fullName'],
        ':email' => $input['email'],
        ':phone' => $input['phone'],
        ':governorate' => $input['governorate'],
        ':city' => $input['city'] ?? null,
        ':address' => $input['address'] ?? null,
        ':backup_phone' => $input['backupPhone'] ?? null,
        ':relationship' => $input['relationship'] ?? null,
        ':photo_path' => $photoPath,
        ':skills' => $input['skills'] ?? null,
        ':experience_years' => $input['experience'] ?? 0,
        ':qualification' => $input['qualification'] ?? null,
        ':specialization' => $input['specialization'] ?? null,
        ':achievements' => $input['achievements'] ?? null,
        ':certificates' => $input['certificates'] ?? null,
        ':expected_salary' => $input['expectedSalary'] ?? null,
        ':available_from' => $input['availableFrom'] ?? null,
        ':cv_path' => $cvPath,
        ':id_card_path' => $idCardPath,
        ':cert_files' => $certFilesJson
    ]);
    
    // ============================================
    // 4. إدراج في جدول registration_requests (سجل عام)
    // ============================================
    $reqStmt = $pdo->prepare("INSERT INTO registration_requests (
        request_number, user_id, full_name, email, phone, username, role, 
        governorate, area, address, backup_phone, relationship, 
        skills, experience_years, qualification, photo_path, status, created_at
    ) VALUES (
        ?, ?, ?, ?, ?, ?, 'pending_supervisor', 
        ?, ?, ?, ?, ?, 
        ?, ?, ?, ?, 'pending', NOW()
    )");
    
    $reqStmt->execute([
        $requestNumber, 
        $userId, 
        $input['fullName'], 
        $input['email'], 
        $input['phone'], 
        $username,
        $input['governorate'],
        $input['city'] ?? null,
        $input['address'] ?? null,
        $input['backupPhone'] ?? null,
        $input['relationship'] ?? null,
        $input['skills'] ?? null,
        $input['experience'] ?? 0,
        $input['qualification'] ?? null,
        $photoPath
    ]);
    
    // تأكيد المعاملة
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم تقديم طلب التسجيل كمشرف بنجاح',
        'data' => [
            'id' => $userId,
            'full_name' => $input['fullName'],
            'username' => $username,
            'email' => $input['email'],
            'phone' => $input['phone'],
            'role' => 'pending_supervisor',
            'role_name' => 'مشرف فني (قيد المراجعة)',
            'request_number' => $requestNumber,
            'status' => 'pending'
        ]
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    if (isset($pdo)) $pdo->rollBack();
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
} catch(Exception $e) {
    if (isset($pdo)) $pdo->rollBack();
    error_log("General error: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}

function saveBase64File($base64, $type, $userId) {
    if (empty($base64)) return null;
    
    try {
        $data = explode(',', $base64);
        if (count($data) < 2) return null;
        
        $fileData = base64_decode($data[1]);
        if ($fileData === false) return null;
        
        $extension = 'jpg';
        if (strpos($data[0], 'pdf') !== false) {
            $extension = 'pdf';
        } elseif (strpos($data[0], 'png') !== false) {
            $extension = 'png';
        } elseif (strpos($data[0], 'jpeg') !== false) {
            $extension = 'jpg';
        }
        
        $filename = $type . '_' . $userId . '_' . time() . '_' . rand(1000, 9999) . '.' . $extension;
        $dir = __DIR__ . '/../../uploads/' . $type . '/';
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        
        $fullPath = $dir . $filename;
        file_put_contents($fullPath, $fileData);
        
        return 'uploads/' . $type . '/' . $filename;
        
    } catch (Exception $e) {
        error_log("File save error: " . $e->getMessage());
        return null;
    }
}
?>