<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\AppointmentController;
use App\Http\Controllers\StatisticsController;
use App\Http\Controllers\CalendarController;
use App\Http\Controllers\UserRoleController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\PermissionController;
use App\Http\Controllers\PlanPermissionController;
use App\Http\Controllers\RolePermissionController;
use App\Http\Controllers\QueueController;
use App\Http\Controllers\TenantController;
use App\Http\Controllers\DisplayPairController;
use App\Http\Controllers\DisplayController;
use App\Http\Controllers\SettingsController;
use App\Http\Controllers\VisitTypeController;
use Illuminate\Support\Facades\Broadcast;
use App\Http\Controllers\QueueTestController;

// تغيير اللغة
Route::get('/lang/{lang}', function ($lang) {
    if (!in_array($lang, ['en', 'fr', 'ar'])) {
        abort(400);
    }
    session()->put('locale', $lang);
    return back();
})->name('change.lang');

// إعادة التوجيه للـ login
Route::get('/', function () {
    // Check if patient is authenticated
    if (Auth::guard('patient')->check()) {
        return redirect()->route('patient.dashboard');
    }
    // Check if staff user is authenticated  
    if (Auth::check()) {
        return redirect('/dashboard');
    }
    // Default redirect to staff login
    return redirect('/login');
});

// تسجيل الدخول والخروج
Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('/login', [LoginController::class, 'login']);
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');

// المسارات المحمية
Route::middleware(['auth'])->group(function () {

    // ترقية الباقة
    Route::get('/upgrade-plan', [RolePermissionController::class, 'upgrade'])->name('upgrade.plan');

    // لوحة التحكم
    Route::get('/dashboard', [DashboardController::class, 'index'])
        ->middleware('check_permission:view_dashboard')
        ->name('dashboard');

    Route::post('/next-customer', [DashboardController::class, 'getNextCustomer'])
        ->middleware('check_permission:next_customer')
        ->name('next.customer');

    Route::post('/queue/update-order', [DashboardController::class, 'updateOrder'])
        ->middleware('check_permission:manage_queue')
        ->name('queue.updateOrder');

    Route::delete('/queue/delete/{id}', [DashboardController::class, 'delete'])
        ->middleware('check_permission:delete_queue_entry');

    Route::post('/queue/update-appointment', [DashboardController::class, 'updateAppointment'])
        ->middleware('check_permission:edit_appointment')
        ->name('queue.updateAppointment');

    Route::delete('/queue/delete-appointment/{id}', [DashboardController::class, 'delete_appointment'])
        ->middleware('check_permission:delete_appointment');

    Route::patch('/queue/{id}/complete', [DashboardController::class, 'complete'])->name('queue.complete');

    // بروفايل المستخدم
    Route::get('/profile', [UserController::class, 'profile'])
        ->middleware('check_permission:view_profile')
        ->name('profile');

    Route::put('/profile', [UserController::class, 'updateProfile'])
        ->middleware('check_permission:edit_profile')
        ->name('profile.update');

    // العملاء
    Route::get("/customers", [CustomerController::class, "index"])
        ->middleware('check_permission:view_customers')
        ->name("customers.index");

    Route::get("/customers/create", [CustomerController::class, "create"])
        ->middleware('check_permission:add_customer')
        ->name("customers.create");

    Route::post("/customers", [CustomerController::class, "store"])
        ->middleware('check_permission:add_customer')
        ->name("customers.store");

    Route::get("/customers/{id}", [CustomerController::class, "show"])
        ->middleware('check_permission:view_customer_details')
        ->name("customers.show");

    Route::delete("/customers/{id}", [CustomerController::class, "destroy"])
        ->middleware('check_permission:delete_customer')
        ->name("customers.destroy");

    // المواعيد
    Route::get("/appointments/create", [AppointmentController::class, "create"])
        ->middleware('check_permission:add_appointment')
        ->name("appointments.create");

    Route::post("/appointments", [AppointmentController::class, "store"])
        ->middleware('check_permission:add_appointment')
        ->name("appointments.store");

    Route::get("/appointments/available-slots", [AppointmentController::class, "getAvailableSlots"])
        ->middleware('check_permission:view_available_slots')
        ->name("appointments.available-slots");

    // الإحصائيات
    /*
    Route::get("/statistics", [StatisticsController::class, "index"])
        ->middleware('check_permission:view_statistics')
        ->name("statistics.index");
    */
    Route::get('/analytics', [App\Http\Controllers\AnalyticsController::class, 'index'])->middleware('check_permission:view_statistics')->name('analytics');

    Route::get('/statistics', [StatisticsController::class, 'index'])->middleware('check_permission:view_statistics')->name('statistics.index');
    Route::get('/stats', [StatisticsController::class, 'index_stat'])->middleware('check_permission:view_statistics')->name('statistics.index_stat');
    Route::post('/statistics/data', [StatisticsController::class, 'getData'])->middleware('check_permission:view_statistics')->name('statistics.data');

    //Route::get('/statistics-advanced', [\App\Http\Controllers\StatisticsAdvancedController::class, 'index'])->name('statistics.advanced');

    // جميع صفحات إحصائيات الإدارة
Route::prefix('statistics')->group(function () {
    Route::get('/customers',    [StatisticsController::class, 'customers'])->name('statistics.customers');
    Route::get('/appointments', [StatisticsController::class, 'appointments'])->name('statistics.appointments');
    Route::get('/queue',        [StatisticsController::class, 'queue'])->name('statistics.queue');
    Route::get('/revenues',     [StatisticsController::class, 'revenues'])->name('statistics.revenues');
    Route::get('/advanced',     [\App\Http\Controllers\StatisticsAdvancedController::class, 'index'])->name('statistics.advanced');
});

    // التقويم
    Route::get('/calendar', [CalendarController::class, 'index'])
        ->middleware('check_permission:view_calendar')
        ->name('calendar.index');

    Route::get('/calendar/events', [CalendarController::class, 'events'])
        ->middleware('check_permission:view_calendar')
        ->name('calendar.events');

    Route::post('/calendar/update/{appointment}', [CalendarController::class, 'update'])
        ->middleware('check_permission:edit_calendar')
        ->name('calendar.update');

    // إدارة المستخدمين
    Route::middleware(['role:administrateur'])->group(function () {

        Route::get('users', [UserController::class, 'index'])
        ->name('users.index')
        ->middleware(['check_permission:view_users']);

    Route::get('users/create', [UserController::class, 'create'])
        ->name('users.create')
        ->middleware(['check_permission:add_user']);

    Route::post('users', [UserController::class, 'store'])
        ->name('users.store')
        ->middleware(['check_permission:add_user']);

    Route::get('users/{user}/edit', [UserController::class, 'edit'])
        ->name('users.edit')
        ->middleware(['check_permission:edit_user']);

    Route::put('users/{user}', [UserController::class, 'update'])
        ->name('users.update')
        ->middleware(['check_permission:edit_user']);

    Route::delete('users/{user}', [UserController::class, 'destroy'])
        ->name('users.destroy')
        ->middleware(['check_permission:delete_user']);

        Route::get('/roless', [UserRoleController::class, 'index'])
            ->middleware('check_permission:view_roles')
            ->name('users.roles');

        Route::post('/{user}/roles/update', [UserRoleController::class, 'update'])
            ->middleware('check_permission:edit_roles')
            ->name('users.roles.update');




        // الأدوار
        Route::prefix('roles')->group(function () {
            Route::get('/', [RoleController::class, 'index'])
                ->middleware('check_permission:view_roles')
                ->name('roles.index');

            Route::post('/', [RoleController::class, 'store'])
                ->middleware('check_permission:add_role')
                ->name('roles.store');

            Route::put('/{role}', [RoleController::class, 'update'])
                ->middleware('check_permission:edit_role')
                ->name('roles.update');

            Route::delete('/{role}', [RoleController::class, 'destroy'])
                ->middleware('check_permission:delete_role')
                ->name('roles.destroy');

            Route::get('/{role}/permissions', [RoleController::class, 'editPermissions'])
                ->middleware('check_permission:edit_role_permissions')
                ->name('roles.permissions.edit');

            Route::post('/{role}/permissions', [RoleController::class, 'updatePermissions'])
                ->middleware('check_permission:edit_role_permissions')
                ->name('roles.permissions.update');
        });

        // الصلاحيات
        Route::prefix('permissions')->group(function () {
            Route::get('/', [PermissionController::class, 'index'])
                ->middleware('check_permission:view_permissions')
                ->name('permissions.index');

            Route::post('/', [PermissionController::class, 'store'])
                ->middleware('check_permission:add_permission')
                ->name('permissions.store');
        });

        // صلاحيات الباقات
        Route::get('/plan-permissions', [PlanPermissionController::class, 'listPlans'])
            ->middleware('check_permission:view_plan_permissions')
            ->name('plan-permissions.index');

        Route::get('/plan-permissions/{plan}/edit', [PlanPermissionController::class, 'edit'])
            ->middleware('check_permission:edit_plan_permissions')
            ->name('plan-permissions.edit');

        Route::post('/plan-permissions/{plan}', [PlanPermissionController::class, 'update'])
            ->middleware('check_permission:edit_plan_permissions')
            ->name('plan-permissions.update');

        // إنشاء دور مع مستخدم
        Route::get('/roles/create-with-user', [RolePermissionController::class, 'create'])
            ->middleware('check_permission:add_role')
            ->name('roles.create_with_user');

        Route::post('/roles/store-with-user', [RolePermissionController::class, 'store'])
            ->middleware('check_permission:add_role')
            ->name('roles.store_with_user');
    });

    // عرض قائمة الانتظار العامة
    Route::get('/queue/{uuid}', [QueueController::class, 'showPublicQueue'])
        ->middleware('check_permission:view_queue')
        ->name('queue.queue');
        
    // Join Request Management Routes
    Route::prefix('join-requests')->name('join-requests.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Staff\JoinRequestController::class, 'index'])
            ->middleware('check_permission:view_queue')
            ->name('index');
            
        Route::get('/{joinRequest}', [\App\Http\Controllers\Staff\JoinRequestController::class, 'show'])
            ->middleware('check_permission:view_queue')
            ->name('show');
            
        Route::post('/{joinRequest}/approve', [\App\Http\Controllers\Staff\JoinRequestController::class, 'approve'])
            ->middleware('check_permission:manage_queue')
            ->name('approve');
            
        Route::post('/{joinRequest}/reject', [\App\Http\Controllers\Staff\JoinRequestController::class, 'reject'])
            ->middleware('check_permission:manage_queue')
            ->name('reject');
            
    });
    
    // API route for pending count (outside the prefix to avoid double nesting)
    Route::get('/join-requests/api/pending-count', [\App\Http\Controllers\Staff\JoinRequestController::class, 'getPendingCount'])
        ->middleware(['auth', 'check_permission:view_queue'])
        ->name('join-requests.api.pending-count');
    
    // عرض جميع الشاشات المرتبطة بالمستأجر
    Route::get('/displays', [App\Http\Controllers\DisplayController::class, 'list'])
        ->middleware('check_permission:view_display_settings')
        ->name('displays.index');
        
    // إنشاء شاشة جديدة
    Route::post('/displays', [App\Http\Controllers\DisplayController::class, 'create'])
        ->middleware('check_permission:add_display_settings')
        ->name('displays.store');
        
    // تعديل شاشة
    Route::put('/displays/{id}', [App\Http\Controllers\DisplayController::class, 'update'])
        ->middleware('check_permission:edit_display_settings')
        ->name('displays.update');
        
    // حذف شاشة
    Route::delete('/displays/{id}', [App\Http\Controllers\DisplayController::class, 'destroy'])
        ->middleware('check_permission:delete_display_settings')
        ->name('displays.destroy');
    
    // Test route without permission check
    Route::get('/displays-test', [App\Http\Controllers\DisplayController::class, 'list'])
        ->name('displays.test');
        
    // Create demo display for testing (without auth for testing)
    Route::get('/create-demo-display-test', function() {
        try {
            $display = \App\Models\DisplayDevice::create([
                'name' => 'Demo Online Display - ' . now()->format('H:i:s'),
                'tenant_id' => 1, // Use tenant ID 1 for demo
                'is_authorized' => 'yes',
                'paired_at' => now(),
                'last_seen_at' => now(), // Set as online
                'last_ip' => request()->ip()
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Demo display created successfully!',
                'display' => $display,
                'display_url' => route('display.index', $display->device_token)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    });
    
    // Create demo display for testing (with auth)
    Route::get('/create-demo-display', function() {
        try {
            $display = \App\Models\DisplayDevice::create([
                'name' => 'Demo Display - ' . now()->format('H:i:s'),
                'tenant_id' => auth()->user()->tenant_id,
                'is_authorized' => 'yes',
                'paired_at' => now(),
                'last_seen_at' => now(),
                'last_ip' => request()->ip()
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Demo display created successfully!',
                'display' => $display
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    });
    
    // Test POST display creation
    Route::post('/test-display-create', function(\Illuminate\Http\Request $request) {
        try {
            $display = \App\Models\DisplayDevice::create([
                'name' => $request->input('name', 'Test Display'),
                'tenant_id' => auth()->user()->tenant_id,
                'is_authorized' => 'non',
                'last_ip' => $request->ip()
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Test display created successfully!',
                'display' => $display
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    });
/*
    //إعدادات التطبيق
    Route::middleware(['auth', 'check_permission:manage-settings'])->group(function () {
        Route::get('/settings/appointment', [SettingsController::class, 'appointmentSettings'])->middleware('check_permission:appointment_settings')->name('settings.appointment');
        Route::post('/settings/appointment', [SettingsController::class, 'saveAppointmentSettings'])->middleware('check_permission:appointment_settings');

        Route::get('/settings/displays', [SettingsController::class, 'displays'])->middleware('check_permission:view_display_settings')->name('settings.displays');
        Route::post('/settings/displays/create', [SettingsController::class, 'createDisplay'])->middleware('check_permission:add_display_settings');
        });

        */

        Route::middleware(['auth', 'check_permission:manage-settings'])->group(function () {
            Route::get('/settings', [SettingsController::class, 'index'])->name('settings.index');

            Route::get('/settings/appointment', [SettingsController::class, 'appointmentSettings'])
                ->middleware('check_permission:appointment_settings')
                ->name('settings.appointment');

            Route::post('/settings/appointment', [SettingsController::class, 'saveAppointmentSettings'])
                ->middleware('check_permission:appointment_settings');
/*
            Route::get('/settings/displays', [SettingsController::class, 'displays'])
                ->middleware('check_permission:view_display_settings')
                ->name('settings.displays');
*/
            Route::get('/settings/displays', [DisplayController::class, 'list'])
                ->middleware('check_permission:view_display_settings')
                ->name('settings.displays');

            Route::post('/settings/displays/create', [SettingsController::class, 'createDisplay'])
                ->middleware('check_permission:add_display_settings');

            Route::prefix('settings/visit-types')->group(function () {
                    Route::get('/', [VisitTypeController::class, 'index'])->name('visit_types.index');
                    Route::get('/create', [VisitTypeController::class, 'create'])->name('visit_types.create');
                    Route::post('/', [VisitTypeController::class, 'store'])->name('visit_types.store');
                    Route::get('/{visitType}/edit', [VisitTypeController::class, 'edit'])->name('visit_types.edit');
                    Route::put('/{visitType}', [VisitTypeController::class, 'update'])->name('visit_types.update');
                    Route::delete('/{visitType}', [VisitTypeController::class, 'destroy'])->name('visit_types.destroy');
            });


            });



});




// Short Link Routes - Public access for redirects
Route::get('/s/{shortCode}', [App\Http\Controllers\ShortLinkController::class, 'redirect'])
    ->name('short.redirect');

// Short Link Management Routes - Authenticated
Route::middleware('auth')->group(function () {
    Route::post('/short-links', [App\Http\Controllers\ShortLinkController::class, 'create'])
        ->name('short.create');
    Route::get('/short-links/{shortCode}/analytics', [App\Http\Controllers\ShortLinkController::class, 'analytics'])
        ->name('short.analytics');
    Route::post('/short-links/{id}/regenerate', [App\Http\Controllers\ShortLinkController::class, 'regenerate'])
        ->name('short.regenerate');
    Route::delete('/short-links/{id}', [App\Http\Controllers\ShortLinkController::class, 'delete'])
        ->name('short.delete');
});

// Create demo display for testing (without auth for testing) - Outside middleware
// Create multiple demo displays for testing statistics
// Check existing enum values in database
Route::get('/check-display-enum-values', function() {
    try {
        $displays = \DB::select('SELECT DISTINCT is_authorized FROM display_devices WHERE is_authorized IS NOT NULL');
        $columnInfo = \DB::select('SHOW COLUMNS FROM display_devices LIKE "is_authorized"');
        
        return response()->json([
            'success' => true,
            'existing_values' => $displays,
            'column_info' => $columnInfo,
            'sample_display' => \App\Models\DisplayDevice::first(),
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
        ]);
    }
});

Route::get('/create-demo-displays-batch', function() {
    try {
        $displays = [];
        
        // Create an online display
        $onlineDisplay = \App\Models\DisplayDevice::create([
            'name' => 'Reception Display (Online)',
            'tenant_id' => 1,
            'paired_at' => now(),
            'last_seen_at' => now(), // Online - seen now
            'last_ip' => '192.168.1.100'
        ]);
        // Use correct French enum values from database
        \DB::table('display_devices')->where('id', $onlineDisplay->id)->update(['is_authorized' => 'oui']);
        $onlineDisplay->refresh();
        $displays[] = $onlineDisplay;
        
        // Create an offline display
        $offlineDisplay = \App\Models\DisplayDevice::create([
            'name' => 'Waiting Area Display (Offline)',
            'tenant_id' => 1,
            'paired_at' => now()->subHours(2),
            'last_seen_at' => now()->subHours(1), // Offline - seen 1 hour ago
            'last_ip' => '192.168.1.101'
        ]);
        \DB::table('display_devices')->where('id', $offlineDisplay->id)->update(['is_authorized' => 'oui']);
        $offlineDisplay->refresh();
        $displays[] = $offlineDisplay;
        
        // Create a pending display (use 'non' since 'pending' doesn't exist)
        $pendingDisplay = \App\Models\DisplayDevice::create([
            'name' => 'New Display (Pending)',
            'tenant_id' => 1,
            'last_ip' => '192.168.1.102'
        ]);
        // Keep as 'non' for pending state
        $displays[] = $pendingDisplay;
        
        // Create a disconnected display
        $disconnectedDisplay = \App\Models\DisplayDevice::create([
            'name' => 'Unused Display (Disconnected)',
            'tenant_id' => 1,
            'last_ip' => '192.168.1.103'
        ]);
        // Already defaults to 'non'
        $disconnectedDisplay->refresh();
        $displays[] = $disconnectedDisplay;
        
        return response()->json([
            'success' => true,
            'message' => 'Created ' . count($displays) . ' demo displays',
            'displays' => array_map(function($d) {
                return [
                    'id' => $d->id,
                    'name' => $d->name,
                    'is_authorized' => $d->is_authorized,
                    'last_seen_at' => $d->last_seen_at,
                    'display_url' => route('display.index', $d->device_token)
                ];
            }, $displays)
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
        ]);
    }
});

Route::get('/create-demo-display-public', function() {
    try {
        $display = \App\Models\DisplayDevice::create([
            'name' => 'Demo Display - ' . now()->format('H:i:s'),
            'tenant_id' => 1,
            'paired_at' => now(),
            'last_seen_at' => now(),
            'last_ip' => request()->ip()
        ]);
        
        // Leave as 'non' for pairing demo
        // This allows testing the pairing flow
        
        return response()->json([
            'success' => true,
            'message' => 'Demo display created successfully!',
            'display' => [
                'id' => $display->id,
                'name' => $display->name,
                'device_token' => $display->device_token,
                'is_authorized' => $display->is_authorized ?? 'default',
                'last_seen_at' => $display->last_seen_at,
            ],
            'display_url' => route('display.index', $display->device_token),
            'note' => 'Display created - authorization status: ' . ($display->is_authorized ?? 'default')
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'line' => $e->getLine(),
            'file' => basename($e->getFile())
        ]);
    }
});

// Create short link for specific display (Test Route)
Route::get('/create-short-link/{device_token}', function($deviceToken) {
    try {
        $display = \App\Models\DisplayDevice::where('device_token', $deviceToken)->first();
        if (!$display) {
            return response()->json(['success' => false, 'error' => 'Display not found']);
        }
        
        $pairingUrl = route('display.pairing', $display->device_token);
        $shortLink = \App\Models\ShortLink::create([
            'original_url' => $pairingUrl,
            'short_code' => \App\Models\ShortLink::generateUniqueCode(),
            'tenant_id' => $display->tenant_id ?? 1,
            'usage_type' => 'display_pairing',
            'expires_at' => now()->addMonths(6),
            'metadata' => json_encode(['display_id' => $display->id]),
            'created_by' => 'demo'
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'Short link created for display pairing!',
            'display' => [
                'id' => $display->id,
                'name' => $display->name,
                'device_token' => $display->device_token
            ],
            'short_link' => [
                'short_code' => $shortLink->short_code,
                'short_url' => $shortLink->short_url,
                'original_url' => $shortLink->original_url
            ],
            'test_steps' => [
                '1. Type this on TV: ' . $shortLink->short_url,
                '2. TV will redirect to pairing page with QR code',
                '3. Scan QR code on mobile device',
                '4. Enter credentials on mobile',
                '5. TV will auto-redirect to display view'
            ]
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
});

// Test route for pairing controller
Route::get('/test-pairing-controller/{device_token}', function($deviceToken) {
    try {
        $display = \App\Models\DisplayDevice::where('device_token', $deviceToken)->first();
        
        if (!$display) {
            return response()->json(['error' => 'Display not found']);
        }
        
        return response()->json([
            'success' => true,
            'display' => $display->toArray(),
            'pairing_status' => $display->pairing_status ?? 'waiting',
            'controller_exists' => class_exists('App\\Http\\Controllers\\DisplayPairingController'),
            'method_exists' => method_exists('App\\Http\\Controllers\\DisplayPairingController', 'showPairingPage'),
            'route_exists' => \Illuminate\Support\Facades\Route::has('display.pairing')
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'error' => $e->getMessage(),
            'line' => $e->getLine(),
            'file' => basename($e->getFile())
        ]);
    }
});

// Simple test pairing route
Route::get('/display/{device_token}/pairing-test', function($deviceToken) {
    $display = \App\Models\DisplayDevice::where('device_token', $deviceToken)->first();
    
    if (!$display) {
        abort(404, 'Display not found');
    }
    
    // Generate pairing session ID if not exists
    if (!$display->pairing_session_id) {
        $display->update([
            'pairing_session_id' => \Illuminate\Support\Str::random(32),
            'pairing_started_at' => now(),
            'pairing_status' => 'waiting'
        ]);
    }
    
    // Generate QR code for mobile authentication
    $mobileAuthUrl = 'http://localhost:8000/mobile/auth/' . $display->device_token . '/' . $display->pairing_session_id;
    
    // Use Google Charts API as fallback for QR code generation
    $qrCodeUrl = 'https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=' . urlencode($mobileAuthUrl);
    $qrCode = '<img src="' . $qrCodeUrl . '" alt="QR Code" style="max-width: 250px; height: auto;">';
    
    return view('display.pairing-simple', [
        'display' => $display,
        'qrCode' => $qrCode,
        'mobileAuthUrl' => $mobileAuthUrl
    ]);
});

// Simulate successful pairing (test route)
Route::get('/simulate-pairing/{device_token}', function($deviceToken) {
    try {
        $display = \App\Models\DisplayDevice::where('device_token', $deviceToken)->first();
        if (!$display) {
            return response()->json(['success' => false, 'error' => 'Display not found']);
        }
        
        $display->update([
            'is_authorized' => 'oui',
            'tenant_id' => 1,
            'paired_at' => now(),
            'pairing_status' => 'completed'
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'Display paired successfully!',
            'display_url' => route('display.index', $display->device_token)
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
});

// Test WebSocket event broadcasting
Route::get('/test-websocket/{tenantId?}', function($tenantId = 1) {
    try {
        // Broadcast QueueUpdated event
        broadcast(new \App\Events\QueueUpdated($tenantId));
        
        // Also broadcast DisplayUpdated event
        broadcast(new \App\Events\NewDisplay($tenantId));
        
        return response()->json([
            'success' => true,
            'message' => 'WebSocket events broadcasted successfully!',
            'events' => [
                'QueueUpdated' => 'waiting-room.' . $tenantId,
                'DisplayUpdated' => 'display.' . $tenantId
            ],
            'tenant_id' => $tenantId
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'line' => $e->getLine()
        ]);
    }
});

// Display Routes (No authentication required) - MOVED OUTSIDE AUTH MIDDLEWARE
Route::get('/display/{device_token}/pairing', [App\Http\Controllers\DisplayPairingController::class, 'showPairingPage'])
    ->name('display.pairing');

Route::get('/display/{device_token}/pairing/status', [App\Http\Controllers\DisplayPairingController::class, 'checkPairingStatus'])
    ->name('display.pairing.status');

Route::post('/display/{device_token}/pairing/reset', [App\Http\Controllers\DisplayPairingController::class, 'resetPairingSession'])
    ->name('display.pairing.reset');

// Mobile Authentication Routes (No authentication required) - MOVED OUTSIDE AUTH MIDDLEWARE
Route::get('/mobile/auth/{device_token}/{session_id}', [App\Http\Controllers\DisplayPairingController::class, 'showMobileAuth'])
    ->name('display.mobile.auth');

Route::post('/mobile/auth/{device_token}/{session_id}', [App\Http\Controllers\DisplayPairingController::class, 'processMobileAuth'])
    ->name('display.mobile.auth.process');

// Display Routes (No authentication required) - MOVED OUTSIDE AUTH MIDDLEWARE
Route::get('/display/{device_token}', [DisplayController::class, 'index'])
    ->name('display.index');

Route::get('/display/{device_token}/data', [DisplayController::class, 'data'])
    ->name('display.data');

Route::post('/display/{device_token}/heartbeat', [DisplayController::class, 'heartbeat'])
    ->name('display.heartbeat');

// رابط داخل QR → يفتحه صاحب المحل على الهاتف، يلزمه تسجيل دخول
Route::middleware('auth')->group(function () {

    Route::get('/pair/confirm/{device_token}', [DisplayPairController::class, 'pairForm'])
        ->name('display.pair.form');

    Route::post('/pair/confirm/{device_token}', [DisplayPairController::class, 'pairStore'])
        ->name('display.pair.store');

    // إلغاء الربط من لوحة التحكم
    Route::delete('/pair/{device_token}', [DisplayPairController::class, 'unpair'])
        ->name('display.pair.unpair');
});

Route::get('/register', [TenantController::class, 'create'])->name('tenants.create');
Route::post('/tenants', [TenantController::class, 'store'])->name('tenants.store');


Route::post('/queue/{uuid}/join', [QueueController::class, 'joinQueue'])->name('queue.queue.join');



Route::get('/check/{uuid}', [QueueController::class, 'showForm'])->name('queue.check.form');
Route::post('/check/{uuid}', [QueueController::class, 'check'])->name('queue.check');




Route::get('/land', function () {
    return view('/land');
});

Route::get('/websocket-test', function () {
    return view('websocket-test');
})->name('websocket.test');

Route::get('/test-broadcast/{tenantId?}', function ($tenantId = 1) {
    try {
        // Test broadcasting with your existing events
        broadcast(new \App\Events\QueueUpdated($tenantId));
        
        return response()->json([
            'status' => 'success', 
            'message' => "QueueUpdated event broadcasted for tenant {$tenantId}",
            'tenantId' => $tenantId
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'status' => 'error',
            'message' => $e->getMessage()
        ], 500);
    }
})->name('test.broadcast');

// QR Login Routes (Outside auth middleware - accessible to guests)
Route::post('/qr-login/generate', [App\Http\Controllers\QrLoginController::class, 'generateQrCode'])->name('qr.login.generate');
Route::get('/qr-login/{token}', [App\Http\Controllers\QrLoginController::class, 'showScanPage'])->name('qr.login.scan');
Route::post('/qr-login/{token}/authenticate', [App\Http\Controllers\QrLoginController::class, 'authenticateQrScan'])->name('qr.login.authenticate');
Route::get('/qr-login/{token}/status', [App\Http\Controllers\QrLoginController::class, 'checkQrStatus'])->name('qr.login.status');
Route::post('/qr-login/{token}/complete', [App\Http\Controllers\QrLoginController::class, 'completeQrLogin'])->name('qr.login.complete');

// QR Test page
Route::get('/test-qr', function () {
    return view('test-qr');
})->name('qr.test');

// Debug QR generation
Route::get('/debug-qr', function () {
    try {
        $token = \App\Models\QrLoginToken::generateToken();
        $expiresAt = now()->addMinutes(5);
        
        $qrToken = \App\Models\QrLoginToken::create([
            'token' => $token,
            'expires_at' => $expiresAt,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent()
        ]);
        
        $qrLoginUrl = route('qr.login.scan', ['token' => $token]);
        $qrCode = \SimpleSoftwareIO\QrCode\Facades\QrCode::size(200)->generate($qrLoginUrl);
        
        // Convert to string if it's not already
        if (is_object($qrCode)) {
            $qrCode = (string) $qrCode;
        }
        
        return response()->json([
            'success' => true,
            'token' => $token,
            'qr_code' => $qrCode,
            'url' => $qrLoginUrl,
            'expires_at' => $expiresAt->toISOString(),
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
    }
});

// Test route to create customer and trigger WebSocket update
Route::get('/test-add-customer/{tenantId?}', function($tenantId = 1) {
    try {
        // Create a test customer
        $customer = \App\Models\Customer::create([
            'name' => 'Test Customer WebSocket ' . now()->format('H:i:s'),
            'email' => 'test' . now()->timestamp . '@example.com',
            'phone' => '+1234567890',
            'tenant_id' => $tenantId
        ]);
        
        // Add to queue as walk-in
        $queueEntry = \App\Models\WaitingQueue::create([
            'customer_id' => $customer->id,
            'tenant_id' => $tenantId,
            'type' => 'walk-in',
            'status' => 'waiting',
            'arrival_time' => now(),
            'created_at' => now()
        ]);
        
        // Trigger WebSocket update
        broadcast(new \App\Events\QueueUpdated($tenantId));
        
        return response()->json([
            'success' => true,
            'message' => 'Test customer created and WebSocket event broadcasted!',
            'customer' => $customer,
            'queue_entry' => $queueEntry,
            'events_sent' => [
                'QueueUpdated' => 'waiting-room.' . $tenantId
            ]
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'line' => $e->getLine()
        ]);
    }
});

// ==============================================
// PATIENT INTERFACE ROUTES
// ==============================================

// Patient Public Routes (no authentication required)
Route::prefix('patient')->name('patient.')->group(function () {
    
    // Authentication routes
    Route::get('/register', [App\Http\Controllers\PatientAuthController::class, 'showRegistrationForm'])->name('register');
    Route::post('/register', [App\Http\Controllers\PatientAuthController::class, 'register']);
    Route::get('/login', [App\Http\Controllers\PatientAuthController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [App\Http\Controllers\PatientAuthController::class, 'login']);
    Route::post('/logout', [App\Http\Controllers\PatientAuthController::class, 'logout'])->name('logout');
    
    // Phone verification
    Route::post('/send-verification-code', [App\Http\Controllers\PatientAuthController::class, 'sendVerificationCode'])->name('send.verification.code');
    
    // Quick join (for walk-ins without full registration)
    Route::get('/join/{uuid}', [App\Http\Controllers\PatientAuthController::class, 'showQuickJoinForm'])->name('quick.join.form');
    Route::post('/quick-join', [App\Http\Controllers\PatientAuthController::class, 'quickJoin'])->name('quick.join');
    
    // Public queue status (for quick join users or direct links)
    Route::get('/queue/{uuid}/status', [App\Http\Controllers\PatientController::class, 'getQueueStatus'])->name('queue.status');
    
});

// Patient Protected Routes (authentication required)
Route::prefix('patient')->name('patient.')->middleware('auth:patient')->group(function () {
    
    // Dashboard
    Route::get('/dashboard', [App\Http\Controllers\PatientController::class, 'dashboard'])->name('dashboard');
    
    // Search and browse
    Route::get('/search', [App\Http\Controllers\PatientController::class, 'search'])->name('search');
    
    // Tenant/Clinic details and queue management
    Route::get('/clinic/{uuid}', [App\Http\Controllers\PatientController::class, 'showTenant'])->name('clinic.show');
    Route::post('/clinic/{uuid}/join', [App\Http\Controllers\PatientController::class, 'joinQueue'])->name('clinic.join');
    Route::delete('/clinic/{uuid}/leave', [App\Http\Controllers\PatientController::class, 'leaveQueue'])->name('clinic.leave');
    Route::get('/clinic/{uuid}/queue-status', [App\Http\Controllers\PatientController::class, 'getQueueStatus'])->name('clinic.queue.status');
    
    // Favorites
    Route::post('/clinic/{uuid}/favorite', [App\Http\Controllers\PatientController::class, 'toggleFavorite'])->name('clinic.favorite');
    Route::get('/favorites', [App\Http\Controllers\PatientController::class, 'favorites'])->name('favorites');
    
    // Profile
    Route::get('/profile', [App\Http\Controllers\PatientController::class, 'profile'])->name('profile');
    Route::put('/profile', [App\Http\Controllers\PatientController::class, 'updateProfile'])->name('profile.update');
    
    // Visit history
    Route::get('/history', [App\Http\Controllers\PatientController::class, 'visitHistory'])->name('history');
    
});

// Patient API Routes (for AJAX requests)
Route::prefix('api/patient')->name('api.patient.')->middleware('auth:patient')->group(function () {
    
    Route::get('/queue-status/{uuid}', [App\Http\Controllers\PatientController::class, 'getQueueStatus']);
    Route::post('/favorite/{uuid}', [App\Http\Controllers\PatientController::class, 'toggleFavorite']);
    
});

// ==============================================
// PATIENT DEMO ROUTES (for testing)
// ==============================================

// Patient interface demo
Route::get('/patient-demo', function () {
    return view('patient.demo');
})->name('patient.demo');

// Patient interface styling test
Route::get('/patient-test', function () {
    return view('patient.test');
})->name('patient.test');

// Create demo tenant and redirect to quick join
Route::get('/create-demo-patient-flow', function() {
    try {
        // Find or create a demo tenant
        $tenant = \App\Models\Tenant::where('name', 'LIKE', 'Demo Clinic%')->first();
        
        if (!$tenant) {
            $tenant = \App\Models\Tenant::create([
                'name' => 'Demo Clinic - Patient Interface',
                'email' => 'demo@clinic.com',
                'phone' => '+966501234567',
                'address' => '123 Demo Street, Demo City',
                'timezone' => 'Asia/Riyadh'
            ]);
            
            // Create some visit types
            \App\Models\VisitType::create([
                'name' => 'استشارة عامة',
                'estimated_duration' => 15,
                'tenant_id' => $tenant->id
            ]);
            
            \App\Models\VisitType::create([
                'name' => 'فحص دوري',
                'estimated_duration' => 30,
                'tenant_id' => $tenant->id
            ]);
            
            // Add some demo queue entries
            for ($i = 1; $i <= 3; $i++) {
                $customer = \App\Models\Customer::create([
                    'name' => "Demo Patient {$i}",
                    'phone' => "+96650123456{$i}",
                    'tenant_id' => $tenant->id
                ]);
                
                \App\Models\WaitingQueue::create([
                    'customer_id' => $customer->id,
                    'tenant_id' => $tenant->id,
                    'type' => 'walk-in',
                    'status' => 'waiting',
                    'arrival_time' => now()->subMinutes($i * 10),
                    'visit_type' => $i == 1 ? 'استشارة عامة' : 'فحص دوري'
                ]);
            }
        }
        
        return redirect()->route('patient.quick.join.form', $tenant->uuid);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'line' => $e->getLine()
        ]);
    }
});


