<?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();
}

// إعدادات الاتصال بقاعدة البيانات
$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. فصل البيانات حسب نوع الحساب
    // ============================================
    
    // ============================================
    // 3a. للعملاء (client) - تخزين في جدول clients
    // ============================================
    if ($role === 'client') {
        // التحقق من وجود جدول clients
        $clientsTableCheck = $pdo->query("SHOW TABLES LIKE 'clients'")->rowCount();
        
        if ($clientsTableCheck == 0) {
            // إنشاء جدول العملاء
            $createClientsTable = "CREATE TABLE IF NOT EXISTS `clients` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `user_id` INT,
                `full_name` VARCHAR(100) NOT NULL,
                `email` VARCHAR(100) NOT NULL,
                `phone` VARCHAR(20) NOT NULL,
                `governorate` VARCHAR(100),
                `city` VARCHAR(100),
                `address` TEXT,
                `backup_phone` VARCHAR(20),
                `relationship` VARCHAR(50),
                `photo_path` VARCHAR(255),
                `total_inspections` INT DEFAULT 0,
                `status` ENUM('active', 'inactive') DEFAULT 'active',
                `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 CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
            $pdo->exec($createClientsTable);
        }
        
        // إدراج العميل في جدول clients
        $clientStmt = $pdo->prepare("INSERT INTO clients (
            user_id, full_name, email, phone, governorate, city, address, 
            backup_phone, relationship, photo_path, status, created_at
        ) VALUES (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW()
        )");
        
        $clientStmt->execute([
            $userId,
            $input['fullName'],
            $input['email'],
            $input['phone'],
            $input['governorate'],
            $input['city'] ?? null,
            $input['address'] ?? null,
            $input['backupPhone'] ?? null,
            $input['relationship'] ?? null,
            $photoPath
        ]);
    }
    
    // ============================================
    // 3b. للفاحصين والمتدربين - تخزين في job_applications
    // ============================================
    elseif ($role === 'inspector' || $role === 'trainee') {
        $idCardPath = null;
        $cvPath = null;
        $licensePath = null;
        
        if (!empty($input['idCard'])) {
            $idCardPath = saveBase64File($input['idCard'], 'id_cards', $userId);
        }
        if (!empty($input['cvFile'])) {
            $cvPath = saveBase64File($input['cvFile'], 'cv', $userId);
        }
        if (!empty($input['licenseFile'])) {
            $licensePath = saveBase64File($input['licenseFile'], 'license', $userId);
        }
        
        // التحقق من وجود جدول job_applications
        $jobTableCheck = $pdo->query("SHOW TABLES LIKE 'job_applications'")->rowCount();
        
        if ($jobTableCheck == 0) {
            $createJobTable = "CREATE TABLE IF NOT EXISTS `job_applications` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `request_number` VARCHAR(50) UNIQUE,
                `user_id` INT,
                `full_name` VARCHAR(100) NOT NULL,
                `email` VARCHAR(100) NOT NULL,
                `phone` VARCHAR(20) NOT NULL,
                `governorate` VARCHAR(100),
                `city` VARCHAR(100),
                `address` TEXT,
                `backup_phone` VARCHAR(20),
                `job_role` VARCHAR(50),
                `years_experience` VARCHAR(20),
                `qualification` VARCHAR(100),
                `skills` TEXT,
                `specialization` VARCHAR(100),
                `certificates` TEXT,
                `expected_salary` DECIMAL(10,2),
                `available_from` DATE,
                `photo_path` VARCHAR(255),
                `id_card_path` VARCHAR(255),
                `cv_path` VARCHAR(255),
                `license_path` VARCHAR(255),
                `status` ENUM('pending', 'reviewed', 'accepted', 'rejected') 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 CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
            $pdo->exec($createJobTable);
        }
        
        // إدراج طلب التوظيف
        $jobStmt = $pdo->prepare("INSERT INTO job_applications (
            request_number, user_id, full_name, email, phone, governorate, city, address,
            backup_phone, job_role, years_experience, qualification, skills, specialization,
            certificates, expected_salary, available_from, photo_path, id_card_path, cv_path, license_path, status
        ) VALUES (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending'
        )");
        
        $jobStmt->execute([
            $requestNumber,
            $userId,
            $input['fullName'],
            $input['email'],
            $input['phone'],
            $input['governorate'],
            $input['city'] ?? null,
            $input['address'] ?? null,
            $input['backupPhone'] ?? null,
            $role === 'inspector' ? 'فاحص سيارات' : 'متدرب',
            $input['experience'] ?? '0',
            $input['qualification'] ?? null,
            $input['skills'] ?? null,
            $input['specialization'] ?? null,
            $input['certificates'] ?? null,
            $input['expectedSalary'] ?? null,
            $input['availableFrom'] ?? null,
            $photoPath,
            $idCardPath,
            $cvPath,
            $licensePath
        ]);
    }
    
    // ============================================
    // 3c. للشركات والمعارض - تخزين في companies
    // ============================================
    elseif ($role === 'showroom' || $role === 'company') {
        // التحقق من وجود جدول companies
        $companyTableCheck = $pdo->query("SHOW TABLES LIKE 'companies'")->rowCount();
        
        if ($companyTableCheck == 0) {
            $createCompanyTable = "CREATE TABLE IF NOT EXISTS `companies` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `request_number` VARCHAR(50) UNIQUE,
                `user_id` INT,
                `company_name` VARCHAR(200) NOT NULL,
                `commercial_record` VARCHAR(100),
                `tax_number` VARCHAR(100),
                `business_type` ENUM('showroom', 'company') DEFAULT 'company',
                `contact_name` VARCHAR(100),
                `contact_phone` VARCHAR(20),
                `contact_email` VARCHAR(100),
                `governorate` VARCHAR(100),
                `city` VARCHAR(100),
                `address` TEXT,
                `photo_path` VARCHAR(255),
                `documents` TEXT,
                `status` ENUM('pending', 'approved', 'rejected') 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 CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
            $pdo->exec($createCompanyTable);
        }
        
        // حفظ المستندات
        $docsJson = null;
        if (!empty($input['documents'])) {
            $docsData = [];
            foreach ($input['documents'] as $doc) {
                $docPath = saveBase64File($doc['data'], 'company_docs', $userId);
                if ($docPath) {
                    $docsData[] = ['name' => $doc['name'], 'path' => $docPath];
                }
            }
            $docsJson = json_encode($docsData);
        }
        
        // إدراج طلب الشركة
        $companyStmt = $pdo->prepare("INSERT INTO companies (
            request_number, user_id, company_name, commercial_record, tax_number, business_type,
            contact_name, contact_phone, contact_email, governorate, city, address,
            photo_path, documents, status, created_at
        ) VALUES (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW()
        )");
        
        $companyStmt->execute([
            $requestNumber,
            $userId,
            $input['companyName'] ?? null,
            $input['commercialRecord'] ?? null,
            $input['taxNumber'] ?? null,
            $role === 'showroom' ? 'showroom' : 'company',
            $input['fullName'],
            $input['phone'],
            $input['email'],
            $input['governorate'],
            $input['city'] ?? null,
            $input['address'] ?? null,
            $photoPath,
            $docsJson
        ]);
    }
    
    // ============================================
    // 3d. لجميع الأنواع - تخزين في 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,
        company_name, commercial_record, tax_number,
        photo_path, status, created_at
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, 
        ?, ?, ?, ?, ?, 
        ?, ?, ?,
        ?, ?, ?,
        ?, 'pending', NOW()
    )");
    
    $reqStmt->execute([
        $requestNumber, $userId, $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
    ]);
    
    // تأكيد المعاملة
    $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;
}
?>