<?php

use App\Http\Controllers\Auth\LoginController;
use App\Http\Middleware\InstallMiddleware;
use App\Http\Middleware\RedirectIfInstalled;
use App\Http\Middleware\SetLocale;
use App\Http\Middleware\CheckModule;
use App\Livewire\InstallWizard;
use App\Livewire\Products\ProductForm;
use App\Livewire\Products\ProductsIndex;
use App\Livewire\Categories\CategoriesIndex;
use App\Livewire\Categories\CategoryForm;
use App\Livewire\Customers\CustomersIndex;
use App\Livewire\Customers\CustomerForm;
use App\Livewire\Suppliers\SuppliersIndex;
use App\Livewire\Suppliers\SupplierForm;
use App\Livewire\PointOfSale;
use App\Livewire\Sales\SalesIndex;
use App\Livewire\PurchaseOrders\PurchaseOrdersIndex;
use App\Livewire\PurchaseOrders\PurchaseOrderForm;
use App\Livewire\PurchaseOrders\PurchaseOrderView;
use App\Livewire\PurchaseOrders\ReceivePurchaseOrder;
use App\Livewire\Inventory\StockOverview;
use App\Livewire\Inventory\StockAdjustments;
use App\Livewire\Inventory\StockTransfers;
use App\Livewire\Inventory\LowStock;
use App\Livewire\Reports\DailySalesReport;
use App\Livewire\Reports\CustomerCreditReport;
use App\Livewire\Reports\InventoryReport;
use App\Livewire\Reports\SessionReport;
use App\Livewire\Reports\ProfitLossReport;
use App\Livewire\Reports\ProductSalesReport;
use App\Livewire\Reports\PurchaseReport;
use App\Livewire\Reports\StockAdjustmentReport;
use App\Livewire\Reports\PartnerStatementReport;
use App\Livewire\Reports\PaymentCollectionReport;
use App\Livewire\Reports\StockByLocationReport;
use App\Livewire\Reports\BatchExpiryReport;
use App\Livewire\Reports\FifoCostLayersReport;
use App\Livewire\Reports\AdjustmentsByLocationReport;
use App\Livewire\Settings\GeneralSettings;
use App\Livewire\Settings\PaymentMethods;
use App\Livewire\Settings\UsersManagement;
use App\Livewire\Settings\BranchesManagement;
use App\Livewire\Settings\LocationsManagement;
use App\Livewire\Settings\UnitsManagement;
use App\Livewire\Settings\ModuleSettingsPage;
use App\Livewire\Settings\BackupSettings;
use App\Livewire\Accounting\ChartOfAccounts;
use App\Livewire\Accounting\JournalEntriesIndex;
use App\Livewire\Accounting\JournalEntryForm;
use App\Livewire\Accounting\TrialBalance;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

// Installation Route
Route::get('/install', InstallWizard::class)
    ->name('install')
    ->middleware([RedirectIfInstalled::class, SetLocale::class]);

// Language Switch
Route::get('/locale/{locale}', function (string $locale) {
    if (in_array($locale, ['en', 'ar'])) {
        Session::put('locale', $locale);
        if (auth()->check()) {
            auth()->user()->update(['locale' => $locale]);
        }
    }
    return back();
})->name('locale.switch');

// Routes that require installation
Route::middleware([InstallMiddleware::class, SetLocale::class])->group(function () {
    
    // Login/Auth Routes
    Route::middleware('guest')->group(function () {
        Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
        Route::post('/login', [LoginController::class, 'login']);
    });

    Route::get('/', function () {
        if (!File::exists(storage_path('installed'))) {
            return redirect()->route('install');
        }
        return redirect()->route('dashboard');
    });

    // Authenticated Routes
    Route::middleware(['auth'])->group(function () {
        
        // Logout
        Route::post('/logout', [LoginController::class, 'logout'])->name('logout');
        
        // Dashboard
        Route::get('/dashboard', \App\Livewire\Dashboard::class)->name('dashboard');

        // Global Search

        Route::get('/search', function () {
            return view('search.index');
        })->name('search');

        // Notifications
        Route::prefix('notifications')->name('notifications.')->group(function () {
            Route::get('/', function () {
                return view('notifications.index');
            })->name('index');
            Route::get('/mark-all-read', function () {
                return back();
            })->name('mark-all-read');
        });

        // Profile
        Route::prefix('profile')->name('profile.')->group(function () {
            Route::get('/', function () {
                return view('profile.edit');
            })->name('edit');
        });

        Route::get('/password/change', function () {
            return view('auth.password-change');
        })->name('password.change');

        // POS Routes
        Route::prefix('pos')->name('pos.')->middleware('module:pos')->group(function () {
            Route::get('/', PointOfSale::class)->name('index');
            Route::get('/sales-history', \App\Livewire\Pos\SalesHistory::class)->name('sales-history');
            Route::get('/returns/{sale?}', \App\Livewire\Pos\Returns::class)->name('returns');
        });

        // Sales Routes
        Route::prefix('sales')->name('sales.')->middleware('module:sales')->group(function () {
            Route::get('/', SalesIndex::class)->name('index');
            Route::get('/create', \App\Livewire\Sales\CreateSale::class)->name('create');
            Route::get('/daily/create', \App\Livewire\Sales\CreateDailySale::class)->name('daily.create');
            Route::get('/daily', \App\Livewire\Sales\DailySalesIndex::class)->name('daily.index');
            
            Route::prefix('returns')->name('returns.')->group(function () {
                Route::get('/', \App\Livewire\Sales\SalesReturnsIndex::class)->name('index');
            });
        });

        // Products Routes
        Route::prefix('products')->name('products.')->middleware('module:products')->group(function () {
            Route::get('/', ProductsIndex::class)->name('index');
            Route::get('/create', ProductForm::class)->name('create');
            Route::get('/{id}/edit', ProductForm::class)->name('edit');
            Route::get('/barcodes', function () {
                return view('products.barcodes');
            })->name('barcodes');
        });

        // Categories Routes
        Route::prefix('categories')->name('categories.')->middleware('module:products')->group(function () {
            Route::get('/', CategoriesIndex::class)->name('index');
            Route::get('/create', CategoryForm::class)->name('create');
            Route::get('/{id}/edit', CategoryForm::class)->name('edit');
        });

        // Partners Routes
        Route::prefix('partners')->name('partners.')->middleware('module:partners')->group(function () {
            Route::get('/', \App\Livewire\Partners\PartnersIndex::class)->name('index');
            Route::get('/types', \App\Livewire\Partners\PartnerTypesIndex::class)->name('types');
            Route::get('/create', \App\Livewire\Partners\PartnerForm::class)->name('create');
            Route::get('/{partner}/edit', \App\Livewire\Partners\PartnerForm::class)->name('edit');
        });

        /* 
        // Legacy Routes - Redirect or Keep for backward compatibility if needed? 
        // For now, we remove them as requested to "merge".
        // Customers Routes (Removed)
        // Suppliers Routes (Removed)
        */

        // Inventory Routes
        Route::prefix('inventory')->name('inventory.')->middleware('module:inventory')->group(function () {
            Route::get('/', StockOverview::class)->name('index');
            Route::get('/adjustments', StockAdjustments::class)->name('adjustments');
            Route::get('/transfers', StockTransfers::class)->name('transfers');
            Route::get('/low-stock', LowStock::class)->name('low-stock');
        });

        // Purchases Routes
        Route::prefix('purchases')->name('purchases.')->middleware('module:purchases')->group(function () {
            Route::get('/', PurchaseOrdersIndex::class)->name('index');
            Route::get('/create', PurchaseOrderForm::class)->name('create');
            
            Route::get('/{id}/edit', PurchaseOrderForm::class)->name('edit');
            Route::get('/{id}', PurchaseOrderView::class)->name('show');
            Route::get('/{id}/receive', ReceivePurchaseOrder::class)->name('receive');
        });
        
        // Purchase Returns Routes (separate to use singular naming)
        Route::prefix('purchase/returns')->name('purchase.returns.')->middleware('module:purchases')->group(function () {
            Route::get('/', \App\Livewire\PurchaseReturns\Index::class)->name('index');
            Route::get('/create', \App\Livewire\PurchaseReturns\Create::class)->name('create');
        });

        // Accounting Routes
        Route::prefix('accounting')->name('accounting.')->middleware('module:accounting')->group(function () {
            Route::get('/chart-of-accounts', ChartOfAccounts::class)->name('chart');
            Route::get('/journals', JournalEntriesIndex::class)->name('journals');
            Route::get('/journals/create', JournalEntryForm::class)->name('journals.create');
            Route::get('/journals/{id}/edit', JournalEntryForm::class)->name('journals.edit');
            Route::get('/trial-balance', TrialBalance::class)->name('trial-balance');
            Route::get('/customer-settlements', \App\Livewire\Accounting\CustomerSettlements::class)->name('customer-settlements');
            Route::get('/supplier-payments', \App\Livewire\Accounting\SupplierPayments::class)->name('supplier-payments');
            Route::get('/general-ledger', \App\Livewire\Accounting\GeneralLedger::class)->name('general-ledger');
            Route::get('/partner-ledger', \App\Livewire\Accounting\PartnerLedger::class)->name('partner-ledger');
        });

        Route::prefix('sessions')->name('sessions.')->group(function () {
            Route::get('/pending', function () {
                return view('sessions.pending');
            })->name('pending');
        });

        // Reports Routes
        Route::prefix('reports')->name('reports.')->middleware('module:reports')->group(function () {
            Route::get('/daily-sales', DailySalesReport::class)->name('daily-sales');
            Route::get('/product-sales', ProductSalesReport::class)->name('product-sales');
            Route::get('/customer-credit', CustomerCreditReport::class)->name('customer-credit');
            Route::get('/inventory', InventoryReport::class)->name('inventory');
            Route::get('/sessions', SessionReport::class)->name('sessions');
            Route::get('/profit-loss', ProfitLossReport::class)->name('profit-loss');
            Route::get('/purchases', PurchaseReport::class)->name('purchases');
            Route::get('/stock-adjustments', StockAdjustmentReport::class)->name('stock-adjustments');
            Route::get('/partner-statement', PartnerStatementReport::class)->name('partner-statement');
            Route::get('/payment-collection', PaymentCollectionReport::class)->name('payment-collection');
            Route::get('/stock-by-location', StockByLocationReport::class)->name('stock-by-location');
            Route::get('/batch-expiry', BatchExpiryReport::class)->name('batch-expiry');
            Route::get('/fifo-cost-layers', FifoCostLayersReport::class)->name('fifo-cost-layers');
            Route::get('/adjustments-by-location', AdjustmentsByLocationReport::class)->name('adjustments-by-location');
        });

        // Export Routes
        Route::prefix('export')->name('export.')->group(function () {
            Route::get('/sales-history', [\App\Http\Controllers\ExportController::class, 'salesHistory'])->name('sales-history');
            Route::get('/sales-returns', [\App\Http\Controllers\ExportController::class, 'salesReturns'])->name('sales-returns');
            Route::get('/purchase-orders', [\App\Http\Controllers\ExportController::class, 'purchaseOrders'])->name('purchase-orders');
            Route::get('/purchase-returns', [\App\Http\Controllers\ExportController::class, 'purchaseReturns'])->name('purchase-returns');
            Route::get('/inventory-stock', [\App\Http\Controllers\ExportController::class, 'inventoryStock'])->name('inventory-stock');
            Route::get('/stock-adjustments', [\App\Http\Controllers\ExportController::class, 'stockAdjustments'])->name('stock-adjustments');
            Route::get('/journal-entries', [\App\Http\Controllers\ExportController::class, 'journalEntries'])->name('journal-entries');
            Route::get('/general-ledger', [\App\Http\Controllers\ExportController::class, 'generalLedger'])->name('general-ledger');
            Route::get('/partner-ledger', [\App\Http\Controllers\ExportController::class, 'partnerLedger'])->name('partner-ledger');
            Route::get('/customer-settlements', [\App\Http\Controllers\ExportController::class, 'customerSettlements'])->name('customer-settlements');
            Route::get('/supplier-payments', [\App\Http\Controllers\ExportController::class, 'supplierPayments'])->name('supplier-payments');
            Route::get('/products', [\App\Http\Controllers\ExportController::class, 'products'])->name('products');
            Route::get('/partners', [\App\Http\Controllers\ExportController::class, 'partners'])->name('partners');
        });

        // PDF Routes
        Route::prefix('pdf')->name('pdf.')->group(function () {
            Route::get('/sale/{sale}/invoice', [\App\Http\Controllers\PDFController::class, 'saleInvoice'])->name('sale.invoice');
            Route::get('/purchase/{order}/order', [\App\Http\Controllers\PDFController::class, 'purchaseOrder'])->name('purchase.order');
            Route::get('/return/{return}/receipt', [\App\Http\Controllers\PDFController::class, 'saleReturn'])->name('return.receipt');
            Route::get('/partner/statement', [\App\Http\Controllers\PDFController::class, 'partnerStatement'])->name('partner.statement');
            Route::get('/report/daily-sales', [\App\Http\Controllers\PDFController::class, 'dailySalesReport'])->name('report.daily-sales');
            Route::get('/report/inventory', [\App\Http\Controllers\PDFController::class, 'inventoryReport'])->name('report.inventory');
            Route::get('/report/adjustments-by-location', [\App\Http\Controllers\PDFController::class, 'adjustmentsByLocation'])->name('report.adjustments-by-location');
            Route::get('/report/batch-expiry', [\App\Http\Controllers\PDFController::class, 'batchExpiry'])->name('report.batch-expiry');
            Route::get('/report/customer-credit', [\App\Http\Controllers\PDFController::class, 'customerCredit'])->name('report.customer-credit');
            Route::get('/report/fifo-layers', [\App\Http\Controllers\PDFController::class, 'fifoCostLayers'])->name('report.fifo-layers');
            Route::get('/report/payment-collection', [\App\Http\Controllers\PDFController::class, 'paymentCollection'])->name('report.payment-collection');
            Route::get('/report/product-sales', [\App\Http\Controllers\PDFController::class, 'productSales'])->name('report.product-sales');
            Route::get('/report/profit-loss', [\App\Http\Controllers\PDFController::class, 'profitLoss'])->name('report.profit-loss');
            Route::get('/report/purchases', [\App\Http\Controllers\PDFController::class, 'purchaseReport'])->name('report.purchases');
            Route::get('/report/sessions', [\App\Http\Controllers\PDFController::class, 'sessionReport'])->name('report.sessions');
            Route::get('/report/stock-adjustment', [\App\Http\Controllers\PDFController::class, 'stockAdjustment'])->name('report.stock-adjustment');
            Route::get('/report/stock-by-location', [\App\Http\Controllers\PDFController::class, 'stockByLocation'])->name('report.stock-by-location');
            Route::get('/report/trial-balance', [\App\Http\Controllers\PDFController::class, 'trialBalance'])->name('report.trial-balance');

            Route::prefix('accounting')->name('accounting.')->group(function () {
                Route::get('/general-ledger', [\App\Http\Controllers\PDFController::class, 'generalLedger'])->name('general-ledger');
                Route::get('/general-ledger/account', [\App\Http\Controllers\PDFController::class, 'generalLedgerAccountDetails'])->name('general-ledger.account');
                Route::get('/partner-ledger', [\App\Http\Controllers\PDFController::class, 'partnerLedger'])->name('partner-ledger');
                Route::get('/partner-ledger/details', [\App\Http\Controllers\PDFController::class, 'partnerLedgerDetails'])->name('partner-ledger.details');
            });
        });

        // Settings Routes
        Route::prefix('settings')->name('settings.')->group(function () {
            Route::get('/general', GeneralSettings::class)->name('general');
            Route::get('/accounting', \App\Livewire\Settings\AccountingSettings::class)->name('accounting');
            Route::get('/payment-methods', PaymentMethods::class)->name('payment-methods');
            Route::get('/users', UsersManagement::class)->name('users');
            Route::get('/branches', BranchesManagement::class)->name('branches');
            Route::get('/backup', BackupSettings::class)->name('backup');
            Route::get('/roles', \App\Livewire\Settings\RolesIndex::class)->name('roles');
            Route::get('/categories-accounting', \App\Livewire\Settings\CategoryAccountingConfig::class)->name('categories.accounting');
            Route::get('/locations', LocationsManagement::class)->name('locations');
            Route::get('/units', UnitsManagement::class)->name('units');
            Route::get('/modules', ModuleSettingsPage::class)->name('modules');
            Route::get('/system', \App\Livewire\Settings\SystemUpdate::class)->name('system');
            
        });

        Route::get('/switch-branch/{branch}', function ($branch) {
            return back();
        })->name('switch-branch');

        Route::prefix('users')->name('users.')->group(function () {
            Route::get('/', function () {
                return view('users.index');
            })->name('index');
        });

        Route::prefix('payment-methods')->name('payment-methods.')->group(function () {
            Route::get('/', function () {
                return view('payment-methods.index');
            })->name('index');
        });
    });
});
