<?php

use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use App\Http\Controllers\ListController;
use App\Http\Controllers\TagController;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\ContactExportController;
use App\Http\Controllers\ContactImportController;
use App\Http\Controllers\ContactNoteController;
use App\Http\Controllers\SmtpConfigController;
use App\Http\Controllers\GoogleOAuthController;
use App\Http\Controllers\MicrosoftOAuthController;
use App\Http\Controllers\WebhookController;
use App\Http\Controllers\FormController;
use App\Http\Controllers\CampaignController;
use App\Http\Controllers\RecurringCampaignController;
use App\Http\Controllers\TrackingController;
use App\Http\Controllers\SearchController;
use App\Http\Controllers\SettingsController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\SequenceController;
use App\Http\Controllers\AutomationController;
use App\Http\Controllers\AudienceController;
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\MediaController;
use App\Http\Controllers\TemplateController;
use App\Http\Controllers\Auth\OtpVerificationController;
use App\Http\Controllers\Auth\GuestVerificationResendController;

Route::get('/', function () {
    return Inertia::render('Home');
});

// Email tracking (no auth - called by email clients)
Route::get('/track/open/{campaign}/{contact}/{token}',        [TrackingController::class, 'open'])->name('track.open');
Route::get('/track/click/{campaign}/{contact}/{token}',       [TrackingController::class, 'click'])->name('track.click');
Route::get('/track/conversion/{campaign}/{contact}/{token}',  [TrackingController::class, 'conversion'])->name('track.conversion');
Route::get('/unsubscribe/{campaign}/{contact}/{token}',       [TrackingController::class, 'unsubscribe'])->name('track.unsubscribe');

// Uploaded file serving (no auth - referenced by sent email HTML, loaded directly
// by recipients' email clients). Served through a route instead of a public/storage
// symlink, since symlinks don't survive most shared-hosting deploy flows.
Route::get('/upload/{path}', [MediaController::class, 'serve'])->where('path', '.*')->name('media.serve');
Route::get('/storage/{path}', [MediaController::class, 'serveLegacy'])->where('path', '.*')->name('media.serve-legacy');

// Email verification - OTP code entry (needs a live session, reached from the
// verify-email notice page) and a guest-accessible resend for anyone whose
// session already expired before they verified (Fortify's own verification
// routes all require auth:web, so without this there'd be no way back in).
Route::post('/email/verify-otp', [OtpVerificationController::class, 'store'])
    ->middleware(['auth:web', 'throttle:6,1'])
    ->name('verification.verify-otp');
Route::post('/email/verify/resend-guest', [GuestVerificationResendController::class, 'store'])
    ->middleware(['throttle:6,1', 'throttle:verification-resend'])
    ->name('verification.resend-guest');

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard/growth', [DashboardController::class, 'growth'])->name('dashboard.growth');
    Route::get('/dashboard/operations', [DashboardController::class, 'operations'])->name('dashboard.operations');

    // Global workspace search (topbar command palette)
    Route::get('/search', [SearchController::class, 'index'])->name('search');

    // Settings - all sections stored in one JSON column, saved per-section
    Route::get('/settings',       [SettingsController::class, 'index'])->name('settings.index');
    Route::put('/settings',       [SettingsController::class, 'update'])->name('settings.update');
    Route::post('/settings/logo', [SettingsController::class, 'uploadLogo'])->name('settings.upload-logo');

    // Media library - browse/reuse past uploads across every upload point
    Route::get('/media',           [MediaController::class, 'index'])->name('media.index');
    Route::post('/media',          [MediaController::class, 'store'])->name('media.store');
    Route::delete('/media/{media}', [MediaController::class, 'destroy'])->name('media.destroy');

    // Audience overview
    Route::get('/audience', [AudienceController::class, 'index'])->name('audience.overview');

    // Contact import / export - must be BEFORE resource to avoid {contact} wildcard conflict
    Route::get('contacts/import',  [ContactImportController::class, 'create'])->name('contacts.import');
    Route::post('contacts/import', [ContactImportController::class, 'store'])->name('contacts.import.store');
    Route::post('contacts/export', ContactExportController::class)->name('contacts.export');

    // Contacts Bulk Actions
    Route::post('contacts/bulk-delete',        [ContactController::class, 'bulkDestroy'])->name('contacts.bulk-destroy');
    Route::post('contacts/bulk-add-tags',      [ContactController::class, 'bulkAddTags'])->name('contacts.bulk-add-tags');
    Route::post('contacts/bulk-add-lists',     [ContactController::class, 'bulkAddLists'])->name('contacts.bulk-add-lists');
    Route::post('contacts/bulk-update-status', [ContactController::class, 'bulkUpdateStatus'])->name('contacts.bulk-update-status');

    // Contacts CRUD
    Route::resource('contacts', ContactController::class)->only(['index', 'store', 'show', 'update', 'destroy']);

    // Contact list/tag attach-detach
    Route::post('contacts/{contact}/lists/{list}',   [ContactController::class, 'attachList'])->name('contacts.lists.attach');
    Route::delete('contacts/{contact}/lists/{list}', [ContactController::class, 'detachList'])->name('contacts.lists.detach');
    Route::post('contacts/{contact}/tags/{tag}',     [ContactController::class, 'attachTag'])->name('contacts.tags.attach');
    Route::delete('contacts/{contact}/tags/{tag}',   [ContactController::class, 'detachTag'])->name('contacts.tags.detach');

    // Contact notes
    Route::post('contacts/{contact}/notes',          [ContactNoteController::class, 'store'])->name('contacts.notes.store');
    Route::delete('contacts/{contact}/notes/{note}', [ContactNoteController::class, 'destroy'])->name('contacts.notes.destroy');

    // Lists Bulk Actions
    Route::post('lists/bulk-delete', [ListController::class, 'bulkDestroy'])->name('lists.bulk-destroy');

    // Lists CRUD
    Route::resource('lists', ListController::class)->only(['index', 'store', 'update', 'destroy']);

    // Tags Bulk Actions
    Route::post('tags/bulk-delete', [TagController::class, 'bulkDestroy'])->name('tags.bulk-destroy');

    // Tags CRUD
    Route::resource('tags', TagController::class)->only(['index', 'store', 'update', 'destroy']);

    // Webhooks Bulk Actions
    Route::post('webhooks/bulk-delete',        [WebhookController::class, 'bulkDestroy'])->name('webhooks.bulk-destroy');
    Route::post('webhooks/bulk-toggle-status', [WebhookController::class, 'bulkToggleStatus'])->name('webhooks.bulk-toggle-status');

    // Webhooks - inbound contact-creation endpoints for external forms/tools
    Route::resource('webhooks', WebhookController::class)->only(['index', 'store', 'update', 'destroy']);
    Route::redirect('/webhook', '/webhooks');
    Route::post('webhooks/{webhook}/regenerate-secret', [WebhookController::class, 'regenerateSecret'])->name('webhooks.regenerate-secret');
    Route::get('webhooks/{webhook}/logs',               [WebhookController::class, 'logs'])->name('webhooks.logs');

    // Forms Bulk Actions
    Route::post('forms/bulk-delete',        [FormController::class, 'bulkDestroy'])->name('forms.bulk-destroy');
    Route::post('forms/bulk-toggle-status', [FormController::class, 'bulkToggleStatus'])->name('forms.bulk-toggle-status');

    // Forms - embeddable inline/popup lead capture forms
    Route::get('forms/create',            [FormController::class, 'create'])->name('forms.create');
    Route::post('forms/{form}/duplicate', [FormController::class, 'duplicate'])->name('forms.duplicate');
    Route::get('forms/{form}/embed',      [FormController::class, 'embed'])->name('forms.embed');
    Route::get('forms/{form}',            [FormController::class, 'show'])->name('forms.show');
    Route::resource('forms', FormController::class)->only(['index', 'store', 'edit', 'update', 'destroy']);

    // SMTP Configuration - test-connection BEFORE {smtpConfig} routes to avoid wildcard match
    Route::get('sending/smtp',                       [SmtpConfigController::class, 'index'])->name('smtp.index');
    Route::post('sending/smtp',                      [SmtpConfigController::class, 'store'])->name('smtp.store');
    Route::post('sending/smtp/test-connection',      [SmtpConfigController::class, 'testConnection'])->name('smtp.test');
    Route::put('sending/smtp/{smtpConfig}',          [SmtpConfigController::class, 'update'])->name('smtp.update');
    Route::delete('sending/smtp/{smtpConfig}',       [SmtpConfigController::class, 'destroy'])->name('smtp.destroy');
    Route::post('sending/smtp/{smtpConfig}/default', [SmtpConfigController::class, 'setDefault'])->name('smtp.default');

    // Gmail / Google Workspace OAuth2 handshake (popup window flow)
    Route::post('sending/smtp/google/oauth/start',   [GoogleOAuthController::class, 'start'])->name('smtp.google.start');
    Route::get('sending/smtp/google/oauth/callback', [GoogleOAuthController::class, 'callback'])->name('smtp.google.callback');

    // Outlook / Office365 OAuth2 handshake (popup window flow)
    Route::post('sending/smtp/microsoft/oauth/start',   [MicrosoftOAuthController::class, 'start'])->name('smtp.microsoft.start');
    Route::get('sending/smtp/microsoft/oauth/callback', [MicrosoftOAuthController::class, 'callback'])->name('smtp.microsoft.callback');

    // Campaigns
    Route::get('/campaigns',                          [CampaignController::class, 'index'])->name('campaigns.index');
    Route::post('/campaigns',                         [CampaignController::class, 'store'])->name('campaigns.store');
    Route::post('/campaigns/upload-image',            [CampaignController::class, 'uploadImage'])->name('campaigns.upload-image');
    Route::post('/campaigns/upload-video',            [CampaignController::class, 'uploadVideo'])->name('campaigns.upload-video');
    Route::post('/campaigns/count-recipients',        [CampaignController::class, 'countRecipients'])->name('campaigns.count-recipients');
    Route::post('/campaigns/bulk-delete',             [CampaignController::class, 'bulkDestroy'])->name('campaigns.bulk-destroy');
    Route::post('/campaigns/{campaign}/send-test',    [CampaignController::class, 'sendTest'])->name('campaigns.send-test');
    Route::post('/campaigns/{campaign}/broadcast',    [CampaignController::class, 'broadcast'])->name('campaigns.broadcast');
    Route::post('/campaigns/{campaign}/duplicate',    [CampaignController::class, 'duplicate'])->name('campaigns.duplicate');
    Route::get('/campaigns/{campaign}/edit',          [CampaignController::class, 'edit'])->name('campaigns.edit');
    Route::get('/campaigns/{campaign}/preview',       [CampaignController::class, 'preview'])->name('campaigns.preview');
    Route::get('/campaigns/{campaign}',               [CampaignController::class, 'show'])->name('campaigns.show');
    Route::patch('/campaigns/{campaign}',             [CampaignController::class, 'update'])->name('campaigns.update');
    Route::delete('/campaigns/{campaign}',            [CampaignController::class, 'destroy'])->name('campaigns.destroy');

    // Recurring Email
    Route::get('/recurring-email',                              [RecurringCampaignController::class, 'index'])->name('recurring.index');
    Route::post('/recurring-email',                             [RecurringCampaignController::class, 'store'])->name('recurring.store');
    Route::post('/recurring-email/count-recipients',            [RecurringCampaignController::class, 'countRecipients'])->name('recurring.count-recipients');
    Route::post('/recurring-email/bulk-delete',                 [RecurringCampaignController::class, 'bulkDestroy'])->name('recurring.bulk-destroy');
    Route::post('/recurring-email/{campaign}/send-test',        [RecurringCampaignController::class, 'sendTest'])->name('recurring.send-test');
    Route::patch('/recurring-email/{campaign}/status',          [RecurringCampaignController::class, 'updateStatus'])->name('recurring.update-status');
    Route::get('/recurring-email/{campaign}/email-history/{occurrence}', [RecurringCampaignController::class, 'showOccurrence'])->name('recurring.occurrence.show');
    Route::get('/recurring-email/{campaign}/edit',              [RecurringCampaignController::class, 'edit'])->name('recurring.edit');
    Route::patch('/recurring-email/{campaign}',                 [RecurringCampaignController::class, 'update'])->name('recurring.update');
    Route::delete('/recurring-email/{campaign}',                [RecurringCampaignController::class, 'destroy'])->name('recurring.destroy');

    // Sequences
    Route::get('/sequences',                          [SequenceController::class, 'index'])->name('sequences.index');
    Route::post('/sequences',                         [SequenceController::class, 'store'])->name('sequences.store');
    Route::post('/sequences/bulk-delete',             [SequenceController::class, 'bulkDestroy'])->name('sequences.bulk-destroy');
    Route::get('/sequences/{sequence}/edit',          [SequenceController::class, 'edit'])->name('sequences.edit');
    Route::get('/sequences/{sequence}/report',        [SequenceController::class, 'show'])->name('sequences.show');
    Route::put('/sequences/{sequence}',               [SequenceController::class, 'update'])->name('sequences.update');
    Route::post('/sequences/{sequence}/start',         [SequenceController::class, 'start'])->name('sequences.start');
    Route::post('/sequences/{sequence}/duplicate',     [SequenceController::class, 'duplicate'])->name('sequences.duplicate');
    Route::post('/sequences/{sequence}/send-test',     [SequenceController::class, 'sendTest'])->name('sequences.send-test');
    Route::post('/sequences/{sequence}/preview-step',  [SequenceController::class, 'previewStep'])->name('sequences.preview-step');
    Route::post('/sequences/{sequence}/enroll-all',    [SequenceController::class, 'enrollAll'])->name('sequences.enroll-all');
    Route::post('/sequences/{sequence}/reset',         [SequenceController::class, 'resetSequence'])->name('sequences.reset');
    Route::delete('/sequences/{sequence}',            [SequenceController::class, 'destroy'])->name('sequences.destroy');

    // Email Templates
    Route::get('/templates',                          [TemplateController::class, 'index'])->name('templates.index');
    Route::get('/templates/create',                   [TemplateController::class, 'create'])->name('templates.create');
    Route::post('/templates',                         [TemplateController::class, 'store'])->name('templates.store');
    Route::post('/templates/bulk-delete',             [TemplateController::class, 'bulkDestroy'])->name('templates.bulk-destroy');
    Route::post('/templates/import',                  [TemplateController::class, 'import'])->name('templates.import');
    Route::post('/templates/send-test',               [TemplateController::class, 'sendTest'])->name('templates.send-test');
    Route::get('/api/templates',                      [TemplateController::class, 'apiIndex'])->name('templates.api');
    Route::get('/templates/{template}/edit',          [TemplateController::class, 'edit'])->name('templates.edit');
    Route::put('/templates/{template}',               [TemplateController::class, 'update'])->name('templates.update');
    Route::post('/templates/{template}/duplicate',    [TemplateController::class, 'duplicate'])->name('templates.duplicate');
    Route::delete('/templates/{template}',            [TemplateController::class, 'destroy'])->name('templates.destroy');

    // Automation
    Route::get('/automation',                            [AutomationController::class, 'index'])->name('automation.index');
    Route::post('/automation',                           [AutomationController::class, 'store'])->name('automation.store');
    Route::post('/automation/bulk-delete',               [AutomationController::class, 'bulkDestroy'])->name('automation.bulk-destroy');
    Route::post('/automation/test-webhook',              [AutomationController::class, 'testWebhook'])->name('automation.test-webhook');
    Route::get('/automation/{automation}/edit',          [AutomationController::class, 'edit'])->name('automation.edit');
    Route::put('/automation/{automation}',               [AutomationController::class, 'update'])->name('automation.update');
    Route::delete('/automation/{automation}',            [AutomationController::class, 'destroy'])->name('automation.destroy');
    Route::post('/automation/{automation}/run',          [AutomationController::class, 'run'])->name('automation.run');
    Route::post('/automation/{automation}/restart',      [AutomationController::class, 'restart'])->name('automation.restart');
    Route::get('/automation/{automation}/report',        [AutomationController::class, 'report'])->name('automation.report');
    Route::get('/automation/{automation}/contacts/{contact}/journey', [AutomationController::class, 'contactJourney'])->name('automation.contact-journey');

    // Notifications
    Route::get('/notifications',                         [NotificationController::class, 'index'])->name('notifications.index');
    Route::post('/notifications/{id}/read',              [NotificationController::class, 'markAsRead'])->name('notifications.read');
    Route::post('/notifications/read-all',               [NotificationController::class, 'markAllAsRead'])->name('notifications.read-all');
    Route::delete('/notifications/clear',                [NotificationController::class, 'clear'])->name('notifications.clear');
});
