<?php

use App\Http\Controllers\AccountBookingController;
use App\Http\Controllers\AccountInstallmentController;
use App\Http\Controllers\AccountPaymentController;
use App\Http\Controllers\ActivityNotificationController;
use App\Http\Controllers\ArchiveSettingController;
use App\Http\Controllers\CaseObjectController;
use App\Http\Controllers\ClientCaseContoller;
use App\Http\Controllers\ClientController;
use App\Http\Controllers\ContractConfigController;
use App\Http\Controllers\ContractSettingController;
use App\Http\Controllers\FieldJobController;
use App\Http\Controllers\FieldJobSettingController;
use App\Http\Controllers\ImportController;
use App\Http\Controllers\ImportTemplateController;
use App\Http\Controllers\InstallmentSettingController;
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\PaymentSettingController;
use App\Http\Controllers\PersonController;
use App\Http\Controllers\PhoneViewController;
use App\Http\Controllers\SegmentController;
use App\Http\Controllers\SettingController;
use App\Http\Controllers\WorkflowController;
use App\Models\Person\Person;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

Route::redirect('/', 'login');

// SMS provider webhook (delivery reports and replies)
Route::match(['GET', 'POST'], 'webhooks/sms/smsapi-si', \App\Http\Controllers\SmsWebhookController::class)
    ->name('webhooks.sms.smsapi-si');

// Admin SMS endpoints (under manage-settings)
Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
    'permission:manage-settings',
])->prefix('admin')->name('admin.')->group(function () {
    Route::get('sms-profiles', [\App\Http\Controllers\Admin\SmsProfileController::class, 'index'])->name('sms-profiles.index');
    Route::post('sms-profiles', [\App\Http\Controllers\Admin\SmsProfileController::class, 'store'])->name('sms-profiles.store');
    Route::post('sms-profiles/{smsProfile}/test-send', [\App\Http\Controllers\Admin\SmsProfileController::class, 'testSend'])->name('sms-profiles.test-send');
    Route::post('sms-profiles/{smsProfile}/balance', [\App\Http\Controllers\Admin\SmsProfileController::class, 'balance'])->name('sms-profiles.balance');
    Route::post('sms-profiles/{smsProfile}/price', [\App\Http\Controllers\Admin\SmsProfileController::class, 'price'])->name('sms-profiles.price');

    // SMS senders management
    Route::get('sms-senders', [\App\Http\Controllers\Admin\SmsSenderController::class, 'index'])->name('sms-senders.index');
    Route::post('sms-senders', [\App\Http\Controllers\Admin\SmsSenderController::class, 'store'])->name('sms-senders.store');
    Route::put('sms-senders/{smsSender}', [\App\Http\Controllers\Admin\SmsSenderController::class, 'update'])->name('sms-senders.update');
    Route::post('sms-senders/{smsSender}/toggle', [\App\Http\Controllers\Admin\SmsSenderController::class, 'toggle'])->name('sms-senders.toggle');
    Route::delete('sms-senders/{smsSender}', [\App\Http\Controllers\Admin\SmsSenderController::class, 'destroy'])->name('sms-senders.destroy');

    // SMS templates management
    Route::get('sms-templates', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'index'])->name('sms-templates.index');
    Route::post('sms-templates', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'store'])->name('sms-templates.store');
    Route::put('sms-templates/{smsTemplate}', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'update'])->name('sms-templates.update');
    Route::post('sms-templates/{smsTemplate}/toggle', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'toggle'])->name('sms-templates.toggle');
    Route::delete('sms-templates/{smsTemplate}', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'destroy'])->name('sms-templates.destroy');
    Route::post('sms-templates/{smsTemplate}/send-test', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'sendTest'])->name('sms-templates.send-test');
});

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
])->group(function () {

    Route::get('/dashboard', \App\Http\Controllers\DashboardController::class)->name('dashboard');

    Route::get('testing', function () {
        return Inertia::render('Testing/Index', [
            'example' => 'Hello World',
        ]);
    })->name('testing.index');

    // Admin panel - user role management
    Route::middleware(['permission:manage-settings'])->prefix('admin')->name('admin.')->group(function () {
        // Admin dashboard
        Route::get('/', function () {
            return Inertia::render('Admin/Index');
        })->name('index');
        Route::get('users', [\App\Http\Controllers\Admin\UserRoleController::class, 'index'])->name('users.index');
        Route::post('users', [\App\Http\Controllers\Admin\UserRoleController::class, 'store'])->name('users.store');
        Route::put('users/{user}', [\App\Http\Controllers\Admin\UserRoleController::class, 'update'])->name('users.update');
        Route::patch('users/{user}/toggle-active', [\App\Http\Controllers\Admin\UserRoleController::class, 'toggleActive'])->name('users.toggle-active');
        Route::patch('users/{user}/settings', [\App\Http\Controllers\Admin\UserRoleController::class, 'updateSettings'])->name('users.settings');

        // Permissions management
        Route::get('permissions', [\App\Http\Controllers\Admin\PermissionController::class, 'index'])->name('permissions.index');
        Route::get('permissions/create', [\App\Http\Controllers\Admin\PermissionController::class, 'create'])->name('permissions.create');
        Route::post('permissions', [\App\Http\Controllers\Admin\PermissionController::class, 'store'])->name('permissions.store');
        Route::get('permissions/{permission}/edit', [\App\Http\Controllers\Admin\PermissionController::class, 'edit'])->name('permissions.edit');
        Route::put('permissions/{permission}', [\App\Http\Controllers\Admin\PermissionController::class, 'update'])->name('permissions.update');

        // Document templates & global document settings
        Route::get('document-templates', [\App\Http\Controllers\Admin\DocumentTemplateController::class, 'index'])->name('document-templates.index');
        Route::post('document-templates', [\App\Http\Controllers\Admin\DocumentTemplateController::class, 'store'])->name('document-templates.store');
        Route::post('document-templates/{template}/rescan', [\App\Http\Controllers\Admin\DocumentTemplateController::class, 'rescanTokens'])->name('document-templates.rescan');
        Route::post('document-templates/{template}/toggle', [\App\Http\Controllers\Admin\DocumentTemplateController::class, 'toggleActive'])->name('document-templates.toggle');
        Route::put('document-templates/{template}/settings', [\App\Http\Controllers\Admin\DocumentTemplateController::class, 'updateSettings'])->name('document-templates.settings.update');
        Route::get('document-templates/{template}', [\App\Http\Controllers\Admin\DocumentTemplateController::class, 'show'])->name('document-templates.show');
        Route::get('document-templates/{template}/edit', [\App\Http\Controllers\Admin\DocumentTemplateController::class, 'edit'])->name('document-templates.edit');
        Route::get('document-settings', [\App\Http\Controllers\Admin\DocumentSettingsController::class, 'edit'])->name('document-settings.index');
        Route::put('document-settings', [\App\Http\Controllers\Admin\DocumentSettingsController::class, 'update'])->name('document-settings.update');

        // Mail profiles (dynamic outgoing mail configuration)
        Route::get('mail-profiles', [\App\Http\Controllers\Admin\MailProfileController::class, 'index'])->name('mail-profiles.index');
        Route::get('mail-profiles.json', function () {
            return \App\Models\MailProfile::query()->get();
        })->name('mail-profiles.json');
        Route::post('mail-profiles', [\App\Http\Controllers\Admin\MailProfileController::class, 'store'])->name('mail-profiles.store');
        Route::put('mail-profiles/{mailProfile}', [\App\Http\Controllers\Admin\MailProfileController::class, 'update'])->name('mail-profiles.update');
        Route::post('mail-profiles/{mailProfile}/toggle', [\App\Http\Controllers\Admin\MailProfileController::class, 'toggle'])->name('mail-profiles.toggle');
        Route::post('mail-profiles/{mailProfile}/toggle-auto-mailer', [\App\Http\Controllers\Admin\MailProfileController::class, 'toggleAutoMailer'])->name('mail-profiles.toggle-auto-mailer');
        Route::post('mail-profiles/{mailProfile}/test', [\App\Http\Controllers\Admin\MailProfileController::class, 'test'])->name('mail-profiles.test');
        Route::post('mail-profiles/{mailProfile}/send-test', [\App\Http\Controllers\Admin\MailProfileController::class, 'sendTest'])->name('mail-profiles.send-test');
        Route::delete('mail-profiles/{mailProfile}', [\App\Http\Controllers\Admin\MailProfileController::class, 'destroy'])->name('mail-profiles.destroy');

        // Email templates
        Route::get('email-templates', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'index'])->name('email-templates.index');
        Route::get('email-templates/create', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'create'])->name('email-templates.create');
        Route::post('email-templates', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'store'])->name('email-templates.store');
        Route::get('email-templates/{emailTemplate}/edit', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'edit'])->name('email-templates.edit');
        Route::put('email-templates/{emailTemplate}', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'update'])->name('email-templates.update');
        Route::delete('email-templates/{emailTemplate}', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'destroy'])->name('email-templates.destroy');
        Route::post('email-templates/{emailTemplate}/preview', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'preview'])->name('email-templates.preview');
        Route::post('email-templates/{emailTemplate}/send-test', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'sendTest'])->name('email-templates.send-test');
        Route::post('email-templates/{emailTemplate}/render-final', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'renderFinalHtml'])->name('email-templates.render-final');
        Route::post('email-templates/upload-image', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'uploadImage'])->name('email-templates.upload-image');
        Route::post('email-templates/{emailTemplate}/replace-image', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'replaceImage'])->name('email-templates.replace-image');
        Route::delete('email-templates/{emailTemplate}/images/{document}', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'deleteImage'])->name('email-templates.images.delete');
        // Cascading selects data
        Route::get('email-templates-data/clients', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'clients'])->name('email-templates.data.clients');
        Route::get('email-templates-data/clients/{client}/cases', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'casesForClient'])->name('email-templates.data.cases');
        Route::get('email-templates-data/cases/{clientCase}/contracts', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'contractsForCase'])->name('email-templates.data.contracts');

        // Email logs
        Route::get('email-logs', [\App\Http\Controllers\Admin\EmailLogController::class, 'index'])->name('email-logs.index');
        Route::get('email-logs/{emailLog}', [\App\Http\Controllers\Admin\EmailLogController::class, 'show'])->name('email-logs.show');
        Route::get('email-logs/{emailLog}/body', [\App\Http\Controllers\Admin\EmailLogController::class, 'body'])->name('email-logs.body');

        // SMS senders
        Route::get('sms-senders', [\App\Http\Controllers\Admin\SmsSenderController::class, 'index'])->name('sms-senders.index');
        Route::post('sms-senders', [\App\Http\Controllers\Admin\SmsSenderController::class, 'store'])->name('sms-senders.store');
        Route::put('sms-senders/{smsSender}', [\App\Http\Controllers\Admin\SmsSenderController::class, 'update'])->name('sms-senders.update');
        Route::post('sms-senders/{smsSender}/toggle', [\App\Http\Controllers\Admin\SmsSenderController::class, 'toggle'])->name('sms-senders.toggle');
        Route::delete('sms-senders/{smsSender}', [\App\Http\Controllers\Admin\SmsSenderController::class, 'destroy'])->name('sms-senders.destroy');

        // SMS templates
        Route::get('sms-templates', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'index'])->name('sms-templates.index');
        Route::get('sms-templates/create', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'create'])->name('sms-templates.create');
        Route::post('sms-templates', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'store'])->name('sms-templates.store');
        Route::get('sms-templates/{smsTemplate}/edit', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'edit'])->name('sms-templates.edit');
        Route::put('sms-templates/{smsTemplate}', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'update'])->name('sms-templates.update');
        Route::post('sms-templates/{smsTemplate}/toggle', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'toggle'])->name('sms-templates.toggle');
        Route::delete('sms-templates/{smsTemplate}', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'destroy'])->name('sms-templates.destroy');
        Route::post('sms-templates/{smsTemplate}/send-test', [\App\Http\Controllers\Admin\SmsTemplateController::class, 'sendTest'])->name('sms-templates.send-test');

        // SMS logs
        Route::get('sms-logs', [\App\Http\Controllers\Admin\SmsLogController::class, 'index'])->name('sms-logs.index');
        Route::get('sms-logs/{smsLog}', [\App\Http\Controllers\Admin\SmsLogController::class, 'show'])->name('sms-logs.show');

    });

    // Packages — accessible to users with manage-settings permission
    Route::middleware(['permission:manage-settings'])->prefix('packages')->name('packages.')->group(function () {
        // Landing
        Route::get('/', [\App\Http\Controllers\Admin\PackageController::class, 'landing'])->name('index');

        // SMS packages
        Route::prefix('sms')->name('sms.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\PackageController::class, 'smsIndex'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\PackageController::class, 'smsCreate'])->name('create');
            Route::post('/', [\App\Http\Controllers\Admin\PackageController::class, 'store'])->name('store');
            Route::get('/contracts/list', [\App\Http\Controllers\Admin\PackageController::class, 'contracts'])->name('contracts');
            Route::post('/from-contracts', [\App\Http\Controllers\Admin\PackageController::class, 'storeFromContracts'])->name('store-from-contracts');
            Route::get('/{package}', [\App\Http\Controllers\Admin\PackageController::class, 'smsShow'])->name('show');
            Route::post('/{package}/dispatch', [\App\Http\Controllers\Admin\PackageController::class, 'dispatch'])->name('dispatch');
            Route::post('/{package}/cancel', [\App\Http\Controllers\Admin\PackageController::class, 'cancel'])->name('cancel');
            Route::delete('/{package}', [\App\Http\Controllers\Admin\PackageController::class, 'destroy'])->name('destroy');
        });

        // Email packages
        Route::prefix('email')->name('email.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Admin\PackageController::class, 'emailIndex'])->name('index');
            Route::get('/create', [\App\Http\Controllers\Admin\PackageController::class, 'emailCreate'])->name('create');
            Route::get('/contracts/list', [\App\Http\Controllers\Admin\PackageController::class, 'contractsForEmail'])->name('contracts');
            Route::post('/from-contracts', [\App\Http\Controllers\Admin\PackageController::class, 'storeEmailFromContracts'])->name('store-from-contracts');
            Route::get('/{package}', [\App\Http\Controllers\Admin\PackageController::class, 'emailShow'])->name('show');
            Route::post('/{package}/dispatch', [\App\Http\Controllers\Admin\PackageController::class, 'dispatch'])->name('dispatch');
            Route::post('/{package}/cancel', [\App\Http\Controllers\Admin\PackageController::class, 'cancel'])->name('cancel');
            Route::delete('/{package}', [\App\Http\Controllers\Admin\PackageController::class, 'destroy'])->name('destroy');
        });
    });

    // Contract document generation (JSON) - protected by auth+verified; permission enforced inside controller service
    Route::post('contracts/{contract:uuid}/generate-document', \App\Http\Controllers\ContractDocumentGenerationController::class)->name('contracts.generate-document')->middleware('permission:create-docs');
    // Contracts actions
    Route::patch('/contracts/segment', [\App\Http\Controllers\ContractController::class, 'segment'])
        ->name('contracts.segment');
    // Phone page
    Route::get('phone', [PhoneViewController::class, 'index'])->name('phone.index');
    Route::get('phone/completed', [PhoneViewController::class, 'completedToday'])->name('phone.completed');
    Route::get('phone/case/{client_case:uuid}', [PhoneViewController::class, 'showCase'])->name('phone.case');
    Route::post('phone/case/{client_case:uuid}/complete', [FieldJobController::class, 'complete'])->name('phone.case.complete');

    Route::get('search', function (Request $request) {

        if (! empty($request->input('query'))) {

            $clients = App\Models\Person\Person::search($request->input('query'))
                ->query(function ($builder) use ($request): void {
                    $builder->join('clients', 'person.id', '=', 'clients.person_id')
                        ->leftJoin('person_addresses', 'person.id', '=', 'person_addresses.person_id')
                        ->leftJoin('person_phones', 'person.id', '=', 'person_phones.person_id')
                        ->leftJoin('emails', 'person.id', '=', 'emails.person_id')
                        ->select('person.*', 'clients.uuid as client_uuid')
                        ->limit($request->input('limit'));
                })
                ->get();

            $clientCases = App\Models\Person\Person::search($request->input('query'))
                ->query(function ($builder) use ($request): void {
                    $builder->join('client_cases', 'person.id', '=', 'client_cases.person_id')
                        ->leftJoin('person_addresses', 'person.id', '=', 'person_addresses.person_id')
                        ->leftJoin('person_phones', 'person.id', '=', 'person_phones.person_id')
                        ->leftJoin('emails', 'person.id', '=', 'emails.person_id')
                        ->leftJoin('clients', 'clients.id', '=', 'client_cases.client_id')
                        ->leftJoin('person as client_person', 'client_person.id', '=', 'clients.person_id')
                        ->select(
                            'person.*',
                            'client_cases.uuid as case_uuid',
                            'client_cases.id as case_id',
                            'client_person.full_name as client_full_name'
                        )
                        ->limit($request->input('limit'));
                })
                ->get();

            // Also search by contract reference and include affiliated cases ("Primeri")
            $limit = (int) ($request->input('limit') ?? 8);
            $query = trim((string) $request->input('query'));
            if ($query !== '') {
                $contractCases = \App\Models\Contract::query()
                    ->join('client_cases', 'contracts.client_case_id', '=', 'client_cases.id')
                    ->join('person', 'client_cases.person_id', '=', 'person.id')
                    ->leftJoin('clients', 'clients.id', '=', 'client_cases.client_id')
                    ->leftJoin('person as client_person', 'client_person.id', '=', 'clients.person_id')
                    ->leftJoin('contract_segment', function ($j) {
                        $j->on('contract_segment.contract_id', '=', 'contracts.id')
                            ->where('contract_segment.active', true);
                    })
                    ->leftJoin('segments', 'segments.id', '=', 'contract_segment.segment_id')
                    // case-insensitive reference match
                    ->whereRaw('LOWER(contracts.reference) LIKE ?', ['%'.mb_strtolower($query).'%'])
                    ->select(
                        'person.*',
                        'client_cases.uuid as case_uuid',
                        'client_cases.id as case_id',
                        'contracts.reference as contract_reference',
                        'client_person.full_name as client_full_name',
                        \DB::raw("COALESCE(json_agg(DISTINCT jsonb_build_object('id', segments.id, 'name', segments.name)) FILTER (WHERE segments.id IS NOT NULL), '[]') as contract_segments")
                    )
                    ->groupBy('person.id', 'client_cases.uuid', 'client_cases.id', 'contracts.reference', 'client_person.full_name')
                    ->limit($limit)
                    ->get();

                // Merge and de-duplicate by case uuid
                $clientCases = $clientCases
                    ->concat($contractCases)
                    ->unique('case_uuid')
                    ->values();

                // Collect all case ids for segment lookup (for non-contract matches)
                $caseIds = $clientCases->pluck('case_id')->filter()->unique()->values();
                if ($caseIds->isNotEmpty()) {
                    $caseSegments = \DB::table('client_cases')
                        ->join('contracts', 'contracts.client_case_id', '=', 'client_cases.id')
                        ->join('contract_segment', function ($j) {
                            $j->on('contract_segment.contract_id', '=', 'contracts.id')
                                ->where('contract_segment.active', true);
                        })
                        ->join('segments', 'segments.id', '=', 'contract_segment.segment_id')
                        ->whereIn('client_cases.id', $caseIds)
                        ->select(
                            'client_cases.id as case_id',
                            \DB::raw("COALESCE(json_agg(DISTINCT jsonb_build_object('id', segments.id, 'name', segments.name)) FILTER (WHERE segments.id IS NOT NULL), '[]') as segments_json")
                        )
                        ->groupBy('client_cases.id')
                        ->get()
                        ->keyBy('case_id');

                    $clientCases = $clientCases->map(function ($row) use ($contractCases, $caseSegments) {
                        $contractHit = $contractCases->firstWhere('case_uuid', $row->case_uuid);
                        if ($contractHit) {
                            $row->contract_reference = $contractHit->contract_reference;
                            $segmentsJson = $contractHit->contract_segments ?? '[]';
                            $row->contract_segments = is_string($segmentsJson) ? json_decode($segmentsJson, true) : (array) $segmentsJson;
                        } else {
                            $segRow = $caseSegments->get($row->case_id);
                            if ($segRow) {
                                $row->case_segments = json_decode($segRow->segments_json, true) ?? [];
                            } else {
                                $row->case_segments = [];
                            }
                        }

                        return $row;
                    })->take($limit);
                } else {
                    $clientCases = $clientCases->take($limit);
                }
            }

            return [
                'clients' => $clients,
                'client_cases' => $clientCases,
                'query' => $request->input('query'),
            ];

        }

        return [];
    })->name('search');

    // person
    Route::put('person/{person:uuid}', [PersonController::class, 'update'])->name('person.update')->middleware('permission:person-edit');
    Route::post('person/{person:uuid}/address', [PersonController::class, 'createAddress'])->name('person.address.create');
    Route::put('person/{person:uuid}/address/{address_id}', [PersonController::class, 'updateAddress'])->name('person.address.update');
    Route::delete('person/{person:uuid}/address/{address_id}', [PersonController::class, 'deleteAddress'])->name('person.address.delete');
    Route::post('person/{person:uuid}/phone', [PersonController::class, 'createPhone'])->name('person.phone.create');
    Route::put('person/{person:uuid}/phone/{phone_id}', [PersonController::class, 'updatePhone'])->name('person.phone.update');
    Route::delete('person/{person:uuid}/phone/{phone_id}', [PersonController::class, 'deletePhone'])->name('person.phone.delete');
    Route::post('person/{person:uuid}/email', [PersonController::class, 'createEmail'])->name('person.email.create');
    Route::put('person/{person:uuid}/email/{email_id}', [PersonController::class, 'updateEmail'])->name('person.email.update');
    Route::delete('person/{person:uuid}/email/{email_id}', [PersonController::class, 'deleteEmail'])->name('person.email.delete');
    // TRR (Bank account) endpoints
    Route::post('person/{person:uuid}/trr', [PersonController::class, 'createTrr'])->name('person.trr.create');
    Route::put('person/{person:uuid}/trr/{trr_id}', [PersonController::class, 'updateTrr'])->name('person.trr.update');
    Route::delete('person/{person:uuid}/trr/{trr_id}', [PersonController::class, 'deleteTrr'])->name('person.trr.delete');
    // client
    Route::get('clients', [ClientController::class, 'index'])->name('client');
    Route::get('clients/{client:uuid}', [ClientController::class, 'show'])->name('client.show');
    Route::get('clients/{client:uuid}/contracts', [ClientController::class, 'contracts'])->name('client.contracts');
    Route::post('clients/{client:uuid}/contracts/export', [ClientController::class, 'exportContracts'])->name('client.contracts.export');

    Route::middleware('permission:client-edit')->group(function () {
        Route::post('clients', [ClientController::class, 'store'])->name('client.store');
        Route::put('clients/{client:uuid}', [ClientController::class, 'update'])->name('client.update');
        Route::post('clients/{client:uuid}/emergency-person', [ClientController::class, 'emergencyCreatePerson'])->name('client.emergencyPerson');

    });

    // client-case
    Route::get('client-cases', [ClientCaseContoller::class, 'index'])->name('clientCase');
    Route::get('client-cases/{client_case:uuid}', [ClientCaseContoller::class, 'show'])->name('clientCase.show');
    Route::post('client-cases/{client_case:uuid}/contracts/{uuid}/segment', [ClientCaseContoller::class, 'updateContractSegment'])->name('clientCase.contract.updateSegment');
    Route::post('client-cases/{client_case:uuid}/contracts/{uuid}/archive', [ClientCaseContoller::class, 'archiveContract'])->name('clientCase.contract.archive');
    Route::post('contracts/archive-batch', [ClientCaseContoller::class, 'archiveBatch'])->name('contracts.archive-batch')->middleware('permission:mass-archive');
    Route::post('client-cases', [ClientCaseContoller::class, 'store'])->name('clientCase.store');
    Route::post('client-cases/{client_case:uuid}/emergency-person', [ClientCaseContoller::class, 'emergencyCreatePerson'])->name('clientCase.emergencyPerson');
    // client-case / contract
    Route::get('client-cases/{client_case:uuid}/contract/{uuid}/debug-accounts', [ClientCaseContoller::class, 'debugContractAccounts'])->name('clientCase.contract.debugAccounts');

    Route::middleware('permission:contract-edit')->group(function () {
        Route::post('client-cases/{client_case:uuid}/contract', [ClientCaseContoller::class, 'storeContract'])->name('clientCase.contract.store');
        Route::put('client-cases/{client_case:uuid}/contract/{uuid}', [ClientCaseContoller::class, 'updateContract'])->name('clientCase.contract.update');
        Route::patch('client-cases/{client_case:uuid}/contract/{uuid}/meta', [ClientCaseContoller::class, 'patchContractMeta'])->name('clientCase.contract.patchMeta');
        Route::delete('client-cases/{client_case:uuid}/contract/{uuid}', [ClientCaseContoller::class, 'deleteContract'])->name('clientCase.contract.delete');
    });

    // client-case / contract / objects
    Route::post('client-cases/{client_case:uuid}/contract/{uuid}/objects', [CaseObjectController::class, 'store'])->name('clientCase.contract.object.store');
    Route::put('client-cases/{client_case:uuid}/objects/{id}', [CaseObjectController::class, 'update'])->name('clientCase.object.update');
    Route::delete('client-cases/{client_case:uuid}/objects/{id}', [CaseObjectController::class, 'destroy'])->name('clientCase.object.delete');
    // client-case / activity
    Route::post('client-cases/{client_case:uuid}/activity', [ClientCaseContoller::class, 'storeActivity'])->name('clientCase.activity.store');
    Route::delete('client-cases/{client_case:uuid}/activity/{activity}', [ClientCaseContoller::class, 'deleteActivity'])->name('clientCase.activity.delete')->middleware('permission:activity-edit');
    // client-case / segments
    Route::post('client-cases/{client_case:uuid}/segments', [ClientCaseContoller::class, 'attachSegment'])->name('clientCase.segments.attach');
    // client-case / documents
    Route::post('client-cases/{client_case:uuid}/documents', [ClientCaseContoller::class, 'storeDocument'])->name('clientCase.document.store');

    Route::get('client-cases/{client_case:uuid}/documents/{document:uuid}/view', [ClientCaseContoller::class, 'viewDocument'])->name('clientCase.document.view');
    Route::get('client-cases/{client_case:uuid}/documents/{document:uuid}/download', [ClientCaseContoller::class, 'downloadDocument'])->name('clientCase.document.download');
    Route::middleware('permission:doc-edit')->group(function () {
        Route::patch('client-cases/{client_case:uuid}/documents/{document:uuid}', [ClientCaseContoller::class, 'updateDocument'])
            ->withoutScopedBindings()
            ->name('clientCase.document.update');
        Route::delete('client-cases/{client_case:uuid}/documents/{document:uuid}', [ClientCaseContoller::class, 'deleteDocument'])->name('clientCase.document.delete');
    });
    // client-case / person phone - send SMS
    Route::post('client-cases/{client_case:uuid}/phone/{phone_id}/sms', [ClientCaseContoller::class, 'sendSmsToPhone'])->name('clientCase.phone.sms');
    // client-case / person email - preview & send
    Route::post('client-cases/{client_case:uuid}/email/{email_id}/preview', [ClientCaseContoller::class, 'previewEmailForEmail'])->name('clientCase.email.preview');
    Route::post('client-cases/{client_case:uuid}/email/{email_id}/send', [ClientCaseContoller::class, 'sendEmailToEmail'])->name('clientCase.email.send');
    // client-case / contracts list for SMS dialog
    Route::get('client-cases/{client_case:uuid}/contracts/list', [ClientCaseContoller::class, 'listContracts'])->name('clientCase.contracts.list');
    // client-case / SMS template preview
    Route::post('client-cases/{client_case:uuid}/sms/preview', [ClientCaseContoller::class, 'previewSms'])->name('clientCase.sms.preview');
    // contract / documents (direct access by contract)
    Route::get('contracts/{contract:uuid}/documents/{document:uuid}/view', [ClientCaseContoller::class, 'viewContractDocument'])->name('contract.document.view');
    Route::get('contracts/{contract:uuid}/documents/{document:uuid}/download', [ClientCaseContoller::class, 'downloadContractDocument'])->name('contract.document.download');

    // Notifications: unread list and mark one activity as read (today)
    Route::get('notifications/unread', [NotificationController::class, 'unread'])->name('notifications.unread');
    Route::patch('notifications/activity/read', ActivityNotificationController::class)->name('notifications.activity.read');
    Route::delete('contracts/{contract:uuid}/documents/{document:uuid}', [ClientCaseContoller::class, 'deleteContractDocument'])->name('contract.document.delete');
    // settings
    Route::get('settings', [SettingController::class, 'index'])->name('settings');
    Route::get('settings/segments', [SegmentController::class, 'settings'])->name('settings.segments');
    Route::post('settings/segments', [SegmentController::class, 'store'])->name('settings.segments.store');
    Route::put('settings/segments/{segment}', [SegmentController::class, 'update'])->name('settings.segments.update');
    // settings / archive settings
    Route::get('settings/archive', [ArchiveSettingController::class, 'index'])->name('settings.archive.index');
    Route::post('settings/archive', [ArchiveSettingController::class, 'store'])->name('settings.archive.store');
    Route::put('settings/archive/{archiveSetting}', [ArchiveSettingController::class, 'update'])->name('settings.archive.update');
    Route::post('settings/archive/{archiveSetting}/run', [ArchiveSettingController::class, 'run'])->name('settings.archive.run');
    Route::delete('settings/archive/{archiveSetting}', [ArchiveSettingController::class, 'destroy'])->name('settings.archive.destroy');
    // settings / reports settings
    Route::get('settings/reports', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'index'])->name('settings.reports.index');
    Route::get('settings/reports/{report}/edit', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'edit'])->name('settings.reports.edit');
    Route::post('settings/reports', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'store'])->name('settings.reports.store');
    Route::put('settings/reports/{report}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'update'])->name('settings.reports.update');
    Route::post('settings/reports/{report}/toggle', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'toggleEnabled'])->name('settings.reports.toggle');
    Route::delete('settings/reports/{report}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'destroy'])->name('settings.reports.destroy');
    // settings / reports - entities
    Route::post('settings/reports/{report}/entities', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'storeEntity'])->name('settings.reports.entities.store');
    Route::put('settings/reports/entities/{entity}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'updateEntity'])->name('settings.reports.entities.update');
    Route::delete('settings/reports/entities/{entity}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'destroyEntity'])->name('settings.reports.entities.destroy');
    // settings / reports - columns
    Route::post('settings/reports/{report}/columns', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'storeColumn'])->name('settings.reports.columns.store');
    Route::put('settings/reports/columns/{column}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'updateColumn'])->name('settings.reports.columns.update');
    Route::delete('settings/reports/columns/{column}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'destroyColumn'])->name('settings.reports.columns.destroy');
    // settings / reports - filters
    Route::post('settings/reports/{report}/filters', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'storeFilter'])->name('settings.reports.filters.store');
    Route::put('settings/reports/filters/{filter}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'updateFilter'])->name('settings.reports.filters.update');
    Route::delete('settings/reports/filters/{filter}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'destroyFilter'])->name('settings.reports.filters.destroy');
    // settings / reports - conditions
    Route::post('settings/reports/{report}/conditions', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'storeCondition'])->name('settings.reports.conditions.store');
    Route::put('settings/reports/conditions/{condition}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'updateCondition'])->name('settings.reports.conditions.update');
    Route::delete('settings/reports/conditions/{condition}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'destroyCondition'])->name('settings.reports.conditions.destroy');
    // settings / reports - orders
    Route::post('settings/reports/{report}/orders', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'storeOrder'])->name('settings.reports.orders.store');
    Route::put('settings/reports/orders/{order}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'updateOrder'])->name('settings.reports.orders.update');
    Route::delete('settings/reports/orders/{order}', [\App\Http\Controllers\Settings\ReportSettingsController::class, 'destroyOrder'])->name('settings.reports.orders.destroy');
    Route::get('settings/workflow', [WorkflowController::class, 'index'])->name('settings.workflow');
    Route::get('settings/field-job', [FieldJobSettingController::class, 'index'])->name('settings.fieldjob.index');

    // field jobs assignment
    Route::middleware('permission:field-job')->group(function () {
        Route::get('field-jobs', [FieldJobController::class, 'index'])->name('fieldjobs.index');
        Route::post('field-jobs/assign', [FieldJobController::class, 'assign'])->name('fieldjobs.assign');
        Route::post('field-jobs/assign-bulk', [FieldJobController::class, 'assignBulk'])->name('fieldjobs.assign-bulk');
        Route::post('field-jobs/cancel', [FieldJobController::class, 'cancel'])->name('fieldjobs.cancel');
        Route::post('settings/field-job', [FieldJobSettingController::class, 'store'])->name('settings.fieldjob.store');
        Route::put('settings/field-job/{setting}', [FieldJobSettingController::class, 'update'])->name('settings.fieldjob.update');
        // settings / contract-configs
    });

    Route::get('settings/contract-configs', [ContractConfigController::class, 'index'])->name('settings.contractConfigs.index');
    Route::post('settings/contract-configs', [ContractConfigController::class, 'store'])->name('settings.contractConfigs.store');
    Route::put('settings/contract-configs/{config}', [ContractConfigController::class, 'update'])->name('settings.contractConfigs.update');
    Route::delete('settings/contract-configs/{config}', [ContractConfigController::class, 'destroy'])->name('settings.contractConfigs.destroy');
    Route::post('settings/actions', [WorkflowController::class, 'storeAction'])->name('settings.actions.store');
    Route::put('settings/actions/{id}', [WorkflowController::class, 'updateAction'])->name('settings.actions.update');
    Route::post('settings/decisions', [WorkflowController::class, 'storeDecision'])->name('settings.decisions.store');
    Route::put('settings/decisions/{id}', [WorkflowController::class, 'updateDecision'])->name('settings.decisions.update');
    Route::delete('settings/actions/{id}', [WorkflowController::class, 'destroyAction'])->name('settings.actions.destroy');
    Route::delete('settings/decisions/{id}', [WorkflowController::class, 'destroyDecision'])->name('settings.decisions.destroy');

    // segments index overview
    Route::get('segments', [SegmentController::class, 'index'])->name('segments.index');
    Route::get('segments/{segment}', [SegmentController::class, 'show'])->name('segments.show');
    Route::post('segments/{segment}/export', [SegmentController::class, 'export'])->name('segments.export');

    Route::middleware('permission:manage-imports')->group(function () {
        // imports
        Route::get('imports/create', [ImportController::class, 'create'])->name('imports.create');
        Route::get('imports', [ImportController::class, 'index'])->name('imports.index');
        Route::get('imports/import/{import:uuid}', [ImportController::class, 'show'])->name('imports.continue');
        Route::post('imports', [ImportController::class, 'store'])->name('imports.store');
        Route::get('imports/{import}/columns', [ImportController::class, 'columns'])->name('imports.columns');
        Route::post('imports/{import}/process', [ImportController::class, 'process'])->name('imports.process');
        Route::post('imports/{import}/mappings', [ImportController::class, 'saveMappings'])->name('imports.mappings.save');
        Route::get('imports/{import}/mappings', [ImportController::class, 'getMappings'])->name('imports.mappings.get');
        Route::get('imports/{import}/events', [ImportController::class, 'getEvents'])->name('imports.events');
        Route::get('imports/{import}/missing-keyref-rows', [ImportController::class, 'missingKeyrefRows'])->name('imports.missing-keyref-rows');
        Route::get('imports/{import}/missing-keyref-csv', [ImportController::class, 'exportMissingKeyrefCsv'])->name('imports.missing-keyref-csv');
        Route::get('imports/{import}/preview', [ImportController::class, 'preview'])->name('imports.preview');
        Route::get('imports/{import}/download', [ImportController::class, 'download'])->name('imports.download');
        Route::get('imports/{import}/missing-contracts', [ImportController::class, 'missingContracts'])->name('imports.missing-contracts');
        Route::post('imports/{import}/options', [ImportController::class, 'updateOptions'])->name('imports.options');
        // Generic simulation endpoint (new) – provides projected effects for first N rows regardless of payments template
        Route::get('imports/{import}/simulate', [ImportController::class, 'simulate'])->name('imports.simulate');
        // Backwards compatible payments simulation route (legacy name) – now proxies to generic simulate method
        Route::get('imports/{import}/simulate-payments', [ImportController::class, 'simulatePayments'])->name('imports.simulatePayments');

        // import templates
        Route::get('imports/templates', [ImportTemplateController::class, 'index'])->name('importTemplates.index');
        Route::get('imports/templates/create', [ImportTemplateController::class, 'create'])->name('importTemplates.create');
        Route::post('imports/templates', [ImportTemplateController::class, 'store'])->name('importTemplates.store');
        Route::post('imports/templates/import', [ImportTemplateController::class, 'import'])->name('importTemplates.import');
        Route::get('imports/templates/edit/{template:uuid}', [ImportTemplateController::class, 'edit'])->name('importTemplates.edit');
        Route::get('imports/templates/{template:uuid}/export', [ImportTemplateController::class, 'export'])->name('importTemplates.export');
        Route::put('imports/templates/{template:uuid}', [ImportTemplateController::class, 'update'])->name('importTemplates.update');
        Route::delete('imports/templates/{template:uuid}', [ImportTemplateController::class, 'destroy'])->name('importTemplates.destroy');
        Route::post('imports/templates/{template:uuid}/mappings', [ImportTemplateController::class, 'addMapping'])->name('importTemplates.mappings.add');
        Route::post('imports/templates/{template:uuid}/mappings/bulk', [ImportTemplateController::class, 'bulkAddMappings'])->name('importTemplates.mappings.bulk');
        Route::put('imports/templates/{template:uuid}/mappings/{mapping}', [ImportTemplateController::class, 'updateMapping'])->name('importTemplates.mappings.update');
        Route::delete('imports/templates/{template:uuid}/mappings/{mapping}', [ImportTemplateController::class, 'deleteMapping'])->name('importTemplates.mappings.delete');
        Route::post('imports/templates{template:uuid}/mappings/reorder', [ImportTemplateController::class, 'reorderMappings'])->name('importTemplates.mappings.reorder');
        Route::post('imports/templates/{template:uuid}/apply/{import}', [ImportTemplateController::class, 'applyToImport'])->name('importTemplates.apply');
        // Delete an unfinished import
        Route::delete('imports/{import}', [ImportController::class, 'destroy'])->name('imports.destroy');
        // Route::put()
        // types
    });
    // accounts / payments & bookings
    Route::prefix('accounts/{account}')->name('accounts.')->group(function (): void {
        Route::get('payments', [AccountPaymentController::class, 'index'])->name('payments.index');
        Route::get('payments/list', [AccountPaymentController::class, 'list'])->name('payments.list');
        Route::post('payments', [AccountPaymentController::class, 'store'])->name('payments.store');
        Route::delete('payments/{payment}', [AccountPaymentController::class, 'destroy'])->name('payments.destroy');

        Route::get('bookings', [AccountBookingController::class, 'index'])->name('bookings.index');
        Route::post('bookings', [AccountBookingController::class, 'store'])->name('bookings.store');
        Route::delete('bookings/{booking}', [AccountBookingController::class, 'destroy'])->name('bookings.destroy');

        Route::get('installments/list', [AccountInstallmentController::class, 'list'])->name('installments.list');
        Route::post('installments', [AccountInstallmentController::class, 'store'])->name('installments.store');
        Route::delete('installments/{installment}', [AccountInstallmentController::class, 'destroy'])->name('installments.destroy');
    });

    // settings - payment settings
    Route::get('settings/payment', [PaymentSettingController::class, 'edit'])->name('settings.payment.edit');
    Route::put('settings/payment', [PaymentSettingController::class, 'update'])->name('settings.payment.update');

    // settings - installment settings
    Route::get('settings/installment', [InstallmentSettingController::class, 'edit'])->name('settings.installment.edit');
    Route::put('settings/installment', [InstallmentSettingController::class, 'update'])->name('settings.installment.update');

    // settings - contract settings
    Route::get('settings/contract', [ContractSettingController::class, 'edit'])->name('settings.contract.edit');
    Route::put('settings/contract', [ContractSettingController::class, 'update'])->name('settings.contract.update');

    Route::get('types/address', function (Request $request) {
        $types = App\Models\Person\AddressType::all();

        return response()->json([
            'types' => $types,
        ]);
    })->name('types.address');

    // reports
    Route::middleware('permission:reports-view')->group(function () {
        Route::get('reports', [\App\Http\Controllers\ReportController::class, 'index'])->name('reports.index');
        // users/clients lookup must come before {slug} to avoid route conflicts
        Route::get('reports/users', [\App\Http\Controllers\ReportController::class, 'users'])->name('reports.users');
        Route::get('reports/clients', [\App\Http\Controllers\ReportController::class, 'clients'])->name('reports.clients');
        Route::get('reports/actions', [\App\Http\Controllers\ReportController::class, 'actions'])->name('reports.actions');
        Route::get('reports/decisions', [\App\Http\Controllers\ReportController::class, 'decisions'])->name('reports.decisions');
        Route::get('reports/{slug}', [\App\Http\Controllers\ReportController::class, 'show'])->name('reports.show');
        Route::get('reports/{slug}/data', [\App\Http\Controllers\ReportController::class, 'data'])->name('reports.data');
    });
    Route::get('reports/{slug}/export', [\App\Http\Controllers\ReportController::class, 'export'])->middleware('permission:reports-export')->name('reports.export');

    // Call laters
    Route::get('call-laters', [\App\Http\Controllers\CallLaterController::class, 'index'])->name('callLaters.index');
    Route::patch('call-laters/{callLater}/complete', [\App\Http\Controllers\CallLaterController::class, 'complete'])->name('callLaters.complete');

});
