<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AppointmentController;
use App\Http\Controllers\PatientController;
use App\Http\Controllers\HistoryController;
use App\Http\Controllers\ControlHistoryController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\RepresentativeController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\AreaController;
use App\Http\Controllers\ConfigController;
use App\Http\Controllers\XrayController;
use App\Http\Controllers\PaymentsController;
use App\Http\Controllers\CurrenciesController;
use App\Http\Controllers\PaymentsMethodController;
use App\Http\Controllers\FileController;
use App\Http\Controllers\EmailController;
use App\Http\Controllers\Api\AppointmentController as AppointmentApiController;
use App\Http\Controllers\Api\ICDController;
use App\Http\Controllers\EspecialityConfigurationController;
use App\Http\Controllers\SectionTypeController;
use App\Http\Controllers\AuditController;
use App\Http\Controllers\MedicalServiceController;
use App\Http\Controllers\BudgetController;
use App\Http\Controllers\UtilitiesController;
use App\Http\Controllers\DoctorScheduleController;
use App\Http\Controllers\TermsAndConditionsController;
use App\Http\Controllers\ClinicIdentityController;
use App\Http\Controllers\PortalController;
use App\Http\Controllers\DoctorSignatureController;
use App\Http\Controllers\InventoryController;
use App\Http\Controllers\InventoryCategoryController;
use App\Http\Controllers\SupplierController;
use App\Http\Controllers\InventoryTransactionController;
use App\Http\Controllers\RecurringAppointmentController;
use App\Http\Controllers\PatientDocumentController;
use App\Http\Controllers\RoutePermissionController;
use App\Http\Controllers\PatientCustomFieldController;
use App\Http\Controllers\PatientCustomFieldValueController;
use App\Http\Controllers\AppointmentTagController;
use App\Http\Controllers\WhatsAppController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::fallback(function () {
    return redirect('/portal');
});

Route::get('/', function () {
    return redirect('/portal');
});

/*Route::get('/', function () {
    return redirect('/create-external');
});*/



Route::get('/send-welcome-email', [App\Http\Controllers\NotificationController::class, 'sendWelcomeEmail'])->name('send-welcome-email');
Route::get('/send-new-features-announcement', [App\Http\Controllers\NotificationController::class, 'sendNewFeaturesAnnouncement'])->name('send-new-features-announcement');

// Rutas para términos y condiciones
Route::get('/admin/terms/{id}', [TermsAndConditionsController::class, 'show'])->name('terms.show');
Route::post('/admin/terms/{id}/process', [TermsAndConditionsController::class, 'process'])->name('terms.process');
Route::get('/admin/terms/check', [TermsAndConditionsController::class, 'checkRequired'])->name('terms.check');


//login
Route::get('/admin/login', [LoginController::class,"login"])->name("authenticate")->middleware("guest");
Route::post('/admin/login', [LoginController::class,"login"])->name("/admin/login")->middleware("guest");

// Grupo de rutas protegidas por autenticación
Route::group(['middleware' => ['auth', 'terms.accepted']], function () {

//logout    
Route::get('/admin/logout', [LoginController::class,"logout"])->name("/admin/logout");

Route::group(['middleware' => ['role:root']], function () {
    //Configs
    Route::get('/admin/view-config', [ConfigController::class,"view"])->name("/admin/view-config");
    Route::post('/admin/create-config', [ConfigController::class,"create"])->name("/admin/create-config");
    
    // Patient Custom Fields Configuration
    Route::prefix('admin/patient-custom-fields')->name('patient-custom-fields.')->group(function () {
        Route::get('/', [PatientCustomFieldController::class, 'index'])->name('index');
        Route::post('/', [PatientCustomFieldController::class, 'store'])->name('store');
        Route::put('/{id}', [PatientCustomFieldController::class, 'update'])->name('update');
        Route::delete('/{id}', [PatientCustomFieldController::class, 'destroy'])->name('destroy');
        Route::post('/order', [PatientCustomFieldController::class, 'updateOrder'])->name('update-order');
    });

    //currencies
    Route::post('/admin/create-currency', [CurrenciesController::class,"create"])->name("/admin/create-currency");

    Route::post('/admin/update-currency', [CurrenciesController::class,"update"])->name("/admin/update-currency");
    Route::get('/admin/update-currency', [CurrenciesController::class,"update"]);
    Route::get('/admin/detail-currency', [CurrenciesController::class,"detail"])->name("/admin/detail-currency");     

});


Route::group(['middleware' => ['role:admin|root']], function () {
    // Patient Custom Fields Configuration
    Route::prefix('admin/patient-custom-fields')->name('patient-custom-fields.')->group(function () {
        Route::get('/', [PatientCustomFieldController::class, 'index'])->name('index');
        Route::post('/', [PatientCustomFieldController::class, 'store'])->name('store');
        Route::put('/{id}', [PatientCustomFieldController::class, 'update'])->name('update');
        Route::delete('/{id}', [PatientCustomFieldController::class, 'destroy'])->name('destroy');
        Route::post('/order', [PatientCustomFieldController::class, 'updateOrder'])->name('update-order');
    });
    
    // Appointment Tags Configuration
    Route::prefix('admin/appointment-tags')->name('appointment-tags.')->group(function () {
        Route::get('/', [AppointmentTagController::class, 'index'])->name('index');
        Route::post('/', [AppointmentTagController::class, 'store'])->name('store');
        Route::put('/{id}', [AppointmentTagController::class, 'update'])->name('update');
        Route::delete('/{id}', [AppointmentTagController::class, 'destroy'])->name('destroy');
        Route::post('/order', [AppointmentTagController::class, 'updateOrder'])->name('update-order');
    });
    
    //areas
    Route::post('/admin/create-areas', [AreaController::class,"create"])->name("/admin/create-areas");
    Route::get('/admin/update-areas', [AreaController::class,"update"])->name("/admin/update-areas");
    Route::get('/admin/update-areas', [AreaController::class,"update"]);

});
Route::group(['middleware' => ['role:admin|root|doctor']], function () {
    Route::get('/admin/create-areas', [AreaController::class,"create"]);
    //users
    Route::get('/admin/update-doctor', [UserController::class,"updateDoctor"]);
    Route::post('/admin/update-doctor', [UserController::class,"updateDoctor"])->name("/admin/update-doctor");

    // Doctor Digital Signature Routes
    Route::get('/admin/doctor/signature', [DoctorSignatureController::class, 'show'])->name('doctor.signature');
    Route::post('/admin/doctor/signature', [DoctorSignatureController::class, 'store'])->name('doctor.signature.store');
    Route::delete('/admin/doctor/signature', [DoctorSignatureController::class, 'destroy'])->name('doctor.signature.destroy');

    Route::get('/admin/view-users', [UserController::class,"view"])->name("/admin/view-users");
    Route::get('/admin/create-users', [UserController::class,"create"]);
    Route::post('/admin/create-users', [UserController::class,"create"])->name("/admin/create-user");
    Route::get('/admin/update-users', [UserController::class,"update"]);
    Route::post('/admin/update-users', [UserController::class,"update"])->name("/admin/update-user");
    Route::get('/admin/detail-users', [UserController::class,"detail"])->name("/admin/detail-user");

    // Rutas para cambio de contraseña de usuario
    Route::get('/admin/users/change-password', [App\Http\Controllers\UserPasswordController::class, 'showChangePasswordForm'])->name('users.change-password');
    Route::post('/admin/users/update-password', [App\Http\Controllers\UserPasswordController::class, 'changePassword'])->name('users.update-password');
    
    // Rutas para el sistema de notificaciones
    Route::get('/admin/notifications', [App\Http\Controllers\NotificationController::class, 'index'])->name('notifications.index');
    Route::post('/admin/notifications/{id}/mark-read', [App\Http\Controllers\NotificationController::class, 'markAsRead'])->name('notifications.mark-read');
    Route::post('/admin/notifications/mark-all-read', [App\Http\Controllers\NotificationController::class, 'markAllAsRead'])->name('notifications.mark-all-read');
    Route::delete('/admin/notifications/{id}', [App\Http\Controllers\NotificationController::class, 'destroy'])->name('notifications.destroy');
    Route::get('/admin/notifications/count', [App\Http\Controllers\NotificationController::class, 'getUnreadCount'])->name('notifications.count');

    //control history
    Route::get('/admin/create-control-history', [ControlHistoryController::class,"create"]);
    Route::post('/admin/create-control-history', [ControlHistoryController::class,"create"])->name("/admin/create-control-history");


    //control history
    Route::get('/admin/view-histories', [HistoryController::class,"view"])->name("/admin/view-histories");
    Route::get('/admin/create-history', [HistoryController::class,"create"]);
    Route::get('/admin/update-history', [HistoryController::class,"update"]);
    Route::post('/admin/update-history', [HistoryController::class,"update"])->name("/admin/update-history");
    Route::post('/admin/create-history', [HistoryController::class,"create"])->name("/admin/create-history");
    Route::get('/admin/detail-history', [HistoryController::class,"detail"])->name("/admin/detail-history");
    Route::get('/admin/download-history', [HistoryController::class,"download"])->name("/admin/download-history");
    Route::get('/admin/preview-history', [HistoryController::class,"preview"])->name("/admin/preview-history");
    Route::get('/admin/configure-history', [HistoryController::class,"configureHistory"])->name("/admin/configure-history");
    Route::post('/admin/configure-history', [HistoryController::class,"saveConfiguration"])->name("/admin/configure-history-save");

    //utilities
    Route::get('/admin/xray-edit', [XrayController::class,"create"]);
    
    // Utilities - Medical Converter
    Route::get('/admin/utilities/converter', [UtilitiesController::class, 'medicalConverter'])->name('utilities.converter');
    Route::post('/admin/utilities/convert', [UtilitiesController::class, 'convert'])->name('utilities.convert');

    // Utilities - IMC Calculator
    Route::get('/admin/utilities/imc', [UtilitiesController::class, 'imcCalculator'])->name('utilities.imc');
    Route::post('/admin/utilities/calculate-imc', [UtilitiesController::class, 'calculateIMC'])->name('utilities.calculate-imc');

    // Utilities - Vaccination Schedule
    Route::get('/admin/utilities/vaccination', [UtilitiesController::class, 'vaccinationSchedule'])->name('utilities.vaccination');

    Route::get('/admin/create-medical-report', [PatientController::class,"createMedicalReport"]);
    Route::post('/admin/create-medical-report', [PatientController::class,"createMedicalReport"])->name("/admin/create-medical-report");
    Route::get('/admin/update-medical-report', [PatientController::class,"updateMedicalReport"]);
    Route::post('/admin/update-medical-report', [PatientController::class,"updateMedicalReport"])->name("/admin/update-medical-report");

    Route::get('/admin/create-medical-recipe', [PatientController::class,"createMedicalRecipes"]);
    Route::post('/admin/create-medical-recipe', [PatientController::class,"createMedicalRecipes"])->name("/admin/create-medical-recipe");
    Route::get('/admin/update-medical-recipe', [PatientController::class,"updateMedicalRecipes"]);
    Route::post('/admin/update-medical-recipe', [PatientController::class,"updateMedicalRecipes"])->name("/admin/update-medical-recipe");

    //Medical Services
    Route::get('/admin/create-medical-services', [MedicalServiceController::class, 'create'])->name('/admin/create-medical-services');
    Route::get('/admin/edit-medical-services/{medicalService}', [MedicalServiceController::class, 'edit'])->name('/admin/edit-medical-services');
    Route::post('/admin/create-medical-services', [MedicalServiceController::class, 'store'])->name('/admin/create-medical-services');
    Route::put('/admin/update-medical-services/{medicalService}', [MedicalServiceController::class, 'update'])->name('/admin/update-medical-services'); 
    Route::post('/admin/delete-medical-services', [MedicalServiceController::class, 'destroy'])->name('/admin/delete-medical-services');

    // Doctor Schedules Routes
    Route::prefix('admin/doctor/schedules')->name('doctor.schedules.')->group(function () {
        Route::get('/', [DoctorScheduleController::class, 'index'])->name('index');
        Route::get('/create', [DoctorScheduleController::class, 'create'])->name('create');
        Route::post('/', [DoctorScheduleController::class, 'store'])->name('store');
        Route::get('/{schedule}/edit', [DoctorScheduleController::class, 'edit'])->name('edit');
        Route::put('/{schedule}', [DoctorScheduleController::class, 'update'])->name('update');
        Route::delete('/{schedule}', [DoctorScheduleController::class, 'destroy'])->name('destroy');
        Route::post('/check-availability', [DoctorScheduleController::class, 'checkAvailability'])->name('check-availability');
    });

});

Route::group(['middleware' => ['role:admin|root|doctor|receptionist']], function () {

    //ver doctores
    Route::get('/admin/view-doctors', [UserController::class,"viewDoctors"])->name("/admin/view-doctors");
    // Patient Documents Routes
    Route::get('/admin/patient/documents', [PatientDocumentController::class, 'index'])->name('patient.documents');
    Route::post('/admin/patient/documents', [PatientDocumentController::class, 'store'])->name('patient.documents.store');
    Route::get('/admin/patient/documents/{id}', [PatientDocumentController::class, 'show'])->name('patient.documents.show');
    Route::get('/admin/patient/documents/{id}/download', [PatientDocumentController::class, 'download'])->name('patient.documents.download');
    Route::delete('/admin/patient/documents/{id}', [PatientDocumentController::class, 'destroy'])->name('patient.documents.destroy');
    
    // Patient Custom Field Values
    Route::post('/admin/patient/{patientId}/custom-fields', [PatientCustomFieldValueController::class, 'storeValues'])->name('patient.custom-fields.store');
    Route::delete('/admin/patient/{patientId}/custom-fields/{fieldId}', [PatientCustomFieldValueController::class, 'deleteValue'])->name('patient.custom-fields.delete');

    //emails
    Route::get('/admin/view-email', [EmailController::class,"inbox"])->name("/admin/view-email");
    Route::get('/admin/view-email-out', [EmailController::class,"outbox"])->name("/admin/view-email-out");
    Route::get('/admin/check-email/{id}', [EmailController::class,"checkEmailInbox"])->name("/admin/check-email");
    Route::get('/admin/check-email-out/{id}', [EmailController::class,"checkEmailOut"])->name("/admin/check-email-out");
    Route::post('/admin/answer', [EmailController::class,"answer"])->name("/admin/answer");


    //areas
    Route::get('/admin/view-areas', [AreaController::class,"view"])->name("/admin/view-areas");
    Route::get('/admin/create-areas', [AreaController::class,"create"]);
    //history
    Route::get('/admin/view-histories', [HistoryController::class,"view"])->name("/admin/view-histories");
    Route::get('/admin/detail-history', [HistoryController::class,"detail"])->name("/admin/detail-history");
    Route::get('/admin/download-history', [HistoryController::class,"download"])->name("/admin/download-history");
    Route::get('/admin/preview-history', [HistoryController::class,"preview"])->name("/admin/preview-history");

    //patients
    Route::get('/admin/view-patients', [PatientController::class,"view"])->name("/admin/view-patients");
    Route::get('/admin/create-patient', [PatientController::class,"create"]);
    Route::post('/admin/create-patient', [PatientController::class,"create"])->name("/admin/create-patient");
    Route::get('/admin/update-patient', [PatientController::class,"update"]);
    Route::post('/admin/update-patient', [PatientController::class,"update"])->name("/admin/update-patient");
    Route::get('/admin/detail-patient', [PatientController::class,"detail"])->name("/admin/detail-patient");

    //Representative
    Route::get('/admin/create-representative-from-patient', [RepresentativeController::class,"createFromPatient"])->name("/admin/create-representative-from-patient");
    Route::get('/admin/create-representative', [RepresentativeController::class,"create"]);
    Route::post('/admin/create-representative', [RepresentativeController::class,"create"])->name("/admin/create-representative");

    //appointments
    Route::get('/admin/view-appointments', [AppointmentController::class,"view"])->name("/admin/view-appointments");
    Route::get('/admin/detail-appointment', [AppointmentController::class,"detail"])->name("/admin/detail-appointment");
    Route::get('/admin/create-appointment', [AppointmentController::class,"create"]);
    Route::get('/admin/remember-appointment', [AppointmentController::class,"rememberAppointment"])->name("/admin/remember-appointment");
    Route::post('/admin/delete-appointment', [AppointmentController::class,"delete"])->name("/admin/delete-appointment");
    Route::post('/admin/create-appointment', [AppointmentController::class,"create"])->name("/admin/create-appointment");
    Route::post('/admin/update-appointment', [AppointmentController::class,"create"])->name("/admin/update-appointment");
    Route::post('/admin/close-appointment', [AppointmentController::class,"closeAppointment"])->name("/admin/close-appointment");
    Route::post('/admin/reschedule-appointment', [AppointmentController::class,"rescheduleAppointment"])->name("/admin/reschedule-appointment");
    
    // Rutas para la integración de citas y pagos
    Route::get('/admin/appointment-payment-relation', [App\Http\Controllers\AppointmentPaymentRelationController::class, 'index'])->name('appointment.payment.relation');
    Route::get('/admin/appointment-payment-relation/export', [App\Http\Controllers\AppointmentPaymentRelationController::class, 'export'])->name('appointment.payment.relation.export');
    Route::get('/admin/payment-for-appointment', [AppointmentController::class,"paymentForAppointment"])->name("/admin/payment-for-appointment");
    Route::get('/admin/payment-for-appointment-individual/{appointment}', [AppointmentController::class,"paymentForAppointmentIndividual"])->name("/admin/payment-for-appointment-individual");
    // Payment routes
    Route::post('/admin/complete-payment-individual', [AppointmentController::class,"completePaymentIndividual"])->name("complete-payment-individual");
    Route::post('/admin/complete-appointment-with-payment', [AppointmentController::class,"completeAppointmentWithPayment"])->name("complete-appointment-with-payment");
    Route::post('/admin/payments/additional/{payment}', [AppointmentController::class, 'processAdditionalPayment'])->name('admin.payments.additional');
    Route::get('/admin/payments/{payment}', [PaymentsController::class, 'show'])->name('admin.payments.show');
    Route::post('/admin/payments/{payment}/add-services', [AppointmentController::class, 'addServices'])->name('admin.payments.add-services');

    
    Route::get('/admin/view-medical-recipes', [PatientController::class,"viewMedicalRecipes"])->name("/admin/view-medical-recipes");


    Route::get('/admin/view-medical-reports', [PatientController::class,"viewMedicalReports"])->name("/admin/view-medical-reports");
   
    Route::get('/admin/download-medical-report', [PatientController::class,"downloadMedicalReport"])->name("/admin/download-medical-report");
    Route::get('/admin/download-medical-report-preview', [PatientController::class,"downloadMedicalReportPreview"])->name("/admin/download-medical-report-preview");
    Route::get('/admin/delete-medical-report', [PatientController::class,"deleteMedicalReport"])->name("/admin/delete-medical-report");


    Route::get('/admin/download-medical-recipe', [PatientController::class,"downloadMedicalRecipes"])->name("/admin/download-medical-recipe");
    Route::get('/admin/download-medical-recipe-preview', [PatientController::class,"downloadMedicalRecipesPreview"])->name("/admin/download-medical-recipe-preview");

    //currencies
    Route::get('/admin/view-currencies', [CurrenciesController::class,"view"])->name("/admin/view-currencies");
    Route::get('/admin/create-currency', [CurrenciesController::class,"create"]);


    //payments
    //Route::post('/admin/create-payment', [PaymentsController::class,"create"])->name("/admin/create-payment");
    //Route::get('/admin/create-payment', [PaymentsController::class,"create"]);
    Route::post('/admin/update-payment', [PaymentsController::class,"update"])->name("/admin/update-payment");
    Route::get('/admin/update-payment', [PaymentsController::class,"update"]);
    Route::get('/admin/view-payments', [PaymentsController::class,"view"])->name("/admin/view-payments");
    Route::get('/admin/detail-payment', [PaymentsController::class,"detail"])->name("/admin/detail-payment");
    Route::get('/admin/view-payments/export', [PaymentsController::class, 'export'])->name('payments.export')->middleware(['auth', 'terms.accepted', 'role:admin|root|doctor|receptionist']);





    //Payment Methods
    Route::get('/admin/view-payments-method', [PaymentsMethodController::class,"view"])->name("/admin/view-payments-method");
    Route::get('/admin/create-payments-method', [PaymentsMethodController::class,"create"]);
    Route::post('/admin/create-payments-method', [PaymentsMethodController::class,"create"])->name("/admin/create-payments-method");
    Route::post('/admin/update-payments-method', [PaymentsMethodController::class,"update"])->name("/admin/update-payments-method");
    Route::get('/admin/update-payments-method', [PaymentsMethodController::class,"update"]);
    Route::get('/admin/detail-payments-method', [PaymentsMethodController::class,"detail"])->name("/admin/detail-payments-method");


    Route::get('/admin/preview-files', [HistoryController::class, 'previewFile'])->name('/admin/preview-files');
    Route::get('/admin/files/{filename}', [FileController::class, 'show'])->name('files.show');
    Route::post('/admin/history-create-file', [HistoryController::class, 'uploadFiles'])->name("/admin/history-create-file");;

    //Medical Services
    Route::get('/admin/view-medical-services', [MedicalServiceController::class, 'index'])->name('/admin/view-medical-services');
  

    Route::get('/admin/additional-payment/{payment}', [AppointmentController::class, 'additionalPayment'])->name('additional-payment');

});


//MedicalReports














//dashboard
Route::get('/admin/dashboard', [DashboardController::class,"view"])->name('dashboard');
Route::get('/admin/not-authorized', [DashboardController::class,"notAuthorized"])->name("/admin/not-authorized");


});

Route::get('/create-external', [AppointmentController::class,"createExternal"])->name("/create-external");;
Route::post('/create-external', [AppointmentController::class,"createExternal"])->name("/create-external");


Route::group(['prefix' => 'api','middleware' => 'cors-send-appointment'], function () {
    Route::post('/createAppointment',[AppointmentController::class,"createFromApi"]);
    Route::post('/appointment/create',[AppointmentApiController::class,"apiCreate"]);
    Route::get('/desease/{desease}', [ICDController::class, 'getDesease']);
    Route::get('/getToken', [AppointmentApiController::class,"getToken"]);
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::get('/admin/get-history-configuration', [HistoryController::class, 'getHistoryConfiguration'])->name('admin.get-history-configuration');

Route::resource('histories', App\Http\Controllers\HistoryController::class);

Route::get('/especialities/{especiality}/configuration', [EspecialityConfigurationController::class, 'getConfiguration'])->name('especialities.configuration');

Route::post('/section-types/names', [SectionTypeController::class, 'getNames'])->name('section-types.names');

// Rutas de auditoría
Route::prefix('admin')->middleware(['auth'])->group(function () {
    Route::get('/audits', 'App\Http\Controllers\AuditController@index')->name('admin.audits.index');
    Route::get('/audits/{id}', 'App\Http\Controllers\AuditController@show')->name('admin.audits.show');
    Route::post('/audits/cleanup', 'App\Http\Controllers\AuditController@cleanup')->name('admin.audits.cleanup');
});

// Rutas para presupuestos
Route::middleware(['auth', 'role:admin|root|doctor|receptionist'])->group(function () {
    Route::get('/admin/view-budgets', [BudgetController::class, 'index'])->name('budgets.index');
    Route::get('/admin/create-budget', [BudgetController::class, 'create'])->name('budgets.create');
    Route::post('/admin/budgets', [BudgetController::class, 'store'])->name('budgets.store');
    Route::get('/admin/budgets/{budget}', [BudgetController::class, 'show'])->name('budgets.show');
    Route::get('/admin/budgets/{budget}/edit', [BudgetController::class, 'edit'])->name('budgets.edit');
    Route::put('/admin/budgets/{budget}', [BudgetController::class, 'update'])->name('budgets.update');
    Route::delete('/admin/budgets/{budget}', [BudgetController::class, 'destroy'])->name('budgets.destroy');
    Route::post('/admin/budgets/{budget}/send', [BudgetController::class, 'send'])->name('budgets.send');
    Route::post('/admin/budgets/{budget}/approve', [BudgetController::class, 'approve'])->name('budgets.approve');
    Route::post('/admin/budgets/{budget}/reject', [BudgetController::class, 'reject'])->name('budgets.reject');
});

Route::middleware(['auth'])->group(function () {
    // Rutas para el convertidor médico
    Route::get('/utilities/converter', [UtilitiesController::class, 'medicalConverter'])->name('utilities.converter');
    Route::post('/utilities/convert', [UtilitiesController::class, 'convert'])->name('utilities.convert');

    // Doctor Schedules Routes
    Route::prefix('doctor/schedules')->name('doctor.schedules.')->group(function () {
        Route::get('/', [DoctorScheduleController::class, 'index'])->name('index');
        Route::get('/create', [DoctorScheduleController::class, 'create'])->name('create');
        Route::post('/', [DoctorScheduleController::class, 'store'])->name('store');
        Route::get('/{schedule}/edit', [DoctorScheduleController::class, 'edit'])->name('edit');
        Route::put('/{schedule}', [DoctorScheduleController::class, 'update'])->name('update');
        Route::delete('/{schedule}', [DoctorScheduleController::class, 'destroy'])->name('destroy');
    });
});

Route::get('/admin/get-available-slots', [AppointmentController::class, 'getAvailableSlots'])
    ->name('/admin/get-available-slots')
    ->middleware(['auth', 'permission:create-appointment']);

Route::get('/doctor/available-hours', [AppointmentController::class, 'getAvailableHours'])->name('doctor.available-hours');

Route::get('/admin/doctor/available-days', [AppointmentController::class, 'getDoctorAvailableDays'])
    ->name('doctor.available-days')
    ->middleware(['auth']);

// Rutas para horarios de doctores (original)
 Route::get('/schedules', [DoctorScheduleController::class, 'index'])->name('doctor.schedules.index');
 Route::get('/admin/schedules', [DoctorScheduleController::class, 'viewAllSchedules'])->name('admin.schedules.index');


// Rutas para la identidad del consultorio
Route::prefix('admin')->middleware(['auth', 'terms.accepted', 'role:admin|root'])->group(function () {
    Route::get('/clinic-identity', 'App\Http\Controllers\ClinicIdentityController@index')->name('clinic-identity.index');
    Route::get('/clinic-identity/storage-link', 'App\Http\Controllers\ClinicIdentityController@createStorageLink')->name('clinic-identity.storage-link');
    Route::get('/clinic-identity/create', 'App\Http\Controllers\ClinicIdentityController@create')->name('clinic-identity.create');
    Route::post('/clinic-identity', 'App\Http\Controllers\ClinicIdentityController@store')->name('clinic-identity.store');
    Route::get('/clinic-identity/{id}/edit', 'App\Http\Controllers\ClinicIdentityController@edit')->name('clinic-identity.edit');
    Route::put('/clinic-identity/{id}', 'App\Http\Controllers\ClinicIdentityController@update')->name('clinic-identity.update');
    Route::delete('/clinic-identity/{id}', 'App\Http\Controllers\ClinicIdentityController@destroy')->name('clinic-identity.destroy');
    Route::get('/clinic-identity/{id}/set-active', 'App\Http\Controllers\ClinicIdentityController@setActive')->name('clinic-identity.set-active');
});



// Rutas para el portal público
Route::get('/portal', 'App\Http\Controllers\PortalController@index')->name('portal.index');
Route::get('/portal/servicios', 'App\Http\Controllers\PortalController@services')->name('portal.services');
Route::get('/portal/contacto', 'App\Http\Controllers\PortalController@contact')->name('portal.contact');
Route::post('/portal/contacto', 'App\Http\Controllers\PortalController@submitContact')->name('portal.contact.send');
Route::get('/portal/registro', 'App\Http\Controllers\PortalController@register')->name('portal.register');
Route::post('/portal/registro', 'App\Http\Controllers\PortalController@storePatient')->name('portal.storePatient');
Route::get('/portal/citas', 'App\Http\Controllers\PortalController@appointments')->name('portal.appointments');
Route::post('/portal/citas', 'App\Http\Controllers\PortalController@storeAppointment')->name('portal.storeAppointment');


// Rutas para el sistema de inventario eliminar
Route::group(['middleware' => ['auth', 'terms.accepted', 'role:admin|root']], function () { 
    // Categorías de inventario
    Route::prefix('admin/inventory/categories')->name('inventory.categories.')->group(function () {
        Route::delete('/{category}', [InventoryCategoryController::class, 'destroy'])->name('destroy');
    });

    // Proveedores de inventario (en un grupo separado)
    Route::prefix('admin/inventory/suppliers')->name('inventory.suppliers.')->group(function () {
        Route::delete('/{supplier}', [SupplierController::class, 'destroy'])->name('destroy');
    });

     // Al final, las rutas dinámicas de inventario
     Route::prefix('admin/inventory')->name('inventory.')->group(function () {
        Route::delete('/{inventory}', [InventoryController::class, 'destroy'])->name('destroy');
    });
});


//Rutar para el sistema de inventario Crear, Actualizar
Route::group(['middleware' => ['auth', 'terms.accepted', 'role:admin|root|inventory']], function () { 
    
      // Inventario principal
      Route::prefix('admin/inventory')->name('inventory.')->group(function () {
        // Rutas específicas primero
        Route::get('/', [InventoryController::class, 'index'])->name('index');
        Route::get('/create', [InventoryController::class, 'create'])->name('create');
        Route::post('/', [InventoryController::class, 'store'])->name('store');
        Route::get('/low-stock', [InventoryController::class, 'lowStock'])->name('low-stock');
        Route::get('/export', [InventoryController::class, 'export'])->name('export');
        Route::get('/category/{category}', [InventoryController::class, 'byCategory'])->name('by-category');
    });

     // Categorías de inventario (en un grupo separado)
     Route::prefix('admin/inventory/categories')->name('inventory.categories.')->group(function () {
        Route::get('/', [InventoryCategoryController::class, 'index'])->name('index');
        Route::get('/create', [InventoryCategoryController::class, 'create'])->name('create');
        Route::post('/', [InventoryCategoryController::class, 'store'])->name('store');
        Route::get('/{category}', [InventoryCategoryController::class, 'show'])->name('show');
        Route::get('/{category}/edit', [InventoryCategoryController::class, 'edit'])->name('edit');
        Route::put('/{category}', [InventoryCategoryController::class, 'update'])->name('update');
    });


     // Proveedores de inventario (en un grupo separado)
     Route::prefix('admin/inventory/suppliers')->name('inventory.suppliers.')->group(function () {
        Route::get('/', [SupplierController::class, 'index'])->name('index');
        Route::get('/create', [SupplierController::class, 'create'])->name('create');
        Route::post('/', [SupplierController::class, 'store'])->name('store');
        Route::get('/{supplier}', [SupplierController::class, 'show'])->name('show');
        Route::get('/{supplier}/edit', [SupplierController::class, 'edit'])->name('edit');
        Route::put('/{supplier}', [SupplierController::class, 'update'])->name('update');
        Route::get('/{supplier}/items', [SupplierController::class, 'items'])->name('items');
    });


     // Transacciones de inventario (en un grupo separado)
     Route::prefix('admin/inventory/transactions')->name('inventory.transactions.')->group(function () {
        Route::get('/', [InventoryTransactionController::class, 'index'])->name('index');
        Route::get('/create', [InventoryTransactionController::class, 'create'])->name('create');
        Route::post('/', [InventoryTransactionController::class, 'store'])->name('store');
        Route::get('/inventory/{inventory}', [InventoryTransactionController::class, 'forInventory'])->name('for-inventory');
        Route::get('/{transaction}', [InventoryTransactionController::class, 'show'])->name('show');
    });
    
    // Al final, las rutas dinámicas de inventario
    Route::prefix('admin/inventory')->name('inventory.')->group(function () {
        Route::get('/{inventory}', [InventoryController::class, 'show'])->name('show');
        Route::get('/{inventory}/edit', [InventoryController::class, 'edit'])->name('edit');
        Route::put('/{inventory}', [InventoryController::class, 'update'])->name('update');
        Route::post('/{inventory}/adjust', [InventoryController::class, 'adjustQuantity'])->name('adjust');
    });
});






Route::get('/admin/view-appointments/export', [AppointmentController::class, 'export'])->name('appointments.export');

Route::get('/admin/view-patients/export', [PatientController::class, 'export'])->name('patients.export')->middleware(['auth', 'terms.accepted', 'role:admin|root|doctor|receptionist']);

// Rutas para citas recurrentes
Route::prefix('admin')->middleware(['auth', 'terms.accepted'])->group(function () {
    Route::get('/recurring-appointments', [RecurringAppointmentController::class, 'index'])->name('recurring-appointments.index')->middleware(['role:admin|root|doctor|receptionist']);
    Route::get('/recurring-appointments/create', [RecurringAppointmentController::class, 'create'])->name('recurring-appointments.create')->middleware(['role:admin|root|doctor|receptionist']);
    Route::post('/recurring-appointments', [RecurringAppointmentController::class, 'store'])->name('recurring-appointments.store')->middleware(['role:admin|root|doctor|receptionist']);
    Route::get('/recurring-appointments/{id}', [RecurringAppointmentController::class, 'show'])->name('recurring-appointments.show')->middleware(['role:admin|root|doctor|receptionist']);
    Route::get('/recurring-appointments/{id}/edit', [RecurringAppointmentController::class, 'edit'])->name('recurring-appointments.edit')->middleware(['role:admin|root|doctor|receptionist']);
    Route::put('/recurring-appointments/{id}', [RecurringAppointmentController::class, 'update'])->name('recurring-appointments.update')->middleware(['role:admin|root|doctor|receptionist']);
    Route::delete('/recurring-appointments/{id}/cancel', [RecurringAppointmentController::class, 'cancel'])->name('recurring-appointments.cancel')->middleware(['role:admin|root|doctor|receptionist']);
});

// Ruta para el procesamiento programado (protegida con middleware)
Route::post('/api/whatsapp/webhook', [WhatsAppController::class, 'handleIncoming']);
Route::get('/api/whatsapp/send', [WhatsAppController::class, 'sendWelcomeMessage']);
Route::get('/api/process-recurring-appointments', [RecurringAppointmentController::class, 'processPendingRecurringAppointments'])->middleware(['auth.api']);

// Rutas para la gestión de permisos de rutas
Route::prefix('admin/routes')->name('routes.')->middleware(['auth', 'terms.accepted', 'role:admin|root'])->group(function () {
    Route::get('/', [RoutePermissionController::class, 'index'])->name('index');
    Route::get('/create', [RoutePermissionController::class, 'create'])->name('create');
    Route::post('/', [RoutePermissionController::class, 'store'])->name('store');
    Route::get('/{route}/edit', [RoutePermissionController::class, 'edit'])->name('edit');
    Route::put('/{route}', [RoutePermissionController::class, 'update'])->name('update');
    Route::delete('/{route}', [RoutePermissionController::class, 'destroy'])->name('destroy');
    Route::get('/detect', [RoutePermissionController::class, 'detectRoutes'])->name('detect');
    Route::post('/import', [RoutePermissionController::class, 'importRoutes'])->name('import');
});

// Ruta de 'no autorizado'
Route::get('/admin/not-authorized', function() {
    return view('errors.not-authorized');
})->name('not-authorized');
