<?php

use App\Http\Controllers\DashboardController;
use App\Http\Controllers\ClientDashboardController;
use App\Http\Controllers\ClientManagementController;
use App\Http\Controllers\ReportController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

// Redirect root to dashboard or login
Route::get('/', function () {
    if (auth()->guard('admin')->check()) {
        return redirect()->route('dashboard');
    }
    return redirect()->route('admin.login');
});

// Admin authentication routes
Route::get('/admin/login', [DashboardController::class, 'showLogin'])->name('admin.login');
Route::post('/admin/login', [DashboardController::class, 'login'])->name('admin.login.submit');
Route::post('/admin/logout', [DashboardController::class, 'logout'])->name('admin.logout');

// Protected admin dashboard routes
Route::middleware(['admin.auth'])->prefix('admin')->group(function () {
    // Dashboard - accessible by all authenticated admins
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

    // ============ USER MANAGEMENT ============
    // User creation (MUST be before {id} routes to avoid conflict)
    Route::middleware(['admin.permission:users.create'])->group(function () {
        Route::get('/users/create', [DashboardController::class, 'createUser'])->name('dashboard.users.create');
        Route::post('/users', [DashboardController::class, 'storeUser'])->name('dashboard.users.store');
    });

    // User listing and viewing
    Route::middleware(['admin.permission:users.view'])->group(function () {
        Route::get('/users', [DashboardController::class, 'users'])->name('dashboard.users');
        Route::get('/users/{id}', [DashboardController::class, 'userDetails'])->where('id', '[0-9]+')->name('dashboard.user-details');
    });

    // User editing
    Route::middleware(['admin.permission:users.edit'])->group(function () {
        Route::get('/users/{id}/edit', [DashboardController::class, 'editUser'])->where('id', '[0-9]+')->name('dashboard.users.edit');
        Route::put('/users/{id}', [DashboardController::class, 'updateUser'])->where('id', '[0-9]+')->name('dashboard.users.update');
    });

    // User deletion - Permitted admins only
    Route::middleware(['admin.permission:users.delete'])->group(function () {
        Route::delete('/users/{id}', [DashboardController::class, 'deleteUser'])->where('id', '[0-9]+')->name('dashboard.users.delete');
    });

    // User Actions
    Route::middleware(['admin.permission:users.toggle_status'])->group(function () {
        Route::post('/users/{id}/toggle-status', [DashboardController::class, 'toggleUserStatus'])->where('id', '[0-9]+')->name('dashboard.users.toggle-status');
    });

    Route::middleware(['admin.permission:users.toggle_sms'])->group(function () {
        Route::post('/users/{id}/toggle-sms-service', [DashboardController::class, 'toggleSmsService'])->where('id', '[0-9]+')->name('dashboard.users.toggle-sms');
    });

    Route::middleware(['admin.permission:users.toggle_promotions'])->group(function () {
        Route::post('/users/{id}/toggle-promotions', [DashboardController::class, 'togglePromotions'])->where('id', '[0-9]+')->name('dashboard.users.toggle-promotions');
    });

    Route::middleware(['admin.permission:users.toggle_sms'])->group(function () {
        Route::post('/users/{id}/toggle-whatsapp', [DashboardController::class, 'toggleWhatsAppService'])->where('id', '[0-9]+')->name('dashboard.users.toggle-whatsapp');
    });

    Route::middleware(['admin.permission:users.force_logout'])->group(function () {
        Route::post('/users/{id}/force-logout', [DashboardController::class, 'forceLogoutUser'])->where('id', '[0-9]+')->name('dashboard.users.force-logout');
    });

    Route::middleware(['admin.permission:users.reset_password'])->group(function () {
        Route::post('/users/{id}/reset-password', [DashboardController::class, 'resetUserPassword'])->where('id', '[0-9]+')->name('dashboard.users.reset-password');
    });

    // ============ TEMPLATES MANAGEMENT ============
    // Template creation (MUST be before {id} routes)
    Route::middleware(['admin.permission:templates.create'])->group(function () {
        Route::get('/templates/create', [DashboardController::class, 'createTemplate'])->name('dashboard.templates.create');
        Route::post('/templates', [DashboardController::class, 'storeTemplate'])->name('dashboard.templates.store');
    });

    Route::middleware(['admin.permission:templates.view'])->group(function () {
        Route::get('/templates', [DashboardController::class, 'templates'])->name('dashboard.templates');
    });

    Route::middleware(['admin.permission:templates.edit'])->group(function () {
        Route::get('/templates/{id}/edit', [DashboardController::class, 'editTemplate'])->where('id', '[0-9]+')->name('dashboard.templates.edit');
        Route::put('/templates/{id}', [DashboardController::class, 'updateTemplate'])->where('id', '[0-9]+')->name('dashboard.templates.update');
        Route::post('/templates/{id}/toggle-status', [DashboardController::class, 'toggleTemplateStatus'])->where('id', '[0-9]+')->name('dashboard.templates.toggle-status');
    });

    Route::middleware(['admin.permission:templates.delete'])->group(function () {
        Route::delete('/templates/{id}', [DashboardController::class, 'deleteTemplate'])->where('id', '[0-9]+')->name('dashboard.templates.delete');
    });

    // ============ LOGS ============
    // Log Export - requires logs.export permission
    Route::middleware(['admin.permission:logs.export'])->group(function () {
        Route::get('/call-logs/export', [DashboardController::class, 'exportCallLogs'])->name('dashboard.call-logs.export');
        Route::get('/sms-logs/export', [DashboardController::class, 'exportSmsLogs'])->name('dashboard.sms-logs.export');
        Route::get('/promotion-logs/export', [DashboardController::class, 'exportPromotionLogs'])->name('dashboard.promotion-logs.export');
    });

    // Call Logs - with masking for admin role
    Route::middleware(['admin.permission:logs.call.view'])->group(function () {
        Route::get('/call-logs', [DashboardController::class, 'callLogs'])->name('dashboard.call-logs');
    });

    // SMS Logs - with masking for admin role
    Route::middleware(['admin.permission:logs.sms.view'])->group(function () {
        Route::get('/sms-logs', [DashboardController::class, 'smsLogs'])->name('dashboard.sms-logs');
    });

    // Promotion Logs - with masking for admin role
    Route::middleware(['admin.permission:logs.promotion.view'])->group(function () {
        Route::get('/promotion-logs', [DashboardController::class, 'promotionLogs'])->name('dashboard.promotion-logs');
    });

    // Session Logs - with masking for admin role
    Route::middleware(['admin.permission:logs.session.view'])->group(function () {
        Route::get('/session-logs', [DashboardController::class, 'sessionLogs'])->name('dashboard.session-logs');
    });

    // ============ ANALYTICS ============
    Route::middleware(['admin.permission:analytics.view'])->group(function () {
        Route::get('/analytics', [DashboardController::class, 'analytics'])->name('dashboard.analytics');
        Route::get('/chart-data', [DashboardController::class, 'chartData'])->name('dashboard.chart-data');
    });

    // ============ SETTINGS - Permission Based ============
    Route::middleware(['admin.permission:settings.view'])->group(function () {
        Route::get('/settings', [DashboardController::class, 'settings'])->name('dashboard.settings');
    });
    Route::middleware(['admin.permission:settings.edit'])->group(function () {
        Route::put('/settings', [DashboardController::class, 'updateSettings'])->name('dashboard.settings.update');
    });

    // ============ ADMIN MANAGEMENT - Permission Based ============
    Route::prefix('admins')->group(function () {
        Route::middleware(['admin.permission:admins.view'])->group(function () {
            Route::get('/', [DashboardController::class, 'admins'])->name('dashboard.admins');
        });
        Route::middleware(['admin.permission:admins.create'])->group(function () {
            Route::get('/create', [DashboardController::class, 'createAdmin'])->name('dashboard.admins.create');
            Route::post('/', [DashboardController::class, 'storeAdmin'])->name('dashboard.admins.store');
        });
        Route::middleware(['admin.permission:admins.edit'])->group(function () {
            Route::get('/{id}/edit', [DashboardController::class, 'editAdmin'])->where('id', '[0-9]+')->name('dashboard.admins.edit');
            Route::put('/{id}', [DashboardController::class, 'updateAdmin'])->where('id', '[0-9]+')->name('dashboard.admins.update');
            Route::post('/{id}/toggle-status', [DashboardController::class, 'toggleAdminStatus'])->where('id', '[0-9]+')->name('dashboard.admins.toggle-status');
            Route::get('/{id}/permissions', [DashboardController::class, 'adminPermissions'])->where('id', '[0-9]+')->name('dashboard.admins.permissions');
            Route::put('/{id}/permissions', [DashboardController::class, 'updateAdminPermissions'])->where('id', '[0-9]+')->name('dashboard.admins.permissions.update');
            Route::get('/{id}/limits', [DashboardController::class, 'adminLimits'])->where('id', '[0-9]+')->name('dashboard.admins.limits');
            Route::put('/{id}/limits', [DashboardController::class, 'updateAdminLimits'])->where('id', '[0-9]+')->name('dashboard.admins.limits.update');
        });
        Route::middleware(['admin.permission:admins.delete'])->group(function () {
            Route::delete('/{id}', [DashboardController::class, 'deleteAdmin'])->where('id', '[0-9]+')->name('dashboard.admins.delete');
        });
    });

    // ============ CLIENT MANAGEMENT - Permission Based ============
    Route::prefix('clients')->group(function () {
        Route::middleware(['admin.permission:clients.view'])->group(function () {
            Route::get('/', [ClientManagementController::class, 'clients'])->name('dashboard.clients');
            Route::get('/{id}', [ClientManagementController::class, 'showClient'])->where('id', '[0-9]+')->name('dashboard.clients.show');
            Route::get('/{id}/templates', [ClientManagementController::class, 'getClientTemplates'])->where('id', '[0-9]+')->name('dashboard.clients.templates');
        });
        Route::middleware(['admin.permission:clients.create'])->group(function () {
            Route::get('/create', [ClientManagementController::class, 'createClient'])->name('dashboard.clients.create');
            Route::post('/', [ClientManagementController::class, 'storeClient'])->name('dashboard.clients.store');
        });
        Route::middleware(['admin.permission:clients.edit'])->group(function () {
            Route::get('/{id}/edit', [ClientManagementController::class, 'editClient'])->where('id', '[0-9]+')->name('dashboard.clients.edit');
            Route::put('/{id}', [ClientManagementController::class, 'updateClient'])->where('id', '[0-9]+')->name('dashboard.clients.update');
        });
        Route::middleware(['admin.permission:clients.toggle_status'])->group(function () {
            Route::post('/{id}/toggle-status', [ClientManagementController::class, 'toggleClientStatus'])->where('id', '[0-9]+')->name('dashboard.clients.toggle-status');
        });
        Route::middleware(['admin.permission:clients.toggle_service'])->group(function () {
            Route::post('/{id}/toggle-service', [ClientManagementController::class, 'toggleClientService'])->where('id', '[0-9]+')->name('dashboard.clients.toggle-service');
        });
        Route::middleware(['admin.permission:clients.subscription'])->group(function () {
            Route::post('/{id}/extend-subscription', [ClientManagementController::class, 'extendSubscription'])->where('id', '[0-9]+')->name('dashboard.clients.extend-subscription');
        });
        // Client Admin Permission Management (from admin panel)
        Route::middleware(['admin.permission:clients.edit'])->group(function () {
            Route::get('/{clientId}/admins/{id}/permissions', [ClientManagementController::class, 'clientAdminPermissions'])->where(['clientId' => '[0-9]+', 'id' => '[0-9]+'])->name('dashboard.clients.admin-permissions');
            Route::put('/{clientId}/admins/{id}/permissions', [ClientManagementController::class, 'updateClientAdminPermissions'])->where(['clientId' => '[0-9]+', 'id' => '[0-9]+'])->name('dashboard.clients.admin-permissions.update');
        });
    });

    // Pending User Approvals - Permission Based
    Route::prefix('approvals')->group(function () {
        Route::middleware(['admin.permission:approvals.view'])->group(function () {
            Route::get('/', [ClientManagementController::class, 'pendingApprovals'])->name('dashboard.approvals');
        });
        Route::middleware(['admin.permission:approvals.manage'])->group(function () {
            Route::post('/approve/{id}', [ClientManagementController::class, 'approveUser'])->where('id', '[0-9]+')->name('dashboard.approvals.approve');
            Route::post('/reject/{id}', [ClientManagementController::class, 'rejectUser'])->where('id', '[0-9]+')->name('dashboard.approvals.reject');
            Route::post('/bulk-approve', [ClientManagementController::class, 'bulkApproveUsers'])->name('dashboard.approvals.bulk-approve');
        });
    });

    // Template Assignment - Permission Based
    Route::prefix('template-assignment')->group(function () {
        Route::middleware(['admin.permission:template_assignment.view'])->group(function () {
            Route::get('/', [ClientManagementController::class, 'templateAssignment'])->name('dashboard.template-assignment');
        });
        Route::middleware(['admin.permission:template_assignment.manage'])->group(function () {
            Route::post('/{clientId}', [ClientManagementController::class, 'assignTemplates'])->where('clientId', '[0-9]+')->name('dashboard.template-assignment.assign');
            Route::delete('/{clientId}/{templateId}', [ClientManagementController::class, 'removeTemplate'])->where(['clientId' => '[0-9]+', 'templateId' => '[0-9]+'])->name('dashboard.template-assignment.remove');
        });
    });

    // ============ AUDIT LOGS - Permission Based ============
    Route::middleware(['admin.permission:audit_logs.view'])->group(function () {
        Route::get('/audit-logs', [DashboardController::class, 'auditLogs'])->name('dashboard.audit-logs');
    });

    // ============ REPORTS ============
    // Reports index - requires base reports.view permission
    Route::middleware(['admin.permission:reports.view'])->prefix('reports')->group(function () {
        Route::get('/', [ReportController::class, 'index'])->name('dashboard.reports');

        // User Activity Report
        Route::middleware(['admin.permission:reports.user_activity'])->group(function () {
            Route::get('/user-activity', [ReportController::class, 'userActivity'])->name('dashboard.reports.user-activity');
        });

        // SMS Summary Report
        Route::middleware(['admin.permission:reports.sms_summary'])->group(function () {
            Route::get('/sms-summary', [ReportController::class, 'smsSummary'])->name('dashboard.reports.sms-summary');
        });

        // Call Summary Report
        Route::middleware(['admin.permission:reports.call_summary'])->group(function () {
            Route::get('/call-summary', [ReportController::class, 'callSummary'])->name('dashboard.reports.call-summary');
        });

        // Promotion Summary Report - SuperAdmin only
        Route::middleware(['admin.permission:reports.promotion_summary'])->group(function () {
            Route::get('/promotion-summary', [ReportController::class, 'promotionSummary'])->name('dashboard.reports.promotion-summary');
        });

        // Device Usage Report - SuperAdmin only
        Route::middleware(['admin.permission:reports.device_usage'])->group(function () {
            Route::get('/device-usage', [ReportController::class, 'deviceUsage'])->name('dashboard.reports.device-usage');
        });

        // Daily Summary Report - SuperAdmin only
        Route::middleware(['admin.permission:reports.daily_summary'])->group(function () {
            Route::get('/daily-summary', [ReportController::class, 'dailySummary'])->name('dashboard.reports.daily-summary');
        });

        // Export Routes - requires reports.export permission
        Route::middleware(['admin.permission:reports.export'])->group(function () {
            Route::get('/user-activity/export', [ReportController::class, 'exportUserActivity'])->name('dashboard.reports.user-activity.export');
            Route::get('/sms-summary/export', [ReportController::class, 'exportSmsSummary'])->name('dashboard.reports.sms-summary.export');
            Route::get('/call-summary/export', [ReportController::class, 'exportCallSummary'])->name('dashboard.reports.call-summary.export');
            Route::get('/promotion-summary/export', [ReportController::class, 'exportPromotionSummary'])->name('dashboard.reports.promotion-summary.export');
            Route::get('/device-usage/export', [ReportController::class, 'exportDeviceUsage'])->name('dashboard.reports.device-usage.export');
            Route::get('/daily-summary/export', [ReportController::class, 'exportDailySummary'])->name('dashboard.reports.daily-summary.export');
        });
    });
});

// ============================================================================
// CLIENT ADMIN ROUTES - Separate login panel for client admins
// ============================================================================

// Client Admin Authentication
Route::get('/client/login', [ClientDashboardController::class, 'showLogin'])->name('client.login');
Route::post('/client/login', [ClientDashboardController::class, 'login'])->name('client.login.submit');
Route::post('/client/logout', [ClientDashboardController::class, 'logout'])->name('client.logout');

// Protected Client Admin Dashboard Routes
Route::middleware(['client_admin.auth'])->prefix('client')->group(function () {
    // Dashboard
    Route::get('/dashboard', [ClientDashboardController::class, 'index'])->name('client.dashboard');

    // User Management
    Route::middleware(['client_admin.permission:client.users.view'])->group(function () {
        Route::get('/users', [ClientDashboardController::class, 'users'])->name('client.users');
        Route::get('/users/{id}', [ClientDashboardController::class, 'userDetails'])->where('id', '[0-9]+')->name('client.users.details');
    });
    Route::middleware(['client_admin.permission:client.users.create'])->group(function () {
        Route::get('/users/create', [ClientDashboardController::class, 'createUser'])->name('client.users.create');
        Route::post('/users', [ClientDashboardController::class, 'storeUser'])->name('client.users.store');
    });
    Route::middleware(['client_admin.permission:client.users.edit'])->group(function () {
        Route::get('/users/{id}/edit', [ClientDashboardController::class, 'editUser'])->where('id', '[0-9]+')->name('client.users.edit');
        Route::put('/users/{id}', [ClientDashboardController::class, 'updateUser'])->where('id', '[0-9]+')->name('client.users.update');
    });
    Route::middleware(['client_admin.permission:client.users.toggle_status'])->group(function () {
        Route::post('/users/{id}/toggle-status', [ClientDashboardController::class, 'toggleUserStatus'])->where('id', '[0-9]+')->name('client.users.toggle-status');
    });
    Route::middleware(['client_admin.permission:client.users.toggle_sms'])->group(function () {
        Route::post('/users/{id}/toggle-sms', [ClientDashboardController::class, 'toggleSmsService'])->where('id', '[0-9]+')->name('client.users.toggle-sms');
    });
    Route::middleware(['client_admin.permission:client.users.toggle_whatsapp'])->group(function () {
        Route::post('/users/{id}/toggle-whatsapp', [ClientDashboardController::class, 'toggleWhatsAppService'])->where('id', '[0-9]+')->name('client.users.toggle-whatsapp');
    });
    Route::middleware(['client_admin.permission:client.users.force_logout'])->group(function () {
        Route::post('/users/{id}/force-logout', [ClientDashboardController::class, 'forceLogoutUser'])->where('id', '[0-9]+')->name('client.users.force-logout');
    });
    Route::middleware(['client_admin.permission:client.users.reset_password'])->group(function () {
        Route::post('/users/{id}/reset-password', [ClientDashboardController::class, 'resetUserPassword'])->where('id', '[0-9]+')->name('client.users.reset-password');
    });

    // Template Management
    Route::middleware(['client_admin.permission:client.templates.view'])->group(function () {
        Route::get('/templates', [ClientDashboardController::class, 'templates'])->name('client.templates');
    });
    Route::middleware(['client_admin.permission:client.templates.edit'])->group(function () {
        Route::get('/templates/{id}/edit', [ClientDashboardController::class, 'editTemplate'])->where('id', '[0-9]+')->name('client.templates.edit');
        Route::put('/templates/{id}', [ClientDashboardController::class, 'updateTemplate'])->where('id', '[0-9]+')->name('client.templates.update');
    });
    Route::middleware(['client_admin.permission:client.templates.toggle_status'])->group(function () {
        Route::post('/templates/{id}/toggle-status', [ClientDashboardController::class, 'toggleTemplateStatus'])->where('id', '[0-9]+')->name('client.templates.toggle-status');
    });

    // Reports
    Route::middleware(['client_admin.permission:client.reports.sms_logs'])->group(function () {
        Route::get('/sms-logs', [ClientDashboardController::class, 'smsLogs'])->name('client.sms-logs');
        Route::get('/sms-logs/export', [ClientDashboardController::class, 'exportSmsLogs'])->name('client.sms-logs.export');
    });
    Route::middleware(['client_admin.permission:client.reports.call_logs'])->group(function () {
        Route::get('/call-logs', [ClientDashboardController::class, 'callLogs'])->name('client.call-logs');
        Route::get('/call-logs/export', [ClientDashboardController::class, 'exportCallLogs'])->name('client.call-logs.export');
    });

    // Profile
    Route::middleware(['client_admin.permission:client.profile.view'])->group(function () {
        Route::get('/profile', [ClientDashboardController::class, 'profile'])->name('client.profile');
    });
    Route::middleware(['client_admin.permission:client.profile.edit'])->group(function () {
        Route::put('/profile', [ClientDashboardController::class, 'updateProfile'])->name('client.profile.update');
        Route::put('/profile/password', [ClientDashboardController::class, 'changePassword'])->name('client.profile.password');
    });

    // Client Admin Management
    Route::middleware(['client_admin.permission:client.admins.view'])->group(function () {
        Route::get('/admins', [ClientDashboardController::class, 'clientAdmins'])->name('client.admins');
    });
    Route::middleware(['client_admin.permission:client.admins.create'])->group(function () {
        Route::get('/admins/create', [ClientDashboardController::class, 'createClientAdmin'])->name('client.admins.create');
        Route::post('/admins', [ClientDashboardController::class, 'storeClientAdmin'])->name('client.admins.store');
    });
    Route::middleware(['client_admin.permission:client.admins.toggle_status'])->group(function () {
        Route::post('/admins/{id}/toggle-status', [ClientDashboardController::class, 'toggleClientAdminStatus'])->where('id', '[0-9]+')->name('client.admins.toggle-status');
    });
    Route::middleware(['client_admin.permission:client.admins.edit'])->group(function () {
        Route::get('/admins/{id}/permissions', [ClientDashboardController::class, 'clientAdminPermissions'])->where('id', '[0-9]+')->name('client.admins.permissions');
        Route::put('/admins/{id}/permissions', [ClientDashboardController::class, 'updateClientAdminPermissions'])->where('id', '[0-9]+')->name('client.admins.permissions.update');
    });
});
