<?php

use App\Http\Controllers\Admin\AgendaController;
use App\Http\Controllers\Admin\AuditoriaController;
use App\Http\Controllers\Admin\CalendarioController;
use App\Http\Controllers\Admin\CalculadoraConfigController;
use App\Http\Controllers\Admin\ComunicadoController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\DocumentoController as AdminDocumentoController;
use App\Http\Controllers\Admin\FinanceiroController;
use App\Http\Controllers\Admin\ObrigacaoController;
use App\Http\Controllers\Admin\OnboardingController;
use App\Http\Controllers\Admin\PostController;
use App\Http\Controllers\Admin\PropostaController;
use App\Http\Controllers\Admin\RelatorioController;
use App\Http\Controllers\Admin\SettingsController;
use App\Http\Controllers\Admin\ClienteController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Cliente\ComunicadoController as ClienteComunicadoController;
use App\Http\Controllers\Cliente\DocumentoController as ClienteDocumentoController;
use App\Http\Controllers\Cliente\FinanceiroController as ClienteFinanceiroController;
use App\Http\Controllers\Cliente\MensagemController;
use App\Http\Controllers\Cliente\OnboardingController as ClienteOnboardingController;
use App\Http\Controllers\Cliente\DashboardController as ClienteDashboardController;
use App\Http\Controllers\AssinaturaController;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\ContratoController;
use App\Http\Controllers\KanbanController;
use App\Http\Controllers\LeadController;
use App\Http\Controllers\NotificacaoController;
use App\Http\Controllers\PageController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\SitemapController;
use App\Http\Controllers\UploadController;
use Illuminate\Support\Facades\Route;

// ── Public pages ─────────────────────────────────────────────────────────────
Route::get('/',            [PageController::class, 'home'])->name('home');
Route::get('/sobre',       [PageController::class, 'sobre'])->name('sobre');
Route::get('/servicos',    [PageController::class, 'servicos'])->name('servicos');
Route::get('/blog',        [PageController::class, 'blog'])->name('blog');
Route::get('/blog/{post:slug}', [PageController::class, 'blogPost'])->name('blog.show');
Route::get('/contato',     [PageController::class, 'contato'])->name('contato');
Route::get('/privacidade', [PageController::class, 'privacidade'])->name('privacidade');
Route::get('/termos',      [PageController::class, 'termos'])->name('termos');
// /calculadora was public — removed (calculator is now internal only)

// ── Contact form ──────────────────────────────────────────────────────────────
Route::post('/contato', [ContactController::class, 'send'])->name('contato.send');

// ── Aceite digital de proposta (público) ──────────────────────────────────────
Route::get('/proposta/{token}/aceitar', [PropostaController::class, 'aceitar'])->name('proposta.aceitar');

// ── E-assinatura de contrato (público — acesso via token) ─────────────────────
Route::get('/assinar/{token}',            [AssinaturaController::class, 'show'])->name('assinar');
Route::post('/assinar/{token}',           [AssinaturaController::class, 'store'])->name('assinar.store');
Route::get('/assinar/{token}/confirmado', [AssinaturaController::class, 'confirmado'])->name('assinar.confirmado');

// ── Simulador público (captura perfil sem mostrar preços) ─────────────────────
Route::get('/simulador',  [LeadController::class, 'simulador'])->name('simulador');
Route::post('/simulador', [LeadController::class, 'storeSimulador'])->name('simulador.store');

// ── Sitemap ───────────────────────────────────────────────────────────────────
Route::get('/sitemap.xml', [SitemapController::class, 'index'])->name('sitemap');

// ── Leads / CRM (requires auth + permission) ─────────────────────────────────
Route::middleware(['auth', 'permission:acessar_leads'])->prefix('leads')->name('leads.')->group(function () {
    Route::get('/',                  [LeadController::class, 'index'])->name('index');
    Route::patch('/{lead}/status',   [LeadController::class, 'updateStatus'])->name('updateStatus');
    Route::post('/{lead}/proposta',  [LeadController::class, 'criarProposta'])->name('proposta');
    Route::delete('/{lead}',         [LeadController::class, 'destroy'])->name('destroy');
});

// ── Kanban (requires auth + permission) ──────────────────────────────────────
Route::middleware(['auth', 'permission:acessar_kanban'])->prefix('kanban')->name('kanban.')->group(function () {
    Route::get('/',                                    [KanbanController::class, 'index'])->name('index');
    Route::post('/demandas',                           [KanbanController::class, 'store'])->name('store');
    Route::get('/demandas/{demanda}',                  [KanbanController::class, 'show'])->name('show');
    Route::patch('/demandas/{demanda}',                [KanbanController::class, 'update'])->name('update');
    Route::patch('/demandas/{demanda}/status',         [KanbanController::class, 'updateStatus'])->name('updateStatus');
    Route::delete('/demandas/{demanda}',               [KanbanController::class, 'destroy'])->name('destroy');
    Route::post('/demandas/{demanda}/uploads',         [UploadController::class, 'storeDemanda'])->name('demanda.uploads.store');
});

// ── Contratos (requires auth + permission) ────────────────────────────────────
Route::middleware(['auth', 'permission:acessar_contratos'])->prefix('contratos')->name('contratos.')->group(function () {
    Route::get('/',                        [ContratoController::class, 'index'])->name('index');
    Route::get('/novo',                    [ContratoController::class, 'create'])->name('create');
    Route::post('/',                       [ContratoController::class, 'store'])->name('store');
    Route::get('/{contrato}',              [ContratoController::class, 'show'])->name('show');
    Route::patch('/{contrato}/status',     [ContratoController::class, 'updateStatus'])->name('updateStatus');
    Route::post('/{contrato}/gerar',       [ContratoController::class, 'gerarConteudo'])->name('gerar');
    Route::get('/{contrato}/pdf',          [ContratoController::class, 'pdf'])->name('pdf');
    Route::delete('/{contrato}',           [ContratoController::class, 'destroy'])->name('destroy');
    Route::post('/{contrato}/uploads',            [UploadController::class, 'storeContrato'])->name('uploads.store');
    Route::post('/{contrato}/solicitar-assinatura', [ContratoController::class, 'solicitarAssinatura'])->name('solicitar-assinatura');
});

// ── Dashboard interno (auth, todos) ──────────────────────────────────────────
Route::middleware('auth')->get('/admin/dashboard', [DashboardController::class, 'index'])->name('admin.dashboard');

// ── Admin panel (admin role only) ────────────────────────────────────────────
Route::middleware(['auth', 'role:admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/usuarios',           [UserController::class, 'index'])->name('usuarios');
    Route::post('/usuarios',          [UserController::class, 'store'])->name('usuarios.store');
    Route::patch('/usuarios/{user}',  [UserController::class, 'update'])->name('usuarios.update');
    Route::delete('/usuarios/{user}', [UserController::class, 'destroy'])->name('usuarios.destroy');

    Route::get('/clientes',                                     [ClienteController::class, 'index'])->name('clientes');
    Route::post('/clientes/{contrato}/acesso',                  [ClienteController::class, 'storeAcesso'])->name('clientes.acesso.store');
    Route::patch('/clientes/{contrato}/acesso',                 [ClienteController::class, 'updateAcesso'])->name('clientes.acesso.update');
    Route::delete('/clientes/{contrato}/acesso',                [ClienteController::class, 'revogarAcesso'])->name('clientes.acesso.revogar');
    Route::patch('/clientes/{contrato}/acesso/toggle',          [ClienteController::class, 'toggleAcesso'])->name('clientes.acesso.toggle');

    Route::get('/configuracoes',   [SettingsController::class, 'index'])->name('settings');
    Route::patch('/configuracoes', [SettingsController::class, 'update'])->name('settings.update');

    Route::get('/calculadora',              [CalculadoraConfigController::class, 'tool'])->name('calculadora');
    Route::get('/calculadora/configurar',   [CalculadoraConfigController::class, 'index'])->name('calculadora.config');
    Route::patch('/calculadora/configurar', [CalculadoraConfigController::class, 'update'])->name('calculadora.config.update');

    // Blog CMS
    Route::get('/blog',                          [PostController::class, 'index'])->name('blog.index');
    Route::get('/blog/novo',                     [PostController::class, 'create'])->name('blog.create');
    Route::post('/blog',                         [PostController::class, 'store'])->name('blog.store');
    Route::get('/blog/{post}/editar',            [PostController::class, 'edit'])->name('blog.edit');
    Route::patch('/blog/{post}',                 [PostController::class, 'update'])->name('blog.update');
    Route::delete('/blog/{post}',                [PostController::class, 'destroy'])->name('blog.destroy');
    Route::patch('/blog/{post}/toggle-publish',  [PostController::class, 'togglePublish'])->name('blog.toggle');

    // Relatórios
    Route::get('/relatorios',              [RelatorioController::class, 'index'])->name('relatorios');
    Route::get('/relatorios/leads',        [RelatorioController::class, 'leadsExport'])->name('relatorios.leads');
    Route::get('/relatorios/demandas',     [RelatorioController::class, 'demandasExport'])->name('relatorios.demandas');
    Route::get('/relatorios/contratos',    [RelatorioController::class, 'contratosExport'])->name('relatorios.contratos');
    Route::get('/relatorios/financeiro',   [RelatorioController::class, 'financeiroExport'])->name('relatorios.financeiro');
    Route::get('/relatorios/obrigacoes',   [RelatorioController::class, 'obrigacoesExport'])->name('relatorios.obrigacoes');

    // Obrigações Acessórias
    Route::get('/obrigacoes',                           [ObrigacaoController::class, 'index'])->name('obrigacoes.index');
    Route::post('/obrigacoes',                          [ObrigacaoController::class, 'store'])->name('obrigacoes.store');
    Route::post('/obrigacoes/gerar',                    [ObrigacaoController::class, 'gerarMes'])->name('obrigacoes.gerar');
    Route::patch('/obrigacoes/{obrigacao}/entregar',    [ObrigacaoController::class, 'marcarEntregue'])->name('obrigacoes.entregar');
    Route::delete('/obrigacoes/{obrigacao}',            [ObrigacaoController::class, 'destroy'])->name('obrigacoes.destroy');

    // Propostas Comerciais
    Route::get('/propostas',                  [PropostaController::class, 'index'])->name('propostas.index');
    Route::post('/propostas',                 [PropostaController::class, 'store'])->name('propostas.store');
    Route::post('/propostas/{proposta}/enviar',   [PropostaController::class, 'enviar'])->name('propostas.enviar');
    Route::get('/propostas/{proposta}/pdf',       [PropostaController::class, 'pdf'])->name('propostas.pdf');
    Route::post('/propostas/{proposta}/contrato', [PropostaController::class, 'converterContrato'])->name('propostas.contrato');
    Route::delete('/propostas/{proposta}',        [PropostaController::class, 'destroy'])->name('propostas.destroy');

    // Agenda
    Route::get('/agenda',              [AgendaController::class, 'index'])->name('agenda');
    Route::post('/agenda',             [AgendaController::class, 'store'])->name('agenda.store');
    Route::get('/agenda/{tarefa}',     [AgendaController::class, 'show'])->name('agenda.show');
    Route::put('/agenda/{tarefa}',     [AgendaController::class, 'update'])->name('agenda.update');
    Route::patch('/agenda/{tarefa}/toggle', [AgendaController::class, 'toggle'])->name('agenda.toggle');
    Route::delete('/agenda/{tarefa}',  [AgendaController::class, 'destroy'])->name('agenda.destroy');

    // Auditoria
    Route::get('/auditoria', [AuditoriaController::class, 'index'])->name('auditoria');

    // Calendário Fiscal
    Route::get('/calendario', [CalendarioController::class, 'index'])->name('calendario');

    // Onboarding
    Route::get('/onboarding',                          [OnboardingController::class, 'index'])->name('onboarding');
    Route::post('/onboarding',                         [OnboardingController::class, 'store'])->name('onboarding.store');
    Route::patch('/onboarding/{item}',                 [OnboardingController::class, 'update'])->name('onboarding.update');
    Route::patch('/onboarding/{item}/toggle',          [OnboardingController::class, 'toggle'])->name('onboarding.toggle');
    Route::delete('/onboarding/{item}',                [OnboardingController::class, 'destroy'])->name('onboarding.destroy');

    // Comunicados
    Route::get('/comunicados',                         [ComunicadoController::class, 'index'])->name('comunicados.index');
    Route::post('/comunicados',                        [ComunicadoController::class, 'store'])->name('comunicados.store');
    Route::patch('/comunicados/{comunicado}/publicar', [ComunicadoController::class, 'publicar'])->name('comunicados.publicar');
    Route::delete('/comunicados/{comunicado}',         [ComunicadoController::class, 'destroy'])->name('comunicados.destroy');

    // Financeiro
    Route::get('/financeiro',                    [FinanceiroController::class, 'index'])->name('financeiro.index');
    Route::post('/financeiro',                   [FinanceiroController::class, 'store'])->name('financeiro.store');
    Route::post('/financeiro/gerar',             [FinanceiroController::class, 'gerarMes'])->name('financeiro.gerar');
    Route::patch('/financeiro/{cobranca}/pago',  [FinanceiroController::class, 'marcarPago'])->name('financeiro.pago');
    Route::delete('/financeiro/{cobranca}',      [FinanceiroController::class, 'destroy'])->name('financeiro.destroy');

    // Documentos (admin)
    Route::get('/documentos',                          [AdminDocumentoController::class, 'index'])->name('documentos.index');
    Route::post('/documentos',                         [AdminDocumentoController::class, 'store'])->name('documentos.store');
    Route::patch('/documentos/{documento}/visivel',    [AdminDocumentoController::class, 'toggleVisivel'])->name('documentos.visivel');
    Route::get('/documentos/{documento}/download',     [AdminDocumentoController::class, 'download'])->name('documentos.download');
    Route::delete('/documentos/{documento}',           [AdminDocumentoController::class, 'destroy'])->name('documentos.destroy');
});

// ── Portal do cliente ─────────────────────────────────────────────────────────
Route::middleware(['auth', 'role:cliente'])->prefix('cliente')->name('cliente.')->group(function () {
    Route::get('/dashboard', [ClienteDashboardController::class, 'index'])->name('dashboard');
    Route::get('/mensagens', [MensagemController::class, 'index'])->name('mensagens');
    Route::post('/mensagens', [MensagemController::class, 'store'])->name('mensagens.store');
    Route::get('/documentos', [ClienteDocumentoController::class, 'index'])->name('documentos');
    Route::get('/documentos/{documento}/download', [ClienteDocumentoController::class, 'download'])->name('documentos.download');
    Route::get('/financeiro', [ClienteFinanceiroController::class, 'index'])->name('financeiro');
    Route::get('/comunicados', [ClienteComunicadoController::class, 'index'])->name('comunicados');
    Route::patch('/comunicados/{comunicado}/ler', [ClienteComunicadoController::class, 'ler'])->name('comunicados.ler');
    Route::get('/onboarding', [ClienteOnboardingController::class, 'index'])->name('onboarding');
    Route::patch('/onboarding/{item}/toggle', [ClienteOnboardingController::class, 'toggle'])->name('onboarding.toggle');
});

// ── Dashboard — redireciona por role ─────────────────────────────────────────
Route::get('/dashboard', function () {
    $user = auth()->user();
    if ($user->hasRole('cliente'))              return redirect()->route('cliente.dashboard');
    if ($user->can('acessar_kanban'))           return redirect()->route('kanban.index');
    if ($user->can('acessar_leads'))            return redirect()->route('leads.index');
    if ($user->can('acessar_contratos'))        return redirect()->route('contratos.index');
    return redirect()->route('admin.dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

// ── Uploads globais (download + delete) ─────────────────────────────────────
Route::middleware('auth')->group(function () {
    Route::get('/uploads/{upload}/download', [UploadController::class, 'download'])->name('uploads.download');
    Route::delete('/uploads/{upload}',       [UploadController::class, 'destroy'])->name('uploads.destroy');
});

// ── Notificações in-app ──────────────────────────────────────────────────────
Route::middleware('auth')->prefix('notificacoes')->name('notificacoes.')->group(function () {
    Route::get('/',                              [NotificacaoController::class, 'index'])->name('index');
    Route::patch('/ler-todas',                   [NotificacaoController::class, 'markAllRead'])->name('markAllRead');
    Route::patch('/{notificacao}/ler',           [NotificacaoController::class, 'markRead'])->name('markRead');
});

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

require __DIR__.'/auth.php';
