<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Homecontroller;
use App\Http\Controllers\TestController;
use App\Http\Controllers\ContactImportController;
use App\Http\Controllers\SmsController;
use App\Http\Controllers\TicketsController;
use App\Http\Controllers\StkTransactionController;
use App\Http\Controllers\ComplimentaryTicketController;
use App\Http\Controllers\MessageTemplateController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\ConfirmablePasswordController;
use App\Http\Controllers\Auth\EmailVerificationNotificationController;
use App\Http\Controllers\Auth\EmailVerificationPromptController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\Auth\PasswordController;
use App\Http\Controllers\Auth\PasswordResetLinkController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\Auth\VerifyEmailController;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\UserController;
use App\Http\Controllers\CsvProcessorController;

Route::get('/', [HomeController::class, 'home'])->name('home');

Route::get('/buy/ticket/{slug}', [HomeController::class, 'index'])->name('ticket');
Route::get('/home/contact', [Homecontroller::class, 'Contact'])->name('contact');

Route::post('/buy-ticket', [Homecontroller::class, 'Ticket'])->name('buy-ticket');
Route::get('/gate-ticket', [Homecontroller::class, 'gateMobile'])->name('gate.ticket.mobile');
Route::get('/events', [Homecontroller::class, 'CreateEvent'])->name('create-event');
Route::post('/events', [Homecontroller::class, 'Store'])->name('events.store');

// Ticket download / confirmation page
Route::get('/get/ticket/{ticket}/{amount}', [HomeController::class, 'showTicketDownload'])->name('ticket.downloads');
Route::get('/get/ticket/{ticket}', [HomeController::class, 'showTicketDownload'])->name('ticket.download');
Route::get('/get/complimentary-ticket/{ticket}', [HomeController::class, 'showComplimentaryTicketDownload'])->name('complimentary.ticket.download');
Route::get('/v2/get/ticket/{ticket}', [HomeController::class, 'showTicketDownloadv2'])->name('ticket.download.v2');

Route::middleware('auth')->group(function () {
    Route::get('/ticket/verify/{reference}', [TicketsController::class, 'verifyShow'])->name('ticket.verify.show');
    Route::post('/ticket/verify', [TicketsController::class, 'verifyProcess'])->name('ticket.verify.process');
});


// M-Pesa Callbacks and Testing Routes
Route::get('/test-stk-push', [TestController::class, 'testStkPush']);
Route::get('/register-mpesa-callback', [TestController::class, 'registerCallbackUrl']);

// M-Pesa Callback Routes
Route::post('/api/v1/c2b-stk-callback', [TestController::class, 'handleStkCallback']);

// Complimentary Tickets Routes
Route::prefix('complimentary')->group(function () {
    // Redemption
    Route::get('/redeem', [ComplimentaryTicketController::class, 'redeemForm'])
        ->name('complimentary.redeem.form');
    Route::post('/redeem', [ComplimentaryTicketController::class, 'redeem'])
        ->name('complimentary.redeem');

    // Ticket download
    Route::get('/ticket/{ticket}/download', [ComplimentaryTicketController::class, 'downloadTicket'])
        ->name('complimentary.ticket.downloads');
});

Route::get('/dashboard', [AuthenticatedSessionController::class, 'dashboard'])
    ->middleware(['auth', 'verified'])
    ->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

// CSV Processor - Only for Super Admin
// Route::middleware(['permission:access-complimentary'])->group(function () {
Route::get('/admin/csv-processor', [CsvProcessorController::class, 'index'])->name('csv.index');
Route::post('/admin/csv-processor', [CsvProcessorController::class, 'process'])->name('csv.process');
// });

Route::middleware('guest')->group(function () {
    // Route::get('register', [RegisteredUserController::class, 'create'])
    //     ->name('register');

    Route::post('register', [RegisteredUserController::class, 'store']);

    Route::post('/login/otp/generate', [AuthenticatedSessionController::class, 'otp'])->name('login.otp.generate');
    Route::post('/login/otp', [AuthenticatedSessionController::class, 'loginWithOtp'])->name('login.otp');

    Route::get('login', [AuthenticatedSessionController::class, 'create'])->name('login');
    Route::post('login', [AuthenticatedSessionController::class, 'store']);

    Route::get('forgot-password', [PasswordResetLinkController::class, 'create'])
        ->name('password.request');

    Route::post('forgot-password', [PasswordResetLinkController::class, 'store'])
        ->name('password.email');

    Route::get('reset-password/{token}', [NewPasswordController::class, 'create'])
        ->name('password.reset');

    Route::post('reset-password', [NewPasswordController::class, 'store'])
        ->name('password.store');
});

Route::middleware('auth')->group(function () {
    Route::get('verify-email', EmailVerificationPromptController::class)
        ->name('verification.notice');

    Route::get('verify-email/{id}/{hash}', VerifyEmailController::class)
        ->middleware(['signed', 'throttle:6,1'])
        ->name('verification.verify');

    Route::post('email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
        ->middleware('throttle:6,1')
        ->name('verification.send');

    Route::get('confirm-password', [ConfirmablePasswordController::class, 'show'])
        ->name('password.confirm');

    Route::post('confirm-password', [ConfirmablePasswordController::class, 'store']);

    Route::put('password', [PasswordController::class, 'update'])->name('password.update');

    Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])
        ->name('logout');

    Route::get('/dashboard', [AuthenticatedSessionController::class, 'dashboard'])
        ->name('dashboard');

    // Messages & Contacts - Only for Super Admin and Customer Support
    Route::middleware(['permission:access-messages'])->group(function () {
        Route::get('/admin/sms', [SmsController::class, 'index'])->name('sms.index');
        Route::get('/admin/sms/all-contact-ids', [SmsController::class, 'getAllContactIds'])->name('sms.all-contact-ids');
        Route::post('/admin/sms/compose', [SmsController::class, 'compose'])->name('sms.compose');
        Route::post('/admin/sms/send', [SmsController::class, 'send'])->name('sms.send');
        Route::get('/admin/sms/logs', [SmsController::class, 'logs'])->name('sms.logs');
        Route::get('/admin/sms/export', [SmsController::class, 'export'])->name('sms.export');
    });

    Route::middleware(['permission:manage-contacts'])->group(function () {
        Route::get('/admin/contacts/import', [ContactImportController::class, 'showImportForm'])->name('contacts.import.form');
        Route::post('/admin/contacts/import', [ContactImportController::class, 'importCsv'])->name('contacts.import');
        Route::post('/admin/contacts/store-single', [ContactImportController::class, 'storeSingle'])->name('contacts.store-single');
        Route::get('/admin/contacts/sample', [ContactImportController::class, 'downloadSample'])->name('contacts.download-sample');
        Route::delete('/admin/contacts/clear', [ContactImportController::class, 'clearAll'])->name('contacts.clear-all');
    });

    // Tickets - Accessible to all roles but with different views
    Route::middleware(['permission:view-tickets'])->group(function () {
        Route::get('/admin/tickets', [TicketsController::class, 'index'])->name('tickets.index');
        Route::get('/admin/dashboard-v2', [TicketsController::class, 'indexV2'])->name('dashboard.v2');
        Route::get('/admin/tickets/export', [TicketsController::class, 'export'])->name('tickets.export');
        Route::post('/admin/tickets/{id}/resend-sms', [TicketsController::class, 'resendSms'])->name('tickets.resend-sms');
        Route::get('/api/transactions', [TicketsController::class, 'transactionsApi'])->name('tickets.api.transactions');
        Route::get('/api/ticket-stats', [TicketsController::class, 'statsApi'])->name('tickets.api.stats');
        Route::get('/api/revenue-series', [TicketsController::class, 'revenueSeriesApi'])->name('tickets.api.revenue');
    });

    // Analytics - Only for Super Admin and Management
    Route::middleware(['permission:view-metrics'])->group(function () {
        Route::get('/admin/tickets/analytics', [TicketsController::class, 'analytics'])->name('tickets.analytics');
    });

    // Complimentary - Only for Super Admin
    Route::middleware(['permission:access-complimentary'])->group(function () {
        Route::prefix('complimentary')->group(function () {
            Route::get('/codes/create', [ComplimentaryTicketController::class, 'createCodes'])->name('complimentary.codes.create');
            Route::post('/codes', [ComplimentaryTicketController::class, 'storeCodes'])->name('complimentary.codes.store');
            Route::get('/codes', [ComplimentaryTicketController::class, 'createCodes'])->name('complimentary.codes.index');
            Route::post('/codes/{id}/resend', [ComplimentaryTicketController::class, 'resendNotification'])->name('complimentary.resend');
        });

        Route::prefix('admin')->group(function () {
            Route::get('/send-codes', [ComplimentaryTicketController::class, 'showSendCodeForm'])->name('admin.send-codes.form');
            Route::post('/send-codes/single', [ComplimentaryTicketController::class, 'sendSingleCode'])->name('admin.send-codes.single');
            Route::post('/send-codes/bulk', [ComplimentaryTicketController::class, 'sendBulkCodes'])->name('admin.send-codes.bulk');
        });
    });

    // Message Templates - Only for Super Admin and Customer Support
    Route::middleware(['permission:access-messages'])->group(function () {
        Route::resource('/admin/message-templates', MessageTemplateController::class)->names([
            'index' => 'admin.message-templates.index',
            'create' => 'admin.message-templates.create',
            'store' => 'admin.message-templates.store',
            'show' => 'admin.message-templates.show',
            'edit' => 'admin.message-templates.edit',
            'update' => 'admin.message-templates.update',
            'destroy' => 'admin.message-templates.destroy'
        ]);
        Route::get('/admin/api/message-templates', [MessageTemplateController::class, 'getTemplates'])->name('admin.message-templates.api');
    });

    // Other routes that should be accessible to all authenticated users
    Route::get('/admin/stk-transactions', [StkTransactionController::class, 'index'])->name('stk-transactions.index');
    Route::get('/admin/cleanup-failed-tickets', [Homecontroller::class, 'cleanupFailedTickets'])->name('cleanup.failed.tickets');
    Route::get('/manage/complimentary/tickets', [ComplimentaryTicketController::class, 'ticketsIndex'])->name('manage.complimentary.tickets.index');
    Route::get('/complimentary/tickets', [ComplimentaryTicketController::class, 'index'])->name('complimentary.tickets.index');
    Route::get('/complimentary', [ComplimentaryTicketController::class, 'index'])->name('complimentary.index');

});

Route::get('/complimentary/ticket-by-code/{code}', [ComplimentaryTicketController::class, 'downloadByCode'])
    ->name('complimentary.ticket.by_code');

Route::get('/test-email', function () {
    try {
        Mail::raw('Test email content', function ($message) {
            $message->to('abrahammwatheka@gmail.com')
                ->subject('Pacesetter Mail Test');
        });
        return "Email sent successfully!";
    } catch (\Exception $e) {
        return "Error: " . $e->getMessage();
    }
});

Route::get('/complimentary/ticket/preview/{ticketId}', [ComplimentaryTicketController::class, 'showTicketPreview'])->name('complimentary.ticket.preview');


Route::middleware(['auth', 'permission:view-users'])->group(function () {
    Route::get('/users', [UserController::class, 'index'])->name('users.index');
    Route::get('/users/{user}', [UserController::class, 'show'])->name('users.show');
});

Route::middleware(['auth'])->group(function () {
    // View users - accessible to super-admin, admin, management
    Route::get('/users', [UserController::class, 'index'])->name('users.index')
        ->middleware('permission:view-users');

    Route::get('/users/{user}', [UserController::class, 'show'])->name('users.show')
        ->middleware('permission:view-users');

    // Create users - accessible to super-admin and admin
    Route::get('/me/new', [UserController::class, 'create'])->name('users.new')
        ->middleware('permission:create-users');

    Route::post('/users', [UserController::class, 'store'])->name('users.store')
        ->middleware('permission:create-users');

    // Edit users - accessible to super-admin and admin
    Route::get('/users/{user}/edit', [UserController::class, 'edit'])->name('users.edit')
        ->middleware('permission:edit-users');

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

    // Delete users - accessible ONLY to super-admin
    Route::delete('/users/{user}', [UserController::class, 'destroy'])->name('users.destroy')
        ->middleware('permission:delete-users');

    Route::get('/scanner', [UserController::class, 'scanner'])->name('users.scanner');
});
