<?php

declare(strict_types=1);

use App\Controllers\ActivityLogController;
use App\Controllers\AiAssistantController;
use App\Controllers\AiPromptController;
use App\Controllers\ApiKeyController;
use App\Controllers\AppointmentController;
use App\Controllers\AttachmentController;
use App\Controllers\AudienceSegmentController;
use App\Controllers\AuthController;
use App\Controllers\AutomationController;
use App\Controllers\CampaignController;
use App\Controllers\ChatbotController;
use App\Controllers\CommentController;
use App\Controllers\CompanyController;
use App\Controllers\ConversationController;
use App\Controllers\CustomerController;
use App\Controllers\DashboardController;
use App\Controllers\DepartmentController;
use App\Controllers\EmailTemplateController;
use App\Controllers\IntegrationController;
use App\Controllers\KnowledgeBaseController;
use App\Controllers\LeadController;
use App\Controllers\LeadSourceController;
use App\Controllers\NoteController;
use App\Controllers\NotificationController;
use App\Controllers\PermissionController;
use App\Controllers\PersonalEmailController;
use App\Controllers\ProfileController;
use App\Controllers\ReportController;
use App\Controllers\RoleController;
use App\Controllers\ServiceController;
use App\Controllers\SmtpSettingsController;
use App\Controllers\TagController;
use App\Controllers\TaskController;
use App\Controllers\TeamController;
use App\Controllers\TrackingController;
use App\Controllers\TrainingDataController;
use App\Controllers\UploadController;
use App\Controllers\UserController;
use App\Controllers\VoiceAgentController;
use App\Core\Request;
use App\Core\Response;




/**
 * routes/web.php
 *
 * Phase 2 (auth + administration) and Phase 3 (CRM modules) routes,
 * all on the same Router/middleware foundation from Phase 1. Every
 * route is backed by a real controller — see docs/ARCHITECTURE.md §9
 * for the pattern every future module plugs into.
 */


/** @var \App\Core\Router $router */

$router->get('/health', function (Request $request): Response {
    try {
        \App\Core\Database::connection()->query('SELECT 1');
        $dbOk = true;
    } catch (\Throwable) {
        $dbOk = false;
    }

    return Response::json(['status' => $dbOk ? 'ok' : 'degraded', 'database' => $dbOk, 'timestamp' => now()], $dbOk ? 200 : 503);
});

// ---------------------------------------------------------------
// Guest-only (auth)
// ---------------------------------------------------------------
$router->get('/', fn () => Response::redirect(base_url('login')));

$router->get('/login', [AuthController::class, 'showLoginForm'], middleware: ['guest']);
$router->post('/login', [AuthController::class, 'login'], middleware: ['guest', 'csrf', 'throttle:strict']);
$router->post('/login/2fa', [AuthController::class, 'twoFactorChallenge'], middleware: ['guest', 'csrf', 'throttle:strict']);
$router->post('/logout', [AuthController::class, 'logout'], middleware: ['csrf']);

$router->get('/forgot-password', [AuthController::class, 'showForgotPasswordForm'], middleware: ['guest']);
$router->post('/forgot-password', [AuthController::class, 'sendResetLink'], middleware: ['guest', 'csrf', 'throttle:strict']);
$router->get('/reset-password/{token}', [AuthController::class, 'showResetPasswordForm'], middleware: ['guest']);
$router->post('/reset-password', [AuthController::class, 'resetPassword'], middleware: ['guest', 'csrf', 'throttle:strict']);

$router->get('/verify-email/{token}', [AuthController::class, 'verifyEmail']);
$router->get('/accept-invitation/{token}', [AuthController::class, 'acceptInvitation'], middleware: ['guest']);
$router->post('/accept-invitation', [AuthController::class, 'completeInvitation'], middleware: ['guest', 'csrf', 'throttle:strict']);

// ---------------------------------------------------------------
// Authenticated app shell
// ---------------------------------------------------------------
$router->get('/dashboard', [DashboardController::class, 'index'], middleware: ['auth']);

// ---- File serving (avatars, attachments) ----
$router->get('/uploads-view/{path}', [UploadController::class, 'show'], middleware: ['auth']);

// ---- Profile (self-service, no special permission needed beyond being logged in) ----
$router->get('/profile', [ProfileController::class, 'show'], middleware: ['auth']);
$router->patch('/profile', [ProfileController::class, 'update'], middleware: ['auth', 'csrf']);
$router->post('/profile/email', [ProfileController::class, 'updateEmail'], middleware: ['auth', 'csrf']);
$router->post('/profile/password', [ProfileController::class, 'changePassword'], middleware: ['auth', 'csrf', 'throttle:strict']);
$router->post('/profile/avatar', [ProfileController::class, 'uploadAvatar'], middleware: ['auth', 'csrf', 'throttle:upload']);
$router->post('/profile/preferences', [ProfileController::class, 'updatePreferences'], middleware: ['auth', 'csrf']);
$router->get('/profile/sessions', [ProfileController::class, 'listSessions'], middleware: ['auth']);
$router->delete('/profile/sessions/{sessionId}', [ProfileController::class, 'revokeSession'], middleware: ['auth', 'csrf']);
$router->post('/profile/sessions/revoke-others', [ProfileController::class, 'revokeAllOtherSessions'], middleware: ['auth', 'csrf']);
$router->post('/profile/2fa/setup', [ProfileController::class, 'twoFactorSetup'], middleware: ['auth', 'csrf']);
$router->post('/profile/2fa/confirm', [ProfileController::class, 'twoFactorConfirm'], middleware: ['auth', 'csrf']);
$router->post('/profile/2fa/disable', [ProfileController::class, 'twoFactorDisable'], middleware: ['auth', 'csrf']);

// ---- Notifications ----
$router->get('/notifications', [NotificationController::class, 'index'], middleware: ['auth']);

// ---- Admin: Users ----
$router->get('/users', [UserController::class, 'index'], middleware: ['auth', 'permission:user_management.view']);
$router->get('/users/{id}', [UserController::class, 'show'], middleware: ['auth', 'permission:user_management.view']);
$router->post('/users', [UserController::class, 'store'], middleware: ['auth', 'csrf', 'permission:user_management.create']);
$router->patch('/users/{id}', [UserController::class, 'update'], middleware: ['auth', 'csrf', 'permission:user_management.update']);
$router->post('/users/{id}/deactivate', [UserController::class, 'deactivate'], middleware: ['auth', 'csrf', 'permission:user_management.update']);
$router->post('/users/{id}/reactivate', [UserController::class, 'reactivate'], middleware: ['auth', 'csrf', 'permission:user_management.update']);
$router->post('/users/{id}/reset-password', [UserController::class, 'resetPassword'], middleware: ['auth', 'csrf', 'permission:user_management.update']);
$router->delete('/users/{id}', [UserController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:user_management.delete']);

// ---- Admin: Roles & Permissions ----
$router->get('/roles', [RoleController::class, 'index'], middleware: ['auth', 'permission:user_management.manage']);
$router->post('/roles', [RoleController::class, 'store'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->patch('/roles/{id}', [RoleController::class, 'update'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->delete('/roles/{id}', [RoleController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->put('/roles/{roleId}/permissions', [PermissionController::class, 'updateRolePermissions'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);

// ---- Admin: Departments ----
$router->get('/departments', [DepartmentController::class, 'index'], middleware: ['auth', 'permission:user_management.manage']);
$router->post('/departments', [DepartmentController::class, 'store'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->patch('/departments/{id}', [DepartmentController::class, 'update'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->delete('/departments/{id}', [DepartmentController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);

// ---- Admin: Teams ----
$router->get('/teams', [TeamController::class, 'index'], middleware: ['auth', 'permission:user_management.manage']);
$router->get('/teams/{id}/members', [TeamController::class, 'members'], middleware: ['auth', 'permission:user_management.manage']);
$router->post('/teams', [TeamController::class, 'store'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->patch('/teams/{id}', [TeamController::class, 'update'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->delete('/teams/{id}', [TeamController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->post('/teams/{id}/members', [TeamController::class, 'addMember'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->delete('/teams/{id}/members/{userId}', [TeamController::class, 'removeMember'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);

// ---- Admin: Activity Logs & Login History ----
$router->get('/activity-logs', [ActivityLogController::class, 'index'], middleware: ['auth', 'permission:user_management.view']);
$router->get('/login-history', [ActivityLogController::class, 'loginHistory'], middleware: ['auth']);

// ---------------------------------------------------------------
// Phase 3: CRM modules
// ---------------------------------------------------------------


// ---- Leads ----
$router->get('/leads', [LeadController::class, 'index'], middleware: ['auth', 'permission:leads_customers.view']);
$router->get('/leads/import', [LeadController::class, 'importForm'], middleware: ['auth', 'permission:leads_customers.create']);
$router->get('/leads/export', [LeadController::class, 'export'], middleware: ['auth', 'permission:leads_customers.export']);
$router->post('/leads/bulk-action', [LeadController::class, 'bulkAction'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->get('/leads/trashed', [LeadController::class, 'trashed'], middleware: ['auth', 'permission:leads_customers.delete']);
$router->get('/leads/{id}', [LeadController::class, 'show'], middleware: ['auth', 'permission:leads_customers.view']);
$router->post('/leads', [LeadController::class, 'store'], middleware: ['auth', 'csrf', 'permission:leads_customers.create']);
$router->post('/leads/import', [LeadController::class, 'import'], middleware: ['auth', 'csrf', 'permission:leads_customers.create', 'throttle:upload']);
$router->patch('/leads/{id}', [LeadController::class, 'update'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->post('/leads/{id}/stage', [LeadController::class, 'moveStage'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->post('/leads/{id}/convert', [LeadController::class, 'convert'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->post('/leads/{id}/merge', [LeadController::class, 'merge'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);
$router->post('/leads/{id}/restore', [LeadController::class, 'restore'], middleware: ['auth', 'csrf', 'permission:leads_customers.delete']);
$router->delete('/leads/{id}', [LeadController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:leads_customers.delete']);

// ---- Customers ----
$router->get('/customers', [CustomerController::class, 'index'], middleware: ['auth', 'permission:leads_customers.view']);
$router->get('/customers/export', [CustomerController::class, 'export'], middleware: ['auth', 'permission:leads_customers.export']);
$router->get('/customers/trashed', [CustomerController::class, 'trashed'], middleware: ['auth', 'permission:leads_customers.delete']);
$router->get('/customers/{id}', [CustomerController::class, 'show'], middleware: ['auth', 'permission:leads_customers.view']);
$router->post('/customers', [CustomerController::class, 'store'], middleware: ['auth', 'csrf', 'permission:leads_customers.create']);
$router->patch('/customers/{id}', [CustomerController::class, 'update'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->post('/customers/{id}/restore', [CustomerController::class, 'restore'], middleware: ['auth', 'csrf', 'permission:leads_customers.delete']);
$router->delete('/customers/{id}', [CustomerController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:leads_customers.delete']);

// ---- Companies ----
$router->get('/companies', [CompanyController::class, 'index'], middleware: ['auth', 'permission:leads_customers.view']);
$router->get('/companies/export', [CompanyController::class, 'export'], middleware: ['auth', 'permission:leads_customers.export']);
$router->get('/companies/{id}', [CompanyController::class, 'show'], middleware: ['auth', 'permission:leads_customers.view']);
$router->post('/companies', [CompanyController::class, 'store'], middleware: ['auth', 'csrf', 'permission:leads_customers.create']);
$router->patch('/companies/{id}', [CompanyController::class, 'update'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->post('/companies/{id}/restore', [CompanyController::class, 'restore'], middleware: ['auth', 'csrf', 'permission:leads_customers.delete']);
$router->delete('/companies/{id}', [CompanyController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:leads_customers.delete']);

// ---- Services & Lead Sources (settings-like admin pages) ----
$router->get('/services', [ServiceController::class, 'index'], middleware: ['auth', 'permission:leads_customers.manage']);
$router->post('/services/types', [ServiceController::class, 'storeType'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);
$router->patch('/services/types/{id}', [ServiceController::class, 'updateType'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);
$router->delete('/services/types/{id}', [ServiceController::class, 'destroyType'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);
$router->post('/services/plans', [ServiceController::class, 'storePlan'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);
$router->patch('/services/plans/{id}', [ServiceController::class, 'updatePlan'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);
$router->delete('/services/plans/{id}', [ServiceController::class, 'destroyPlan'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);

$router->get('/lead-sources', [LeadSourceController::class, 'index'], middleware: ['auth', 'permission:leads_customers.manage']);
$router->post('/lead-sources', [LeadSourceController::class, 'store'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);
$router->patch('/lead-sources/{id}', [LeadSourceController::class, 'update'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);
$router->delete('/lead-sources/{id}', [LeadSourceController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:leads_customers.manage']);

// ---- Appointments ----
$router->get('/appointments', [AppointmentController::class, 'calendar'], middleware: ['auth', 'permission:scheduling.view']);
$router->get('/appointments/feed', [AppointmentController::class, 'feed'], middleware: ['auth', 'permission:scheduling.view']);
$router->get('/appointments/availability', [AppointmentController::class, 'checkAvailability'], middleware: ['auth', 'permission:scheduling.view']);
$router->get('/appointments/export', [AppointmentController::class, 'export'], middleware: ['auth', 'permission:scheduling.view']);
$router->post('/appointments', [AppointmentController::class, 'store'], middleware: ['auth', 'csrf', 'permission:scheduling.create']);
$router->patch('/appointments/{id}/reschedule', [AppointmentController::class, 'reschedule'], middleware: ['auth', 'csrf', 'permission:scheduling.update']);
$router->post('/appointments/{id}/cancel', [AppointmentController::class, 'cancel'], middleware: ['auth', 'csrf', 'permission:scheduling.update']);
$router->post('/appointments/{id}/complete', [AppointmentController::class, 'complete'], middleware: ['auth', 'csrf', 'permission:scheduling.update']);
$router->post('/appointments/{id}/missed', [AppointmentController::class, 'missed'], middleware: ['auth', 'csrf', 'permission:scheduling.update']);
$router->delete('/appointments/{id}', [AppointmentController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:scheduling.delete']);

// ---- Shared: Tasks, Notes, Comments, Attachments, Tags (polymorphic, attach to lead/customer/company) ----
$router->post('/tasks', [TaskController::class, 'store'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->post('/tasks/{id}/toggle', [TaskController::class, 'toggle'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->delete('/tasks/{id}', [TaskController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->get('/my-tasks', [TaskController::class, 'myTasks'], middleware: ['auth']);

$router->post('/notes', [NoteController::class, 'store'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->get('/notes/{entityType}/{entityId}', [NoteController::class, 'index'], middleware: ['auth', 'permission:leads_customers.view']);
$router->delete('/notes/{id}', [NoteController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);

$router->post('/comments', [CommentController::class, 'store'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->get('/comments/{entityType}/{entityId}', [CommentController::class, 'index'], middleware: ['auth', 'permission:leads_customers.view']);
$router->delete('/comments/{id}', [CommentController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);

$router->post('/attachments', [AttachmentController::class, 'store'], middleware: ['auth', 'csrf', 'permission:leads_customers.update', 'throttle:upload']);
$router->get('/attachments/{entityType}/{entityId}', [AttachmentController::class, 'index'], middleware: ['auth', 'permission:leads_customers.view']);
$router->delete('/attachments/{id}', [AttachmentController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);

$router->get('/tags', [TagController::class, 'index'], middleware: ['auth', 'permission:leads_customers.view']);
$router->post('/tags/attach', [TagController::class, 'attach'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);
$router->delete('/tags/{tagId}/detach', [TagController::class, 'detach'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);

// ---------------------------------------------------------------
// Phase 4: Marketing system
// ---------------------------------------------------------------


// ---- Public tracking (no auth — hit by anonymous recipients) ----
$router->get('/track/open/{token}', [TrackingController::class, 'pixel']);
$router->get('/track/click/{token}', [TrackingController::class, 'click']);
$router->get('/unsubscribe/{token}', [TrackingController::class, 'showUnsubscribeForm']);
$router->post('/unsubscribe', [TrackingController::class, 'confirmUnsubscribe']);

// ---- Campaigns ----
$router->get('/campaigns', [CampaignController::class, 'index'], middleware: ['auth', 'permission:email_campaigns.view']);
$router->get('/campaigns/preview-audience', [CampaignController::class, 'previewAudience'], middleware: ['auth', 'permission:email_campaigns.view']);
$router->get('/campaigns/{id}', [CampaignController::class, 'show'], middleware: ['auth', 'permission:email_campaigns.view']);
$router->post('/campaigns', [CampaignController::class, 'store'], middleware: ['auth', 'csrf', 'permission:email_campaigns.create']);
$router->post('/campaigns/{id}/send-now', [CampaignController::class, 'sendNow'], middleware: ['auth', 'csrf', 'permission:email_campaigns.update']);
$router->post('/campaigns/{id}/schedule', [CampaignController::class, 'schedule'], middleware: ['auth', 'csrf', 'permission:email_campaigns.update']);
$router->post('/campaigns/{id}/cancel', [CampaignController::class, 'cancel'], middleware: ['auth', 'csrf', 'permission:email_campaigns.update']);
$router->delete('/campaigns/{id}', [CampaignController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:email_campaigns.delete']);

// ---- Email Templates ----
$router->get('/email-templates', [EmailTemplateController::class, 'index'], middleware: ['auth', 'permission:email_campaigns.view']);
$router->get('/email-templates/{id}', [EmailTemplateController::class, 'show'], middleware: ['auth', 'permission:email_campaigns.view']);
$router->post('/email-templates', [EmailTemplateController::class, 'store'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);
$router->patch('/email-templates/{id}', [EmailTemplateController::class, 'update'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);
$router->delete('/email-templates/{id}', [EmailTemplateController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);

// ---- Audience Segments ----
$router->get('/audience-segments', [AudienceSegmentController::class, 'index'], middleware: ['auth', 'permission:email_campaigns.view']);
$router->get('/audience-segments/preview', [AudienceSegmentController::class, 'preview'], middleware: ['auth', 'permission:email_campaigns.view']);
$router->post('/audience-segments', [AudienceSegmentController::class, 'store'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);
$router->delete('/audience-segments/{id}', [AudienceSegmentController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);

// ---- SMTP Settings ----
$router->get('/settings/smtp', [SmtpSettingsController::class, 'show'], middleware: ['auth', 'permission:email_campaigns.manage']);
$router->post('/settings/smtp', [SmtpSettingsController::class, 'update'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);
$router->post('/settings/smtp/test', [SmtpSettingsController::class, 'sendTestEmail'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);


use App\Controllers\BusinessLineSettingsController;
// ...
$router->get('/settings/business-lines', [BusinessLineSettingsController::class, 'show'], middleware: ['auth', 'permission:email_campaigns.manage']);
$router->post('/settings/business-lines', [BusinessLineSettingsController::class, 'update'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);

$router->post('/settings/business-lines/logo', [BusinessLineSettingsController::class, 'uploadLogo'], middleware: ['auth', 'csrf', 'permission:email_campaigns.manage']);






// ---- Marketing Automation ----
$router->get('/automation', [AutomationController::class, 'index'], middleware: ['auth', 'permission:ai_automation.view']);
$router->get('/automation/{id}', [AutomationController::class, 'show'], middleware: ['auth', 'permission:ai_automation.view']);
$router->post('/automation/{id}/toggle', [AutomationController::class, 'toggleActive'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);

// ---- Personal / Individual Email ----
$router->get('/emails', [PersonalEmailController::class, 'index'], middleware: ['auth', 'permission:leads_customers.view']);
$router->get('/emails/{entityType}/{entityId}', [PersonalEmailController::class, 'forEntity'], middleware: ['auth', 'permission:leads_customers.view']);
$router->post('/emails/send', [PersonalEmailController::class, 'send'], middleware: ['auth', 'csrf', 'permission:leads_customers.update']);

// ---------------------------------------------------------------
// Phase 5: AI modules & integrations
// ---------------------------------------------------------------


// ---- AI Assistant (staff-facing) ----
$router->get('/ai-assistant', [AiAssistantController::class, 'index'], middleware: ['auth', 'permission:ai_automation.view']);
$router->post('/ai-assistant/ask', [AiAssistantController::class, 'ask'], middleware: ['auth', 'csrf', 'permission:ai_automation.view']);
$router->get('/ai-assistant/history', [AiAssistantController::class, 'history'], middleware: ['auth', 'permission:ai_automation.view']);

// ---- Website Chatbot: public widget endpoints (no auth) ----
// $router->post('/widget/chatbot/start', [ChatbotController::class, 'start'], middleware: ['throttle:strict']);
// $router->post('/widget/chatbot/message', [ChatbotController::class, 'message'], middleware: ['throttle:strict']);
$router->post('/widget/chatbot/start', [ChatbotController::class, 'start'], middleware: ['cors', 'throttle:strict']);
$router->options('/widget/chatbot/start', [ChatbotController::class, 'start'], middleware: ['cors']);
$router->post('/widget/chatbot/message', [ChatbotController::class, 'message'], middleware: ['cors', 'throttle:strict']);
$router->options('/widget/chatbot/message', [ChatbotController::class, 'message'], middleware: ['cors']);




use App\Controllers\PublicLeadController;
$router->post('/widget/leads/capture', [PublicLeadController::class, 'capture'], middleware: ['cors', 'throttle:strict']);
$router->options('/widget/leads/capture', [PublicLeadController::class, 'capture'], middleware: ['cors']);


$router->post('/widget/leads/book', [PublicLeadController::class, 'bookQuote'], middleware: ['cors', 'throttle:strict']);
$router->options('/widget/leads/book', [PublicLeadController::class, 'bookQuote'], middleware: ['cors']);


// ---- Website Chatbot: admin settings ----
$router->get('/chatbot-settings', [ChatbotController::class, 'settings'], middleware: ['auth', 'permission:ai_automation.manage']);
$router->post('/chatbot-settings', [ChatbotController::class, 'updateSettings'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);

// ---- AI Voice Agent: public Twilio webhooks (signature-verified inside the controller, not session-auth'd) ----
$router->post('/voice/incoming', [VoiceAgentController::class, 'incomingCall']);
$router->post('/voice/gather', [VoiceAgentController::class, 'gatherResult']);
$router->post('/voice/status', [VoiceAgentController::class, 'statusCallback']);

// ---- AI Voice Agent: admin ----
$router->get('/voice-agent', [VoiceAgentController::class, 'index'], middleware: ['auth', 'permission:ai_automation.view']);
$router->post('/voice-agent/call', [VoiceAgentController::class, 'initiateCall'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);

// ---- Conversation Logs (unified: chatbot + voice + AI assistant) ----
$router->get('/conversation-logs', [ConversationController::class, 'index'], middleware: ['auth', 'permission:ai_automation.view']);
$router->get('/conversation-logs/{id}', [ConversationController::class, 'show'], middleware: ['auth', 'permission:ai_automation.view']);
$router->get('/conversation-logs-stats', [ConversationController::class, 'stats'], middleware: ['auth', 'permission:ai_automation.view']);

// ---- Knowledge Base ----
$router->get('/knowledge-base', [KnowledgeBaseController::class, 'index'], middleware: ['auth', 'permission:ai_automation.manage']);
$router->post('/knowledge-base', [KnowledgeBaseController::class, 'store'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->patch('/knowledge-base/{id}', [KnowledgeBaseController::class, 'update'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->delete('/knowledge-base/{id}', [KnowledgeBaseController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);

// ---- Prompt Management ----
$router->get('/ai-prompts', [AiPromptController::class, 'index'], middleware: ['auth', 'permission:ai_automation.manage']);
$router->post('/ai-prompts', [AiPromptController::class, 'store'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->patch('/ai-prompts/{id}', [AiPromptController::class, 'update'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->delete('/ai-prompts/{id}', [AiPromptController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);

// ---- Training Data ----
$router->get('/training-data', [TrainingDataController::class, 'index'], middleware: ['auth', 'permission:ai_automation.manage']);
$router->post('/training-data', [TrainingDataController::class, 'store'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->delete('/training-data/{id}', [TrainingDataController::class, 'destroy'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->get('/training-data/{feature}/export', [TrainingDataController::class, 'export'], middleware: ['auth', 'permission:ai_automation.manage']);

// ---- Integrations (AI Settings lives here too — every provider's config in one hub) ----
$router->get('/integrations', [IntegrationController::class, 'index'], middleware: ['auth', 'permission:ai_automation.manage']);
$router->post('/integrations/{slug}/connect', [IntegrationController::class, 'connect'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->post('/integrations/{slug}/disconnect', [IntegrationController::class, 'disconnect'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->post('/integrations/{slug}/oauth-config', [IntegrationController::class, 'saveOauthConfig'], middleware: ['auth', 'csrf', 'permission:ai_automation.manage']);
$router->get('/integrations/{slug}/redirect', [IntegrationController::class, 'googleAuthorize'], middleware: ['auth', 'permission:ai_automation.manage']);
$router->get('/integrations/{slug}/callback', [IntegrationController::class, 'googleCallback'], middleware: ['auth']);

// ---- Meta (Facebook/Instagram) Lead Ads webhook — public ----
$router->get('/webhooks/meta', [IntegrationController::class, 'metaWebhookVerify']);
$router->post('/webhooks/meta', [IntegrationController::class, 'metaWebhookReceive']);

// ---- Reports ----
$router->get('/reports', [ReportController::class, 'index'], middleware: ['auth', 'permission:reports_analytics.view']);
$router->get('/reports/{type}/export/{format}', [ReportController::class, 'export'], middleware: ['auth', 'permission:reports_analytics.view']);

// ---- API Keys ----
$router->get('/api-keys', [ApiKeyController::class, 'index'], middleware: ['auth', 'permission:user_management.manage']);
$router->post('/api-keys', [ApiKeyController::class, 'store'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);
$router->post('/api-keys/{id}/revoke', [ApiKeyController::class, 'revoke'], middleware: ['auth', 'csrf', 'permission:user_management.manage']);

// ---- Global Search ----
$router->get('/search', [\App\Controllers\SearchController::class, 'search'], middleware: ['auth']);
