<?php
/**
 * API: تسجيل مستخدم جديد
 * POST /api/client/endpoints/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();
}

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

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

// ============================================
// إعدادات الاتصال بقاعدة البيانات
// ============================================
$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 = 'REG-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
    $hashedPassword = password_hash($input['password'], PASSWORD_DEFAULT);
    $role = $input['role'];
    
    // توليد اسم مستخدم من البريد الإلكتروني
    $baseUsername = strtolower(preg_replace('/[^a-z0-9]/', '', explode('@', $input['email'])[0]));
    if (empty($baseUsername)) $baseUsername = 'user';
    $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 (
        ?, ?, ?, ?, ?, ?, 
        ?, ?, ?, ?, ?, 
        ?, 1, NOW()
    )");
    
    $userStmt->execute([
        $username,
        $input['fullName'],
        $input['email'],
        $input['phone'],
        $hashedPassword,
        $role,
        $input['governorate'],
        $input['city'] ?? null,
        $input['address'] ?? null,
        $input['backupPhone'] ?? null,
        $input['relationship'] ?? null,
        $requestNumber
    ]);
    $userId = $pdo->lastInsertId();
    
    // ============================================
    // 2. حفظ الصورة الشخصية (إذا وجدت)
    // ============================================
    $photoPath = null;
    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. إدراج في جدول registration_requests
    // ============================================
    $reqStmt = $pdo->prepare("INSERT INTO registration_requests (
        request_number, full_name, email, phone, username, role, 
        governorate, area, address, backup_phone, relationship, 
        skills, experience_years, qualification,
        company_name, commercial_record, tax_number,
        photo_path, status, created_at
    ) VALUES (
        ?, ?, ?, ?, ?, ?, 
        ?, ?, ?, ?, ?, 
        ?, ?, ?,
        ?, ?, ?,
        ?, 'pending', NOW()
    )");
    
    $reqStmt->execute([
        $requestNumber, $input['fullName'], $input['email'], $input['phone'], $username, $role,
        $input['governorate'], $input['city'] ?? null, $input['address'] ?? null, $input['backupPhone'] ?? null, $input['relationship'] ?? null,
        $input['skills'] ?? null, $input['experience'] ?? 0, $input['qualification'] ?? null,
        $input['companyName'] ?? null, $input['commercialRecord'] ?? null, $input['taxNumber'] ?? null,
        $photoPath
    ]);
    
    // ============================================
    // 4. للفاحصين والمتدربين - حسب هيكل جدول job_applications
    // ============================================
    if ($role === 'inspector' || $role === 'trainee') {
        // حفظ السيرة الذاتية
        $cvPath = null;
        if (!empty($input['cvFile'])) {
            $cvPath = saveBase64File($input['cvFile'], 'cv', $userId);
        }
        
        // حفظ رخصة القيادة (إذا وجدت)
        $licensePath = null;
        if (!empty($input['licenseFile'])) {
            $licensePath = saveBase64File($input['licenseFile'], 'license', $userId);
        }
        
        // حفظ الشهادات (إذا وجدت)
        $certificates = null;
        if (!empty($input['certificates'])) {
            $certificates = $input['certificates'];
        }
        
        // إدراج في job_applications باستخدام الأعمدة الموجودة في الجدول
        $jobStmt = $pdo->prepare("INSERT INTO job_applications (
            request_id, full_name, email, phone, job_role, years_experience, 
            qualification, skills, governorate, city, status, 
            position, experience_years, certificates, expected_salary, 
            available_from, cv_file, license_file, created_at
        ) VALUES (
            ?, ?, ?, ?, ?, ?, 
            ?, ?, ?, ?, 'pending', 
            ?, ?, ?, ?, 
            ?, ?, ?, NOW()
        )");
        
        $jobStmt->execute([
            $userId,  // request_id
            $input['fullName'],
            $input['email'],
            $input['phone'],
            $role === 'inspector' ? 'فاحص سيارات' : 'متدرب',  // job_role
            $input['experience'] ?? '0',  // years_experience
            $input['qualification'] ?? null,  // qualification
            $input['skills'] ?? null,  // skills
            $input['governorate'],
            $input['city'] ?? null,
            $role === 'inspector' ? 'فاحص' : 'متدرب',  // position
            $input['experience'] ?? 0,  // experience_years
            $certificates,  // certificates
            null,  // expected_salary
            null,  // available_from
            $cvPath,  // cv_file
            $licensePath  // license_file
        ]);
        
        // تحديث registration_requests بإضافة مسارات الملفات
        if ($cvPath) {
            $pdo->prepare("UPDATE registration_requests SET cv_path = ? WHERE request_number = ?")
                ->execute([$cvPath, $requestNumber]);
        }
    }
    
    // ============================================
    // 5. للشركات والمعارض
    // ============================================
    if ($role === 'showroom' || $role === 'company') {
        $companyStmt = $pdo->prepare("INSERT INTO companies (
            company_name, commercial_record, tax_number, business_type, 
            contact_name, contact_phone, contact_email, status, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())");
        
        $companyStmt->execute([
            $input['companyName'] ?? null, 
            $input['commercialRecord'] ?? null, 
            $input['taxNumber'] ?? null, 
            $role === 'showroom' ? 'showroom' : 'company',
            $input['fullName'],
            $input['phone'],
            $input['email']
        ]);
        
        $companyId = $pdo->lastInsertId();
        
        // حفظ المستندات
        if (!empty($input['documents']) && $companyId) {
            $docStmt = $pdo->prepare("INSERT INTO company_documents (company_id, document_path, document_name) VALUES (?, ?, ?)");
            foreach ($input['documents'] as $doc) {
                $docPath = saveBase64File($doc['data'], 'company_docs', $userId);
                if ($docPath) {
                    $docStmt->execute([$companyId, $docPath, $doc['name']]);
                }
            }
        }
    }
    
    // تأكيد المعاملة
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم إنشاء الحساب بنجاح',
        'data' => [
            'id' => $userId,
            'full_name' => $input['fullName'],
            'username' => $username,
            'email' => $input['email'],
            'phone' => $input['phone'],
            'role' => $role,
            'role_name' => getRoleName($role),
            '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;
    }
}

function getRoleName($role) {
    $roles = [
        'client' => 'عميل فردي',
        'showroom' => 'معرض سيارات',
        'inspector' => 'فاحص سيارات',
        'trainee' => 'متدرب',
        'company' => 'شركة / مؤسسة'
    ];
    return $roles[$role] ?? $role;
}
?>