<?php
// debug_api.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

// تسجيل البيانات الواردة
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

// إنشاء ملف سجل
$log_file = __DIR__ . '/debug_log.txt';
file_put_contents($log_file, date('Y-m-d H:i:s') . " - Request received\n", FILE_APPEND);
file_put_contents($log_file, "Data: " . print_r($input, true) . "\n", FILE_APPEND);

try {
    require_once '../../config/database.php';
    
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    file_put_contents($log_file, "Database connected successfully\n", FILE_APPEND);
    
    // إنشاء رقم طلب فريد
    $request_number = 'REQ-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    // تحضير البيانات
    $full_name = $input['fullName'] ?? 'Unknown';
    $email = $input['email'] ?? 'unknown@example.com';
    $phone = $input['phone'] ?? '00000000000';
    $governorate = $input['governorate'] ?? 'القاهرة';
    $password_hash = password_hash($input['password'] ?? 'default123', PASSWORD_DEFAULT);
    $role = $input['role'] ?? 'client';
    $role_name = getRoleName($role);
    
    // إدراج البيانات
    $sql = "INSERT INTO registration_requests (
        request_number, full_name, email, phone, governorate, 
        password_hash, role, role_name, status, created_at
    ) VALUES (
        :request_number, :full_name, :email, :phone, :governorate,
        :password_hash, :role, :role_name, 'pending', NOW()
    )";
    
    $stmt = $db->prepare($sql);
    $result = $stmt->execute([
        ':request_number' => $request_number,
        ':full_name' => $full_name,
        ':email' => $email,
        ':phone' => $phone,
        ':governorate' => $governorate,
        ':password_hash' => $password_hash,
        ':role' => $role,
        ':role_name' => $role_name
    ]);
    
    if ($result) {
        $last_id = $db->lastInsertId();
        file_put_contents($log_file, "Success: Inserted ID $last_id, Number $request_number\n", FILE_APPEND);
        
        echo json_encode([
            'success' => true,
            'message' => 'تم التسجيل بنجاح',
            'data' => [
                'id' => $last_id,
                'request_number' => $request_number,
                'full_name' => $full_name,
                'role_name' => $role_name
            ]
        ]);
    } else {
        throw new Exception("فشل في إدراج البيانات");
    }
    
} catch (Exception $e) {
    file_put_contents($log_file, "Error: " . $e->getMessage() . "\n", FILE_APPEND);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error_details' => $e->getTraceAsString()
    ]);
}

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