<?php

use App\Http\Controllers\Tenant\BookingController;
use App\Http\Controllers\Tenant\CashMovementController;
use App\Http\Controllers\Tenant\ClinicalHistoryController;
use App\Http\Controllers\Tenant\CustomerController;
use App\Http\Controllers\Tenant\DashboardController;
use App\Http\Controllers\Tenant\EmployeeController;
use App\Http\Controllers\Tenant\ModuleManagementController;
use App\Http\Controllers\Tenant\PaymentController;
use App\Http\Controllers\Tenant\PromotionController;
use App\Http\Controllers\Tenant\ReportController;
use App\Http\Controllers\Tenant\ScheduleController;
use App\Http\Controllers\Tenant\ServiceController;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth', 'role:company_admin', 'company.active'])
    ->prefix('empresa')
    ->name('tenant.')
    ->group(function () {

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

        // Pago / suscripción
        Route::view('/billing/expired', 'tenant.billing.expired')->name('billing.expired');

        // Recursos del módulo (gateados por module: middleware donde aplica)
        Route::middleware(['plan.active', 'module:services'])->group(function () {
            Route::resource('services', ServiceController::class)->except(['show']);
        });

        Route::middleware(['plan.active', 'module:employees'])->group(function () {
            Route::resource('employees', EmployeeController::class)->except(['show']);
        });

        Route::middleware(['plan.active', 'module:schedules'])->group(function () {
            Route::resource('schedules', ScheduleController::class)->only(['index', 'store', 'update', 'destroy']);
        });

        Route::middleware(['plan.active', 'module:customers'])->group(function () {
            Route::resource('customers', CustomerController::class)->except(['show']);
            Route::middleware(['module:clinical_history'])->group(function () {
                Route::get('/clinical-histories', [ClinicalHistoryController::class, 'index'])->name('clinical-histories.index');
                Route::get('/customers/{customer}/clinical-history', [ClinicalHistoryController::class, 'show'])->name('clinical-histories.show');
                Route::put('/customers/{customer}/clinical-history', [ClinicalHistoryController::class, 'update'])->name('clinical-histories.update');
                Route::post('/customers/{customer}/clinical-history/notes', [ClinicalHistoryController::class, 'storeNote'])->name('clinical-histories.notes.store');
                Route::post('/customers/{customer}/clinical-history/consents', [ClinicalHistoryController::class, 'storeConsent'])
                    ->middleware('module:consent_forms')
                    ->name('clinical-histories.consents.store');
                Route::post('/customers/{customer}/clinical-history/files', [ClinicalHistoryController::class, 'storeFile'])
                    ->middleware('module:client_files')
                    ->name('clinical-histories.files.store');
                Route::get('/customers/{customer}/clinical-history/files/{file}', [ClinicalHistoryController::class, 'downloadFile'])
                    ->middleware('module:client_files')
                    ->name('clinical-histories.files.download');
                Route::delete('/customers/{customer}/clinical-history/files/{file}', [ClinicalHistoryController::class, 'deleteFile'])
                    ->middleware('module:client_files')
                    ->name('clinical-histories.files.destroy');
            });
        });

        Route::middleware(['plan.active', 'module:bookings'])->group(function () {
            Route::get('/agenda',             [BookingController::class, 'agenda'])->name('bookings.agenda');
            Route::get('/agenda/events.json', [BookingController::class, 'eventsJson'])->name('bookings.events');
            Route::patch('/bookings/{booking}/move', [BookingController::class, 'move'])->name('bookings.move');
            Route::patch('/bookings/{booking}/confirm', [BookingController::class, 'confirm'])->name('bookings.confirm');
            Route::patch('/bookings/{booking}/complete', [BookingController::class, 'complete'])->name('bookings.complete');
            Route::patch('/bookings/{booking}/no-show', [BookingController::class, 'noShow'])->name('bookings.no-show');
            Route::patch('/bookings/{booking}/cancel', [BookingController::class, 'cancel'])->name('bookings.cancel');
            Route::resource('bookings', BookingController::class);
        });

        // Marcar notificación individual como leída y redirigir
        Route::get('/notifications/{notification}/read', function (\App\Models\AppNotification $notification) {
            abort_unless($notification->user_id === auth()->id(), 403);
            $notification->markAsRead();
            return redirect($notification->action_url ?? route('tenant.dashboard'));
        })->name('notifications.read');

        Route::middleware(['plan.active'])->group(function () {
            Route::view('/workspace', 'tenant.workspace.index')->name('workspace.index');
            Route::get('/business-settings', [ModuleManagementController::class, 'branding'])->name('business-settings.index');
            Route::put('/business-settings', [ModuleManagementController::class, 'updateBranding'])->name('business-settings.update');

            Route::get('/reports', [ReportController::class, 'index'])->middleware('module:reports')->name('reports.index');

            Route::middleware(['module:promotions,coupons'])->group(function () {
                Route::get('/promotions', [PromotionController::class, 'index'])->name('promotions.index');
            });
            Route::middleware(['module:promotions'])->group(function () {
                Route::post('/promotions', [PromotionController::class, 'storePromotion'])->name('promotions.store');
                Route::patch('/promotions/{promotion}/toggle', [PromotionController::class, 'togglePromotion'])->name('promotions.toggle');
            });
            Route::middleware(['module:coupons'])->group(function () {
                Route::post('/coupons', [PromotionController::class, 'storeCoupon'])->name('coupons.store');
                Route::patch('/coupons/{coupon}/toggle', [PromotionController::class, 'toggleCoupon'])->name('coupons.toggle');
            });

            Route::middleware(['module:payments'])->group(function () {
                Route::get('/payments', [PaymentController::class, 'index'])->name('payments.index');
                Route::post('/payments', [PaymentController::class, 'createPending'])->name('payments.create-pending');
                Route::post('/payments/{payment}/checkout', [PaymentController::class, 'checkout'])->name('payments.checkout');
            });

            Route::middleware(['module:cash_register'])->group(function () {
                Route::get('/cash', [CashMovementController::class, 'index'])->name('cash.index');
                Route::post('/cash', [CashMovementController::class, 'store'])->name('cash.store');
                Route::patch('/cash/{movement}/void', [CashMovementController::class, 'void'])->name('cash.void');
            });

            Route::middleware(['module:gallery'])->group(function () {
                Route::get('/gallery', [ModuleManagementController::class, 'gallery'])->name('gallery.index');
                Route::post('/gallery', [ModuleManagementController::class, 'storeGalleryItem'])->name('gallery.store');
                Route::delete('/gallery/{item}', [ModuleManagementController::class, 'deleteGalleryItem'])->name('gallery.destroy');
            });

            Route::middleware(['module:multi_branch'])->group(function () {
                Route::get('/branches', [ModuleManagementController::class, 'branches'])->name('branches.index');
                Route::post('/branches', [ModuleManagementController::class, 'storeBranch'])->name('branches.store');
                Route::put('/branches/{branch}', [ModuleManagementController::class, 'updateBranch'])->name('branches.update');
                Route::delete('/branches/{branch}', [ModuleManagementController::class, 'deleteBranch'])->name('branches.destroy');
            });

            Route::middleware(['module:reminders,notifications,whatsapp'])->group(function () {
                Route::get('/communications', [ModuleManagementController::class, 'communications'])->name('communications.index');
                Route::put('/communications', [ModuleManagementController::class, 'updateCommunications'])->name('communications.update');
            });

            Route::middleware(['module:branding'])->group(function () {
                Route::get('/branding', [ModuleManagementController::class, 'branding'])->name('branding.index');
                Route::put('/branding', [ModuleManagementController::class, 'updateBranding'])->name('branding.update');
            });

            Route::middleware(['module:invoicing'])->group(function () {
                Route::get('/invoicing', [ModuleManagementController::class, 'billing'])->name('invoicing.index');
                Route::put('/invoicing', [ModuleManagementController::class, 'updateBilling'])->name('invoicing.update');
            });

            Route::middleware(['module:pwa'])->group(function () {
                Route::get('/pwa', [ModuleManagementController::class, 'pwa'])->name('pwa.index');
                Route::put('/pwa', [ModuleManagementController::class, 'updatePwa'])->name('pwa.update');
            });

            Route::middleware(['module:advanced_agenda'])->group(function () {
                Route::get('/advanced-agenda', [ModuleManagementController::class, 'advancedAgenda'])->name('advanced-agenda.index');
                Route::put('/advanced-agenda', [ModuleManagementController::class, 'updateAdvancedAgenda'])->name('advanced-agenda.update');
            });

            // ── Configuración del módulo clínico (sin guard de módulo) ──────────
            Route::get('/clinical-settings', [ModuleManagementController::class, 'clinicalSettings'])->name('clinical-settings.index');
            Route::put('/clinical-settings', [ModuleManagementController::class, 'updateClinicalSettings'])->name('clinical-settings.update');

            // ── Módulo Clínico Completo ─────────────────────────────────────────
            Route::middleware(['module:clinical_history'])->group(function () {

                // Pacientes
                Route::get('/patients', [\App\Http\Controllers\Tenant\PatientController::class, 'index'])->name('patients.index');
                Route::get('/patients/create', [\App\Http\Controllers\Tenant\PatientController::class, 'create'])->name('patients.create');
                Route::post('/patients', [\App\Http\Controllers\Tenant\PatientController::class, 'store'])->name('patients.store');
                Route::get('/patients/{patient}', [\App\Http\Controllers\Tenant\PatientController::class, 'show'])->name('patients.show');
                Route::get('/patients/{patient}/edit', [\App\Http\Controllers\Tenant\PatientController::class, 'edit'])->name('patients.edit');
                Route::put('/patients/{patient}', [\App\Http\Controllers\Tenant\PatientController::class, 'update'])->name('patients.update');
                Route::delete('/patients/{patient}', [\App\Http\Controllers\Tenant\PatientController::class, 'destroy'])->name('patients.destroy');

                // Evoluciones clínicas
                Route::get('/patients/{patient}/evolutions/create', [\App\Http\Controllers\Tenant\ClinicalEvolutionController::class, 'create'])->name('evolutions.create');
                Route::post('/patients/{patient}/evolutions', [\App\Http\Controllers\Tenant\ClinicalEvolutionController::class, 'store'])->name('evolutions.store');
                Route::get('/patients/{patient}/evolutions/{evolution}', [\App\Http\Controllers\Tenant\ClinicalEvolutionController::class, 'show'])->name('evolutions.show');
                Route::post('/patients/{patient}/evolutions/{evolution}/sign', [\App\Http\Controllers\Tenant\ClinicalEvolutionController::class, 'sign'])->name('evolutions.sign');

                // Prescripciones / recetas
                Route::get('/patients/{patient}/prescriptions', [\App\Http\Controllers\Tenant\PrescriptionController::class, 'index'])->name('prescriptions.index');
                Route::get('/patients/{patient}/prescriptions/create', [\App\Http\Controllers\Tenant\PrescriptionController::class, 'create'])->name('prescriptions.create');
                Route::post('/patients/{patient}/prescriptions', [\App\Http\Controllers\Tenant\PrescriptionController::class, 'store'])->name('prescriptions.store');
                Route::get('/patients/{patient}/prescriptions/{prescription}', [\App\Http\Controllers\Tenant\PrescriptionController::class, 'show'])->name('prescriptions.show');
                Route::post('/patients/{patient}/prescriptions/{prescription}/sign', [\App\Http\Controllers\Tenant\PrescriptionController::class, 'sign'])->name('prescriptions.sign');

                // Órdenes clínicas
                Route::get('/patients/{patient}/orders', [\App\Http\Controllers\Tenant\ClinicalOrderController::class, 'index'])->name('orders.index');
                Route::get('/patients/{patient}/orders/create', [\App\Http\Controllers\Tenant\ClinicalOrderController::class, 'create'])->name('orders.create');
                Route::post('/patients/{patient}/orders', [\App\Http\Controllers\Tenant\ClinicalOrderController::class, 'store'])->name('orders.store');
                Route::get('/patients/{patient}/orders/{order}', [\App\Http\Controllers\Tenant\ClinicalOrderController::class, 'show'])->name('orders.show');
                Route::post('/patients/{patient}/orders/{order}/sign', [\App\Http\Controllers\Tenant\ClinicalOrderController::class, 'sign'])->name('orders.sign');

                // PDF clínico
                Route::get('/patients/{patient}/pdf/history', [\App\Http\Controllers\Tenant\ClinicalPdfController::class, 'fullHistory'])->name('pdf.history');
                Route::get('/patients/{patient}/pdf/evolutions/{evolution}', [\App\Http\Controllers\Tenant\ClinicalPdfController::class, 'evolution'])->name('pdf.evolution');
                Route::get('/patients/{patient}/pdf/prescriptions/{prescription}', [\App\Http\Controllers\Tenant\ClinicalPdfController::class, 'prescription'])->name('pdf.prescription');
                Route::get('/patients/{patient}/pdf/orders/{order}', [\App\Http\Controllers\Tenant\ClinicalPdfController::class, 'order'])->name('pdf.order');

                // Plantillas de consentimientos
                Route::resource('/consent-templates', \App\Http\Controllers\Tenant\ConsentTemplateController::class)
                    ->names('consent-templates')
                    ->middleware('module:consent_forms');
            });
        });
    });
