<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Middleware\PreventAccessFromCentralDomains;

use App\Http\Controllers\SuperAdmin\AdminController;
use App\Http\Controllers\Admin\ClientController;
use App\Http\Controllers\Admin\CaseController;
use App\Http\Controllers\Admin\DocumentController;
use App\Http\Controllers\Admin\CaseNoteController;
use App\Http\Controllers\Admin\RoleController;
use App\Http\Controllers\Admin\CalendarController;
use App\Http\Controllers\Admin\InvoiceController;
use App\Http\Controllers\Admin\WitnessController;
use App\Http\Controllers\SuperAdmin\SettingController;
use App\Http\Controllers\SuperAdmin\DashboardController;
use App\Http\Controllers\Admin\AiController;
use App\Http\Controllers\Admin\RecordingController;
use App\Http\Controllers\Admin\EvidenceController;
use App\Http\Controllers\Admin\AppointmentController;
use App\Http\Controllers\Admin\FinanceController;
use App\Http\Controllers\Admin\DictationController;
use App\Http\Controllers\Client\AiChatController;
use App\Http\Controllers\Tenant\ImpersonationController;

/*
|--------------------------------------------------------------------------
| Tenant Routes
|--------------------------------------------------------------------------
*/


Route::middleware([
    'web',
    InitializeTenancyByDomain::class,
    PreventAccessFromCentralDomains::class,
    \App\Http\Middleware\CheckTenantStatus::class,
])->group(function () {

Route::get('/', function () {
        return redirect()->route('login');
    });

require __DIR__.'/auth.php';


    // Route::get('/dashboard', function () {
    //     return 'Tenant Dashboard Works!';
    // })->name('dashboard');

    // 2. Authenticated Tenant Routes
    Route::middleware(['auth'])->group(function () {

        Route::post('/exit-impersonation', [ImpersonationController::class, 'exit']);
        // --- DASHBOARD SWITCHER (The route causing your error) ---
        Route::get('/dashboard', function () {
            // Determine where to send the user based on role
            if (auth()->user()->hasRole('super_admin') || auth()->user()->hasRole('lawyer')) {
                return redirect()->route('admin.dashboard');
            }
            return redirect()->route('admin.dashboard');
        })->name('dashboard');
        Route::get('admin-dashboard', [AdminController::class, 'index'])->name('admin.dashboard');

        // --- CLIENT / USER AREA ---
        // Route::get('user/dashboard', [AdminController::class, 'userDashboard'])->name('user.dashboard');

        Route::prefix('portal')->group(function () {
            Route::get('/assistant', [AiChatController::class, 'index'])->name('client.chat.index');
            Route::post('/assistant/send', [AiChatController::class, 'sendMessage'])->name('client.chat.send');
        });

        // --- ADMIN / LAWYER AREA ---
        Route::middleware(['role:super_admin|lawyer'])->prefix('admin')->name('admin.')->group(function () {

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

            // Executive Dashboard (Super Admin Only)
            Route::get('/executive/dashboard', [DashboardController::class, 'index'])
                ->middleware('role:super_admin')
                ->name('superadmin.dashboard');

            // Core Resources
            Route::resource('clients', ClientController::class);
            Route::resource('cases', CaseController::class);
            Route::resource('roles', RoleController::class);
            Route::resource('appointments', AppointmentController::class)->except(['create', 'show', 'edit']);

            // Documents
            Route::get('/documents', [DocumentController::class, 'index'])->name('documents.index');
            Route::post('cases/{case}/documents', [DocumentController::class, 'store'])->name('documents.store');
            Route::get('documents/{document}/preview', [DocumentController::class, 'preview'])->name('documents.preview');
            Route::get('documents/{document}/download', [DocumentController::class, 'download'])->name('documents.download');

            // Case Features
            Route::post('cases/{case}/notes', [CaseNoteController::class, 'store'])->name('cases.notes.store');
            Route::post('/cases/{case}/analyze', [AiController::class, 'generateAnalysis'])->name('cases.analyze');
            Route::post('/dictate', [DictationController::class, 'transcribe'])->name('dictate');

            // Evidence & Witnesses
            Route::post('cases/{case}/witnesses', [WitnessController::class, 'store'])->name('witnesses.store');
            Route::delete('witnesses/{witness}', [WitnessController::class, 'destroy'])->name('witnesses.destroy');
            Route::post('/cases/{case}/evidence', [EvidenceController::class, 'store'])->name('evidence.store');
            Route::delete('/evidence/{evidence}', [EvidenceController::class, 'destroy'])->name('evidence.destroy');
            Route::post('/cases/{case}/recordings', [RecordingController::class, 'store'])->name('recordings.store');
            Route::delete('/recordings/{recording}', [RecordingController::class, 'destroy'])->name('recordings.destroy');

            // Finance & Invoicing
            Route::get('/finance', [FinanceController::class, 'index'])->name('finance.index');
            Route::post('/finance/payment', [FinanceController::class, 'storePayment'])->name('finance.payment.store');
            Route::post('/finance/credit-note', [FinanceController::class, 'storeCreditNote'])->name('finance.credit.store');
            Route::post('/finance/invoice', [FinanceController::class, 'quickInvoice'])->name('finance.invoice.store');
            Route::put('/finance/invoice/{id}', [FinanceController::class, 'updateInvoice'])->name('finance.invoice.update');
            Route::put('/finance/payment/{id}', [FinanceController::class, 'updateExpense'])->name('finance.payment.update');

            // Accounts / Ledger
            Route::get('/accounts', [FinanceController::class, 'accounts'])->name('accounts');
            Route::post('/accounts', [FinanceController::class, 'storeAccount'])->name('accounts.store');
            Route::put('/accounts/{id}', [FinanceController::class, 'updateAccount'])->name('accounts.update');
            Route::delete('/accounts/{id}', [FinanceController::class, 'destroyAccount'])->name('accounts.destroy');
            Route::get('/accounts/ledger', [FinanceController::class, 'listAll'])->name('accounts.ledger');

            // Invoice Management
            Route::get('cases/{case}/invoices/create', [InvoiceController::class, 'create'])->name('invoices.create');
            Route::post('cases/{case}/invoices', [InvoiceController::class, 'store'])->name('invoices.store');
            Route::get('invoices/{id}/download', [InvoiceController::class, 'download'])->name('invoices.download');
            Route::get('invoices/{invoice}/edit', [InvoiceController::class, 'edit'])->name('invoices.edit');
            Route::put('invoices/{invoice}', [InvoiceController::class, 'update'])->name('invoices.update');
            Route::post('invoices/{invoice}/send', [InvoiceController::class, 'sendEmail'])->name('invoices.send');
            Route::post('/invoices/{invoice}/approve', [InvoiceController::class, 'approve'])->name('invoices.approve');
            Route::post('/invoices/{invoice}/reject', [InvoiceController::class, 'reject'])->name('invoices.reject');

            // Calendar
            Route::get('/calendar', function () {
                return view('admin.calendar.index');
            })->name('calendar.index');
            Route::get('/calendar/events', [CalendarController::class, 'index'])->name('calendar.events');

            // Settings
            Route::get('/settings', [SettingController::class, 'index'])->name('settings.index');
            Route::post('/settings', [SettingController::class, 'update'])->name('settings.update');
            Route::post('/roles/{role}/users', [RoleController::class, 'assignUser'])->name('roles.assign');
            Route::delete('/roles/{role}/users/{userId}', [RoleController::class, 'removeUser'])->name('roles.remove');
        });
    });
});
