<?php
/**
 * API: تسجيل متدرب جديد
 * POST /api/client/endpoints/trainee-register.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";

// قراءة البيانات المرسلة
$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 = 'TRN-' . 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 = 'trainee';
    $username = $baseUsername;
    $counter = 1;
    while (true) {
        $checkUser = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $checkUser->execute([$username]);
        if ($checkUser->rowCount() == 0) break;
        $username = $baseUsername . $counter;
        $counter++;
    }
    
    // ============================================
    // 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 (
        ?, ?, ?, ?, ?, 'trainee', 
        ?, ?, ?, ?, ?, 
        ?, 1, 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;
    
    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);
        if ($photoPath) {
            $pdo->prepare("UPDATE users SET profile_image = ? WHERE id = ?")->execute([$photoPath, $userId]);
        }
    }
    
    // ============================================
    // 3. التحقق من وجود جدول trainees
    // ============================================
    $traineeTableCheck = $pdo->query("SHOW TABLES LIKE 'trainees'")->rowCount();
    
    if ($traineeTableCheck == 0) {
        $createTraineeTable = "CREATE TABLE IF NOT EXISTS `trainees` (
            `id` INT AUTO_INCREMENT PRIMARY KEY,
            `user_id` INT NULL,
            `full_name` VARCHAR(100) NOT NULL,
            `email` VARCHAR(100) NOT NULL,
            `phone` VARCHAR(20) NOT NULL,
            `governorate` VARCHAR(100) NULL,
            `city` VARCHAR(100) NULL,
            `address` TEXT NULL,
            `backup_phone` VARCHAR(20) NULL,
            `relationship` VARCHAR(50) NULL,
            `photo_path` VARCHAR(255) NULL,
            `qualification` VARCHAR(100) NULL,
            `major` VARCHAR(100) NULL,
            `graduation_year` YEAR NULL,
            `university` VARCHAR(200) NULL,
            `previous_experience` TEXT NULL,
            `skills` TEXT NULL,
            `cv_path` VARCHAR(255) NULL,
            `id_card_path` VARCHAR(255) NULL,
            `status` ENUM('pending', 'accepted', 'rejected', 'in_progress', 'completed') DEFAULT 'pending',
            `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
            `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE SET NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        $pdo->exec($createTraineeTable);
    }
    
    // ============================================
    // 4. إدراج في جدول trainees
    // ============================================
    // بناء الاستعلام بدقة - التأكد من تطابق عدد الحقول مع عدد القيم
    $traineeQuery = "INSERT INTO trainees (
        user_id, 
        full_name, 
        email, 
        phone, 
        governorate, 
        city, 
        address, 
        backup_phone, 
        relationship, 
        photo_path,
        qualification, 
        major, 
        graduation_year, 
        university, 
        previous_experience, 
        skills, 
        cv_path, 
        id_card_path, 
        status
    ) VALUES (
        :user_id,
        :full_name,
        :email,
        :phone,
        :governorate,
        :city,
        :address,
        :backup_phone,
        :relationship,
        :photo_path,
        :qualification,
        :major,
        :graduation_year,
        :university,
        :previous_experience,
        :skills,
        :cv_path,
        :id_card_path,
        'pending'
    )";
    
    $traineeStmt = $pdo->prepare($traineeQuery);
    
    $traineeStmt->execute([
        ':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,
        ':qualification' => $input['qualification'] ?? null,
        ':major' => $input['major'] ?? null,
        ':graduation_year' => $input['graduationYear'] ?? null,
        ':university' => $input['university'] ?? null,
        ':previous_experience' => $input['previousExperience'] ?? null,
        ':skills' => $input['skills'] ?? null,
        ':cv_path' => $cvPath,
        ':id_card_path' => $idCardPath
    ]);
    
    $traineeId = $pdo->lastInsertId();
    
    // ============================================
    // 5. إدراج في جدول 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, qualification, photo_path, status, created_at
    ) VALUES (
        ?, ?, ?, ?, ?, ?, 'trainee', 
        ?, ?, ?, ?, ?, 
        ?, ?, ?, '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['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' => 'trainee',
            '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;
    }
}
?>