<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\InstallController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\CashInController;
use App\Http\Controllers\CashOutController;
use App\Http\Controllers\ClientController;
use App\Http\Controllers\ExpenseController;
use App\Http\Controllers\UsersController;
use App\Http\Controllers\ReportsController;
use App\Http\Controllers\SettingsController;
use App\Http\Controllers\CustomAccountController;
use App\Http\Controllers\ConsignmentController;
use Illuminate\Support\Facades\Route;

// 1. Installation Wizard Routes (InstallMiddleware blocks if lock file exists)
Route::prefix('install')->name('install.')->group(function () {
    Route::get('/', [InstallController::class, 'step1'])->name('step1');
    Route::get('/requirements', [InstallController::class, 'step2'])->name('step2');
    Route::get('/database', [InstallController::class, 'step3'])->name('step3');
    Route::post('/database/test', [InstallController::class, 'testConnection'])->name('step3.test');
    Route::post('/database/save', [InstallController::class, 'saveDatabase'])->name('step3.save');
    Route::get('/business', [InstallController::class, 'step4'])->name('step4');
    Route::post('/business/save', [InstallController::class, 'saveBusiness'])->name('step4.save');
    Route::get('/admin', [InstallController::class, 'step5'])->name('step5');
    Route::post('/admin/save', [InstallController::class, 'saveAdmin'])->name('step5.save');
    Route::get('/complete', [InstallController::class, 'step6'])->name('step6');
});

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

// Public route to serve storage files (no symlink needed for cPanel)
Route::get('/serve-storage/{path}', function ($path) {
    if (str_contains($path, '..')) {
        abort(404);
    }
    $fullPath = storage_path('app/public/' . $path);
    abort_unless(file_exists($fullPath), 404);
    return response()->file($fullPath);
})->where('path', '.*');

// 3. Authenticated Dashboard Route
Route::get('/dashboard', [DashboardController::class, 'index'])
    ->middleware(['auth', 'verified'])
    ->name('dashboard');

// 4A. Group: Admin, Manager, and Accountant Access Limits
Route::middleware(['auth', 'role:admin,manager,accountant,data_entry_manager', 'throttle:60,1'])->group(function () {
    
    // CASH IN MODULE
    Route::get('/cash-in', [CashInController::class, 'index'])->name('cash-in.index');
    Route::get('/cash-in/create', [CashInController::class, 'create'])->name('cash-in.create');
    Route::post('/cash-in', [CashInController::class, 'store'])->name('cash-in.store');
    Route::get('/cash-in/{cashIn}', [CashInController::class, 'show'])->name('cash-in.show');
    Route::get('/cash-in/{cashIn}/edit', [CashInController::class, 'edit'])->name('cash-in.edit');
    Route::put('/cash-in/{cashIn}', [CashInController::class, 'update'])->name('cash-in.update');
    Route::get('/cash-in/{cashIn}/download-receipt', [CashInController::class, 'downloadReceipt'])->name('cash-in.download-receipt');
    Route::get('/cash-in/{cashIn}/download-pdf', [CashInController::class, 'downloadPdf'])->name('cash-in.download-pdf');
    Route::post('/cash-in/{cashIn}/send-email', [CashInController::class, 'sendEmail'])->name('cash-in.send-email');
    Route::get('/cash-in/{cashIn}/share-whatsapp', [CashInController::class, 'shareWhatsApp'])->name('cash-in.share-whatsapp');
    Route::post('/cash-in/create-client', [CashInController::class, 'createClientInline'])->name('cash-in.create-client');
    Route::post('/cash-in/create-custom-account', [CashInController::class, 'createCustomAccountInline'])->name('cash-in.create-custom-account');

    // CASH OUT MODULE
    Route::get('/cash-out', [CashOutController::class, 'index'])->name('cash-out.index');
    Route::get('/cash-out/create', [CashOutController::class, 'create'])->name('cash-out.create');
    Route::post('/cash-out', [CashOutController::class, 'store'])->name('cash-out.store');
    Route::get('/cash-out/{cashOut}', [CashOutController::class, 'show'])->name('cash-out.show');
    Route::get('/cash-out/{cashOut}/edit', [CashOutController::class, 'edit'])->name('cash-out.edit');
    Route::put('/cash-out/{cashOut}', [CashOutController::class, 'update'])->name('cash-out.update');
    Route::get('/cash-out/{cashOut}/download-receipt', [CashOutController::class, 'downloadReceipt'])->name('cash-out.download-receipt');
    Route::get('/cash-out/{cashOut}/download-pdf', [CashOutController::class, 'downloadPdf'])->name('cash-out.download-pdf');
    Route::post('/cash-out/{cashOut}/send-email', [CashOutController::class, 'sendEmail'])->name('cash-out.send-email');
    Route::get('/cash-out/{cashOut}/share-whatsapp', [CashOutController::class, 'shareWhatsApp'])->name('cash-out.share-whatsapp');
    Route::post('/cash-out/create-client', [CashOutController::class, 'createClientInline'])->name('cash-out.create-client');
    Route::post('/cash-out/create-custom-account', [CashOutController::class, 'createCustomAccountInline'])->name('cash-out.create-custom-account');

    // CLIENTS MODULE
    Route::get('/clients', [ClientController::class, 'index'])->name('clients.index');
    Route::get('/clients/create', [ClientController::class, 'create'])->name('clients.create');
    Route::post('/clients', [ClientController::class, 'store'])->name('clients.store');
    Route::get('/clients/{client}', [ClientController::class, 'show'])->name('clients.show');
    Route::get('/clients/{client}/edit', [ClientController::class, 'edit'])->name('clients.edit');
    Route::put('/clients/{client}', [ClientController::class, 'update'])->name('clients.update');
    Route::get('/clients/{client}/download-ledger-pdf', [ClientController::class, 'downloadLedgerPdf'])->name('clients.download-ledger-pdf');

    // CONSIGNMENTS MODULE
    Route::get('/consignments', [ConsignmentController::class, 'index'])->name('consignments.index');
    Route::get('/consignments/create', [ConsignmentController::class, 'create'])->name('consignments.create');
    Route::post('/consignments', [ConsignmentController::class, 'store'])->name('consignments.store');
    Route::get('/consignments/{consignment}', [ConsignmentController::class, 'show'])->name('consignments.show');
    Route::get('/consignments/{consignment}/edit', [ConsignmentController::class, 'edit'])->name('consignments.edit');
    Route::put('/consignments/{consignment}', [ConsignmentController::class, 'update'])->name('consignments.update');

    // EXPENSES MODULE
    Route::get('/expenses', [ExpenseController::class, 'index'])->name('expenses.index');
    Route::get('/expenses/create', [ExpenseController::class, 'create'])->name('expenses.create');
    Route::post('/expenses', [ExpenseController::class, 'store'])->name('expenses.store');
    Route::get('/expenses/categories-list', [ExpenseController::class, 'categoriesList'])->name('expenses.categories.list');
    Route::get('/expenses/{expense}', [ExpenseController::class, 'show'])->name('expenses.show');
    Route::get('/expenses/{expense}/edit', [ExpenseController::class, 'edit'])->name('expenses.edit');
    Route::put('/expenses/{expense}', [ExpenseController::class, 'update'])->name('expenses.update');
    Route::get('/expenses/{expense}/download-pdf', [ExpenseController::class, 'downloadPdf'])->name('expenses.download-pdf');
    Route::post('/expenses/{expense}/send-email', [ExpenseController::class, 'sendEmail'])->name('expenses.send-email');
    Route::get('/expenses/{expense}/share-whatsapp', [ExpenseController::class, 'shareWhatsApp'])->name('expenses.share-whatsapp');
    
    // REPORTS MODULE
    Route::get('/reports', [ReportsController::class, 'index'])->name('reports.index');
    Route::get('/reports/tax-summary/pdf', [ReportsController::class, 'taxSummaryPdf'])->name('reports.tax-summary.pdf');
    Route::get('/reports/cash-flow/pdf', [ReportsController::class, 'cashFlowPdf'])->name('reports.cash-flow.pdf');
    Route::get('/reports/cash-flow/excel', [ReportsController::class, 'cashFlowExcel'])->name('reports.cash-flow.excel');
    Route::get('/reports/expenses/pdf', [ReportsController::class, 'expensesPdf'])->name('reports.expenses.pdf');
    Route::get('/reports/clients/pdf', [ReportsController::class, 'clientsPdf'])->name('reports.clients.pdf');
    Route::get('/reports/vat-return/csv', [ReportsController::class, 'vatReturnCsv'])->name('reports.vat-return.csv');
    Route::get('/reports/vat-return/pdf', [ReportsController::class, 'vatReturnPdf'])->name('reports.vat-return.pdf');

    // CUSTOM ACCOUNTS MODULE
    Route::get('/custom-accounts', [CustomAccountController::class, 'index'])->name('custom-accounts.index');
    Route::get('/custom-accounts/create', [CustomAccountController::class, 'create'])->name('custom-accounts.create');
    Route::post('/custom-accounts', [CustomAccountController::class, 'store'])->name('custom-accounts.store');
    Route::get('/custom-accounts/{customAccount}', [CustomAccountController::class, 'show'])->name('custom-accounts.show');
    Route::get('/custom-accounts/{customAccount}/edit', [CustomAccountController::class, 'edit'])->name('custom-accounts.edit');
    Route::put('/custom-accounts/{customAccount}', [CustomAccountController::class, 'update'])->name('custom-accounts.update');
    Route::get('/custom-accounts/{customAccount}/download-ledger-pdf', [CustomAccountController::class, 'downloadLedgerPdf'])->name('custom-accounts.download-ledger-pdf');

    // MULTI-CURRENCY EXCHANGE RATE UTILITY
    Route::get('/currency/fetch-rate', [CashInController::class, 'fetchExchangeRate'])->name('currency.fetch-rate');
});

// 4B. Group: Admin and Manager Only (accountant and data_entry_manager excluded)
Route::middleware(['auth', 'role:admin,manager', 'throttle:60,1'])->group(function () {
    // Expense category management
    Route::post('/expenses/categories', [ExpenseController::class, 'storeCategory'])->name('expenses.categories.store');
    Route::put('/expenses/categories/{category}', [ExpenseController::class, 'updateCategory'])->name('expenses.categories.update');
    Route::delete('/expenses/categories/{category}', [ExpenseController::class, 'deleteCategory'])->name('expenses.categories.destroy');
    
    // AJAX Expense Categories management
    Route::post('/expenses/store-category-ajax', [ExpenseController::class, 'storeCategoryAjax'])->name('expenses.categories.store-ajax');
    Route::post('/expenses/update-category-ajax/{category}', [ExpenseController::class, 'updateCategoryAjax'])->name('expenses.categories.update-ajax');
    Route::post('/expenses/destroy-category-ajax/{id}', [ExpenseController::class, 'destroyCategoryAjax'])->name('expenses.categories.destroy-ajax');
});

// 5A. Group: Admin + Accountant (settings module)
Route::middleware(['auth', 'role:admin,accountant', 'throttle:60,1'])->group(function () {

    // SETTINGS MODULE
    Route::get('/settings', [SettingsController::class, 'index'])->name('settings.index');
    Route::post('/settings/business', [SettingsController::class, 'saveBusiness'])->name('settings.business');
    Route::post('/settings/currency', [SettingsController::class, 'saveCurrency'])->name('settings.currency');
    Route::post('/settings/bank-accounts', [SettingsController::class, 'storeBankAccount'])->name('settings.bank-accounts.store');
    Route::put('/settings/bank-accounts/{bankAccount}', [SettingsController::class, 'updateBankAccount'])->name('settings.bank-accounts.update');
    Route::delete('/settings/bank-accounts/{bankAccount}', [SettingsController::class, 'deleteBankAccount'])->name('settings.bank-accounts.destroy');
    Route::post('/settings/payment-methods', [SettingsController::class, 'storePaymentMethod'])->name('settings.payment-methods.store');
    Route::delete('/settings/payment-methods/{paymentMethod}', [SettingsController::class, 'deletePaymentMethod'])->name('settings.payment-methods.destroy');
    Route::post('/settings/payment-types', [SettingsController::class, 'storePaymentType'])->name('settings.payment-types.store');
    Route::delete('/settings/payment-types/{paymentType}', [SettingsController::class, 'deletePaymentType'])->name('settings.payment-types.destroy');
    Route::post('/settings/smtp', [SettingsController::class, 'saveSmtp'])->name('settings.smtp');
    Route::post('/settings/smtp/test', [SettingsController::class, 'testSmtp'])->name('settings.smtp.test');
    Route::post('/settings/vat', [SettingsController::class, 'saveVat'])->name('settings.vat');
    Route::post('/settings/backups', [SettingsController::class, 'createBackup'])->name('settings.backups.create');
    Route::get('/settings/backups/{filename}/download', [SettingsController::class, 'downloadBackup'])->name('settings.backups.download');
    Route::post('/settings/backups/{filename}/restore', [SettingsController::class, 'restoreBackup'])->name('settings.backups.restore');
    Route::delete('/settings/backups/{filename}', [SettingsController::class, 'deleteBackup'])->name('settings.backups.destroy');
    Route::post('/settings/backups/upload-restore', [SettingsController::class, 'uploadRestoreBackup'])->name('settings.backups.upload-restore');
    Route::post('/settings/backups/auto-toggle', [SettingsController::class, 'toggleAutoBackup'])->name('settings.backups.auto-toggle');
    Route::post('/settings/storage-link', [SettingsController::class, 'generateStorageLink'])->name('settings.storage-link');
    Route::post('/settings/clear-cache', [SettingsController::class, 'clearCache'])->name('settings.clear-cache');
});

// 5B. Group: Admin Only (destructive actions, security cards, users)
Route::middleware(['auth', 'role:admin', 'throttle:60,1'])->group(function () {
    
    // Deletions
    Route::delete('/cash-in/{cashIn}', [CashInController::class, 'destroy'])->name('cash-in.destroy');
    Route::delete('/cash-out/{cashOut}', [CashOutController::class, 'destroy'])->name('cash-out.destroy');
    Route::delete('/clients/{client}', [ClientController::class, 'destroy'])->name('clients.destroy');
    Route::delete('/expenses/{expense}', [ExpenseController::class, 'destroy'])->name('expenses.destroy');
    Route::delete('/custom-accounts/{customAccount}', [CustomAccountController::class, 'destroy'])->name('custom-accounts.destroy');
    Route::delete('/consignments/{consignment}', [ConsignmentController::class, 'destroy'])->name('consignments.destroy');

    // Users and Staff CRUD
    Route::resource('users', UsersController::class);
});

// 7. Profile routes (Breeze standard)
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';

Route::get('/clear-cache', function() {
    \Illuminate\Support\Facades\Artisan::call('view:clear');
    \Illuminate\Support\Facades\Artisan::call('route:clear');
    \Illuminate\Support\Facades\Artisan::call('config:clear');
    \Illuminate\Support\Facades\Artisan::call('cache:clear');
    return "All caches cleared successfully on cPanel!";
});

Route::get('/run-migrations', function() {
    \Illuminate\Support\Facades\Artisan::call('migrate', ['--force' => true]);
    return "Database migrations run successfully on cPanel!";
});
