<?php

use App\Http\Controllers\AuditLogController;
use App\Http\Controllers\AccountsController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\ResetPasswordController;
use App\Http\Controllers\BackupController;
use App\Http\Controllers\BrandController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\ExpiryReportController;
use App\Http\Controllers\InvoicePreviewController;
use App\Http\Controllers\GlobalSearchController;
use App\Http\Controllers\LanguageController;
use App\Http\Controllers\OpeningStockController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\PurchaseController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\ReturnController;
use App\Http\Controllers\SalesController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\Settings\BranchController;
use App\Http\Controllers\Settings\CompanyController;
use App\Http\Controllers\Settings\DocumentSequenceController;
use App\Http\Controllers\Settings\FinancialYearController;
use App\Http\Controllers\Settings\GeneralSettingController;
use App\Http\Controllers\Settings\VatSettingController;
use App\Http\Controllers\Settings\WarehouseController;
use App\Http\Controllers\StockAdjustmentController;
use App\Http\Controllers\StockLedgerController;
use App\Http\Controllers\StockTransferController;
use App\Http\Controllers\SupplierController;
use App\Http\Controllers\TreasuryController;
use App\Http\Controllers\TranslationDictionaryController;
use App\Http\Controllers\UnitController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\VanSalesController;
use Illuminate\Support\Facades\Route;

// Redirect root to dashboard or login.
Route::get('/', function () {
    return auth()->check() ? redirect()->route('dashboard') : redirect()->route('login');
});

// Authentication Routes
Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('/login', [LoginController::class, 'login']);
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');
Route::middleware('guest')->group(function () {
    Route::get('/forgot-password', [ResetPasswordController::class, 'requestForm'])->name('password.request');
    Route::post('/forgot-password', [ResetPasswordController::class, 'sendLink'])->name('password.email');
    Route::get('/reset-password/{token}', [ResetPasswordController::class, 'resetForm'])->name('password.reset');
    Route::post('/reset-password', [ResetPasswordController::class, 'reset'])->name('password.update');
});

// Language Switcher
Route::get('/lang/{locale}', [LanguageController::class, 'switchLanguage'])->name('language.switch');

// Sample Invoice Print/PDF Preview (Accessible for preview verification)
Route::get('/invoices/sample-preview', [InvoicePreviewController::class, 'showSample'])->name('invoices.sample-preview');

// Protected ERP Routes
Route::middleware(['auth'])->group(function () {

    // Dashboard
    Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('perm:dashboard.view')->name('dashboard');
    Route::get('/global-search', GlobalSearchController::class)->name('global-search');

    // Sales and fast billing
    Route::get('/sales', [SalesController::class, 'index'])->middleware('perm:sales.view')->name('sales.index');
    Route::get('/sales/create', [SalesController::class, 'create'])->middleware('perm:sales.create')->name('sales.create');
    Route::post('/sales', [SalesController::class, 'store'])->middleware('perm:sales.create')->name('sales.store');
    Route::get('/sales/{sale}', [SalesController::class, 'show'])->middleware('perm:sales.view')->name('sales.show');
    Route::post('/sales/{sale}/finalize', [SalesController::class, 'finalize'])->middleware('perm:sales.approve')->name('sales.finalize');
    Route::get('/sales/{sale}/print', [SalesController::class, 'print'])->middleware('perm:sales.print')->name('sales.print');
    Route::get('/sales/{sale}/thermal', [SalesController::class, 'thermal'])->middleware('perm:sales.print')->name('sales.thermal');
    Route::get('/sales/{sale}/pdf', [SalesController::class, 'pdf'])->middleware('perm:sales.print')->name('sales.pdf');

    // Purchases
    Route::get('/purchases', [PurchaseController::class, 'index'])->middleware('perm:purchases.view')->name('purchases.index');
    Route::get('/purchases/create', [PurchaseController::class, 'create'])->middleware('perm:purchases.create')->name('purchases.create');
    Route::post('/purchases', [PurchaseController::class, 'store'])->middleware('perm:purchases.create')->name('purchases.store');
    Route::get('/purchases/{purchase}', [PurchaseController::class, 'show'])->middleware('perm:purchases.view')->name('purchases.show');
    Route::post('/purchases/{purchase}/finalize', [PurchaseController::class, 'finalize'])->middleware('perm:purchases.approve')->name('purchases.finalize');

    // Returns / credit notes
    Route::get('/sales-returns', [ReturnController::class, 'salesIndex'])->middleware('perm:sales-return.view')->name('sales-returns.index');
    Route::get('/sales/{sale}/return', [ReturnController::class, 'salesCreate'])->middleware('perm:sales-return.create')->name('sales-returns.create');
    Route::post('/sales/{sale}/return', [ReturnController::class, 'salesStore'])->middleware('perm:sales-return.create')->name('sales-returns.store');
    Route::get('/purchase-returns', [ReturnController::class, 'purchaseIndex'])->middleware('perm:purchase-return.view')->name('purchase-returns.index');
    Route::get('/purchases/{purchase}/return', [ReturnController::class, 'purchaseCreate'])->middleware('perm:purchase-return.create')->name('purchase-returns.create');
    Route::post('/purchases/{purchase}/return', [ReturnController::class, 'purchaseStore'])->middleware('perm:purchase-return.create')->name('purchase-returns.store');

    // Accounts and treasury
    Route::get('/accounts/chart', [AccountsController::class, 'chart'])->middleware('perm:accounts.view')->name('accounts.chart');
    Route::post('/accounts/chart', [AccountsController::class, 'storeAccount'])->middleware('perm:accounts.create')->name('accounts.chart.store');
    Route::get('/accounts/journals', [AccountsController::class, 'journals'])->middleware('perm:journal.view')->name('accounts.journals');
    Route::get('/accounts/journals/create', [AccountsController::class, 'createJournal'])->middleware('perm:journal.create')->name('accounts.journals.create');
    Route::post('/accounts/journals', [AccountsController::class, 'storeJournal'])->middleware('perm:journal.create')->name('accounts.journals.store');
    Route::get('/accounts/ledger', [AccountsController::class, 'ledger'])->middleware('perm:accounts.view')->name('accounts.ledger');
    Route::get('/accounts/trial-balance', [AccountsController::class, 'trialBalance'])->middleware('perm:accounts.view_reports')->name('accounts.trial-balance');
    Route::get('/accounts/statements/{statement}', [AccountsController::class, 'financialStatement'])->middleware('perm:accounts.view_reports')->name('accounts.statement');
    Route::get('/treasury/{type}', [TreasuryController::class, 'index'])->whereIn('type', ['receipts', 'payments', 'expenses'])->name('treasury.index');
    Route::get('/treasury/{type}/create', [TreasuryController::class, 'create'])->whereIn('type', ['receipts', 'payments', 'expenses'])->name('treasury.create');
    Route::post('/treasury/{type}', [TreasuryController::class, 'store'])->whereIn('type', ['receipts', 'payments', 'expenses'])->name('treasury.store');
    Route::get('/api/customers/{customer}/open-invoices', [TreasuryController::class, 'customerDocuments'])->name('api.customer-documents');
    Route::get('/api/suppliers/{supplier}/open-purchases', [TreasuryController::class, 'supplierDocuments'])->name('api.supplier-documents');

    // Van sales
    Route::get('/van-sales', [VanSalesController::class, 'index'])->middleware('perm:van-sales.view')->name('van.index');
    Route::get('/van-sales/open', [VanSalesController::class, 'create'])->middleware('perm:van-sales.create')->name('van.create');
    Route::post('/van-sales', [VanSalesController::class, 'store'])->middleware('perm:van-sales.create')->name('van.store');
    Route::get('/van-sales/{session}', [VanSalesController::class, 'show'])->middleware('perm:van-sales.view')->name('van.show');
    Route::get('/van-sales/{session}/loading', [VanSalesController::class, 'createLoading'])->middleware('perm:van-sales.create')->name('van.loading.create');
    Route::post('/van-sales/{session}/loading', [VanSalesController::class, 'storeLoading'])->middleware('perm:van-sales.create')->name('van.loading.store');
    Route::post('/van-loading/{loading}/approve', [VanSalesController::class, 'approveLoading'])->middleware('perm:van-sales.approve')->name('van.loading.approve');
    Route::post('/van-sales/{session}/close', [VanSalesController::class, 'close'])->middleware('perm:van-sales.approve')->name('van.close');

    // Reports and backup
    Route::get('/reports', [ReportController::class, 'index'])->middleware('perm:reports.view')->name('reports.index');
    Route::get('/reports/export', [ReportController::class, 'export'])->middleware('perm:reports.export')->name('reports.export');
    Route::get('/settings/backups', [BackupController::class, 'index'])->middleware('perm:backups.view')->name('backups.index');
    Route::post('/settings/backups', [BackupController::class, 'store'])->middleware('perm:backups.create')->name('backups.store');
    Route::get('/settings/backups/{backup}/download', [BackupController::class, 'download'])->middleware('perm:backups.export')->name('backups.download');

    // User Management
    Route::get('/users', [UserController::class, 'index'])->middleware('perm:users.view')->name('users.index');
    Route::get('/users/create', [UserController::class, 'create'])->middleware('perm:users.create')->name('users.create');
    Route::post('/users', [UserController::class, 'store'])->middleware('perm:users.create')->name('users.store');
    Route::get('/users/{user}/edit', [UserController::class, 'edit'])->middleware('perm:users.edit')->name('users.edit');
    Route::match(['put','patch'], '/users/{user}', [UserController::class, 'update'])->middleware('perm:users.edit')->name('users.update');
    Route::delete('/users/{user}', [UserController::class, 'destroy'])->middleware('perm:users.delete')->name('users.destroy');

    // Role & Permission Management
    Route::get('/roles', [RoleController::class, 'index'])->middleware('perm:roles.view')->name('roles.index');
    Route::get('/roles/create', [RoleController::class, 'create'])->middleware('perm:roles.create')->name('roles.create');
    Route::post('/roles', [RoleController::class, 'store'])->middleware('perm:roles.create')->name('roles.store');
    Route::get('/roles/{role}/edit', [RoleController::class, 'edit'])->middleware('perm:roles.edit')->name('roles.edit');
    Route::match(['put','patch'], '/roles/{role}', [RoleController::class, 'update'])->middleware('perm:roles.edit')->name('roles.update');
    Route::delete('/roles/{role}', [RoleController::class, 'destroy'])->middleware('perm:roles.delete')->name('roles.destroy');

    // Settings Subsystem
    Route::prefix('settings')->name('settings.')->middleware('perm:settings.access_settings')->group(function () {
        Route::get('/company', [CompanyController::class, 'edit'])->name('company');
        Route::post('/company', [CompanyController::class, 'update'])->name('company.update');

        Route::get('/zatca', [VatSettingController::class, 'edit'])->name('zatca');
        Route::post('/zatca', [VatSettingController::class, 'update'])->name('zatca.update');

        Route::get('/general', [GeneralSettingController::class, 'edit'])->name('general');
        Route::post('/general', [GeneralSettingController::class, 'update'])->name('general.update');

        // Translation Dictionary
        Route::get('/translation-dictionary', [TranslationDictionaryController::class, 'index'])->name('translation-dictionary.index');
        Route::post('/translation-dictionary', [TranslationDictionaryController::class, 'store'])->name('translation-dictionary.store');
        Route::put('/translation-dictionary/{translationDictionary}', [TranslationDictionaryController::class, 'update'])->name('translation-dictionary.update');
        Route::delete('/translation-dictionary/{translationDictionary}', [TranslationDictionaryController::class, 'destroy'])->name('translation-dictionary.destroy');
        Route::post('/translation-dictionary/import', [TranslationDictionaryController::class, 'importProcess'])->name('translation-dictionary.import');
    });

    // Masters / Operational Settings
    Route::resource('branches', BranchController::class)->except(['create', 'show', 'edit'])->middleware('perm:settings.access_settings');
    Route::resource('warehouses', WarehouseController::class)->except(['create', 'show', 'edit'])->middleware('perm:warehouses.view');
    Route::resource('financial-years', FinancialYearController::class)->except(['create', 'show', 'edit'])->middleware('perm:settings.access_settings');
    Route::resource('document-sequences', DocumentSequenceController::class)->except(['create', 'show', 'edit'])->middleware('perm:settings.access_settings');

    // Audit Logs
    Route::get('/audit-logs', [AuditLogController::class, 'index'])->middleware('perm:audit-logs.view')->name('audit-logs.index');

    // ============================================================
    // PROMPT 2: MASTER DATA & INVENTORY FOUNDATION
    // ============================================================

    // Categories
    Route::get('/categories', [CategoryController::class, 'index'])->middleware('perm:categories.view')->name('categories.index');
    Route::get('/categories/create', [CategoryController::class, 'create'])->middleware('perm:categories.create')->name('categories.create');
    Route::post('/categories', [CategoryController::class, 'store'])->middleware('perm:categories.create')->name('categories.store');
    Route::get('/categories/{category}/edit', [CategoryController::class, 'edit'])->middleware('perm:categories.edit')->name('categories.edit');
    Route::put('/categories/{category}', [CategoryController::class, 'update'])->middleware('perm:categories.edit')->name('categories.update');

    // Brands
    Route::get('/brands', [BrandController::class, 'index'])->middleware('perm:products.view')->name('brands.index');
    Route::post('/brands', [BrandController::class, 'store'])->middleware('perm:products.create')->name('brands.store');
    Route::put('/brands/{brand}', [BrandController::class, 'update'])->middleware('perm:products.edit')->name('brands.update');

    // Units
    Route::get('/units', [UnitController::class, 'index'])->middleware('perm:units.view')->name('units.index');
    Route::post('/units', [UnitController::class, 'store'])->middleware('perm:units.create')->name('units.store');
    Route::put('/units/{unit}', [UnitController::class, 'update'])->middleware('perm:units.edit')->name('units.update');

    // Products
    Route::get('/products', [ProductController::class, 'index'])->middleware('perm:products.view')->name('products.index');
    Route::get('/products/create', [ProductController::class, 'create'])->middleware('perm:products.create')->name('products.create');
    Route::post('/products', [ProductController::class, 'store'])->middleware('perm:products.create')->name('products.store');
    Route::get('/products/import', [ProductController::class, 'importPage'])->middleware('perm:products.create')->name('products.import');
    Route::post('/products/import', [ProductController::class, 'importProcess'])->middleware('perm:products.create')->name('products.import.process');
    Route::get('/products/import/template', [ProductController::class, 'importTemplate'])->middleware('perm:products.create')->name('products.import.template');
    Route::get('/products/export', [ProductController::class, 'export'])->middleware('perm:products.export')->name('products.export');
    Route::get('/products/barcodes/print', [ProductController::class, 'printBarcodes'])->middleware('perm:products.print')->name('products.barcodes.print');
    Route::get('/products/{product}', [ProductController::class, 'show'])->middleware('perm:products.view')->name('products.show');
    Route::get('/products/{product}/edit', [ProductController::class, 'edit'])->middleware('perm:products.edit')->name('products.edit');
    Route::put('/products/{product}', [ProductController::class, 'update'])->middleware('perm:products.edit')->name('products.update');
    Route::get('/products/{product}/price-history', [ProductController::class, 'priceHistory'])->middleware('perm:products.view')->name('products.price-history');

    // Customers
    Route::get('/customers', [CustomerController::class, 'index'])->middleware('perm:customers.view')->name('customers.index');
    Route::get('/customers/create', [CustomerController::class, 'create'])->middleware('perm:customers.create')->name('customers.create');
    Route::post('/customers', [CustomerController::class, 'store'])->middleware('perm:customers.create')->name('customers.store');
    Route::get('/customers/export', [CustomerController::class, 'export'])->middleware('perm:customers.export')->name('customers.export');
    Route::post('/customers/import', [CustomerController::class, 'importProcess'])->middleware('perm:customers.create')->name('customers.import');
    Route::get('/customers/{customer}', [CustomerController::class, 'show'])->middleware('perm:customers.view')->name('customers.show');
    Route::get('/customers/{customer}/edit', [CustomerController::class, 'edit'])->middleware('perm:customers.edit')->name('customers.edit');
    Route::put('/customers/{customer}', [CustomerController::class, 'update'])->middleware('perm:customers.edit')->name('customers.update');
    Route::get('/customers/{customer}/statement', [CustomerController::class, 'statement'])->middleware('perm:customers.view')->name('customers.statement');

    // Suppliers
    Route::get('/suppliers', [SupplierController::class, 'index'])->middleware('perm:suppliers.view')->name('suppliers.index');
    Route::get('/suppliers/create', [SupplierController::class, 'create'])->middleware('perm:suppliers.create')->name('suppliers.create');
    Route::post('/suppliers', [SupplierController::class, 'store'])->middleware('perm:suppliers.create')->name('suppliers.store');
    Route::get('/suppliers/export', [SupplierController::class, 'export'])->middleware('perm:suppliers.export')->name('suppliers.export');
    Route::post('/suppliers/import', [SupplierController::class, 'importProcess'])->middleware('perm:suppliers.create')->name('suppliers.import');
    Route::get('/suppliers/{supplier}/edit', [SupplierController::class, 'edit'])->middleware('perm:suppliers.edit')->name('suppliers.edit');
    Route::put('/suppliers/{supplier}', [SupplierController::class, 'update'])->middleware('perm:suppliers.edit')->name('suppliers.update');
    Route::get('/suppliers/{supplier}/statement', [SupplierController::class, 'statement'])->middleware('perm:suppliers.view')->name('suppliers.statement');

    // Inventory: Opening Stock
    Route::get('/inventory/opening-stock', [OpeningStockController::class, 'index'])->middleware('perm:inventory.view')->name('opening-stock.index');
    Route::get('/inventory/opening-stock/bulk', [OpeningStockController::class, 'bulk'])->middleware('perm:inventory.create')->name('opening-stock.bulk');
    Route::post('/inventory/opening-stock', [OpeningStockController::class, 'store'])->middleware('perm:inventory.create')->name('opening-stock.store');
    Route::get('/inventory/opening-stock/{inventoryOpening}', [OpeningStockController::class, 'show'])->middleware('perm:inventory.view')->name('opening-stock.show');
    Route::post('/inventory/opening-stock/{inventoryOpening}/approve', [OpeningStockController::class, 'approve'])->middleware('perm:inventory.approve')->name('opening-stock.approve');

    // Inventory: Current Stock & Stock Ledger
    Route::get('/inventory/current-stock', [StockLedgerController::class, 'currentStock'])->middleware('perm:inventory.view')->name('current-stock.index');
    Route::get('/inventory/stock-ledger', [StockLedgerController::class, 'index'])->middleware('perm:inventory.view')->name('stock-ledger.index');
    Route::get('/inventory/stock-ledger/export', [StockLedgerController::class, 'export'])->middleware('perm:inventory.export')->name('stock-ledger.export');
    Route::get('/inventory/stock-ledger/product/{product}', [StockLedgerController::class, 'byWarehouse'])->middleware('perm:inventory.view')->name('stock-ledger.by-warehouse');

    // Inventory: Stock Adjustments
    Route::get('/inventory/stock-adjustments', [StockAdjustmentController::class, 'index'])->middleware('perm:stock-adjustment.view')->name('stock-adjustments.index');
    Route::get('/inventory/stock-adjustments/create', [StockAdjustmentController::class, 'create'])->middleware('perm:stock-adjustment.create')->name('stock-adjustments.create');
    Route::post('/inventory/stock-adjustments', [StockAdjustmentController::class, 'store'])->middleware('perm:stock-adjustment.create')->name('stock-adjustments.store');
    Route::get('/inventory/stock-adjustments/{stockAdjustment}', [StockAdjustmentController::class, 'show'])->middleware('perm:stock-adjustment.view')->name('stock-adjustments.show');
    Route::post('/inventory/stock-adjustments/{stockAdjustment}/approve', [StockAdjustmentController::class, 'approve'])->middleware('perm:stock-adjustment.approve')->name('stock-adjustments.approve');

    // Inventory: Stock Transfers
    Route::get('/inventory/stock-transfers', [StockTransferController::class, 'index'])->middleware('perm:stock-transfer.view')->name('stock-transfers.index');
    Route::get('/inventory/stock-transfers/create', [StockTransferController::class, 'create'])->middleware('perm:stock-transfer.create')->name('stock-transfers.create');
    Route::post('/inventory/stock-transfers', [StockTransferController::class, 'store'])->middleware('perm:stock-transfer.create')->name('stock-transfers.store');
    Route::get('/inventory/stock-transfers/{stockTransfer}', [StockTransferController::class, 'show'])->middleware('perm:stock-transfer.view')->name('stock-transfers.show');
    Route::post('/inventory/stock-transfers/{stockTransfer}/approve', [StockTransferController::class, 'approve'])->middleware('perm:stock-transfer.approve')->name('stock-transfers.approve');
    Route::post('/inventory/stock-transfers/{stockTransfer}/receive', [StockTransferController::class, 'receive'])->middleware('perm:stock-transfer.approve')->name('stock-transfers.receive');

    // Inventory: Expiry Report
    Route::get('/inventory/expiry-report', [ExpiryReportController::class, 'index'])->middleware('perm:inventory.view_reports')->name('expiry-report.index');

    // AJAX API endpoints (prefixed for clarity)
    Route::prefix('api')->name('api.')->group(function () {
        Route::get('/categories', [CategoryController::class, 'apiList'])->middleware('perm:categories.view')->name('categories');
        Route::post('/translate/suggest', [CategoryController::class, 'translateSuggest'])->middleware('perm:categories.create')->name('translate.suggest');
        Route::get('/brands', [BrandController::class, 'apiList'])->middleware('perm:products.view')->name('brands');
        Route::get('/units', [UnitController::class, 'apiList'])->middleware('perm:units.view')->name('units');
        Route::get('/products/search', [ProductController::class, 'quickSearch'])->middleware('perm:products.view')->name('products.search');
        Route::post('/products/translate', [ProductController::class, 'translateSuggest'])->middleware('perm:products.create')->name('products.translate');
        Route::get('/products/duplicate-check', [ProductController::class, 'duplicateCheck'])->middleware('perm:products.create')->name('products.duplicate-check');
        Route::get('/customers', [CustomerController::class, 'apiList'])->middleware('perm:customers.view')->name('customers');
        Route::post('/customers/quick', [CustomerController::class, 'quickStore'])->middleware('perm:customers.create')->name('customers.quick');
        Route::get('/suppliers', [SupplierController::class, 'apiList'])->middleware('perm:suppliers.view')->name('suppliers');
        Route::post('/suppliers/quick', [SupplierController::class, 'quickStore'])->middleware('perm:suppliers.create')->name('suppliers.quick');
    });
});
