<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\SettingController;

use App\Http\Controllers\AuthController;

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

Route::middleware('guest')->group(function () {
    Route::get('login', [AuthController::class, 'create'])->name('login');
    Route::post('login', [AuthController::class, 'store'])->middleware('throttle:5,1');
    Route::get('login/otp', [AuthController::class, 'showOtpForm'])->name('login.otp');
    Route::post('login/otp', [AuthController::class, 'verifyOtp'])->name('login.otp.verify');
});

// Global Search
Route::get('/global-search', [App\Http\Controllers\SearchController::class, 'search'])->name('global.search')->middleware('auth');

// Client Portal (Passwordless)
// Auth Routes
Route::get('/portal/login', [\App\Http\Controllers\Portal\PortalAuthController::class, 'showLoginForm'])->name('portal.login');
Route::post('/portal/login', [\App\Http\Controllers\Portal\PortalAuthController::class, 'login'])->name('portal.login.submit');

Route::group(['prefix' => 'portal', 'as' => 'portal.', 'middleware' => ['portal.auth']], function () {
    Route::get('/{token}', [\App\Http\Controllers\Portal\ClientPortalController::class, 'index'])->name('index');
    Route::get('/{token}/invoices', [\App\Http\Controllers\Portal\ClientPortalController::class, 'invoices'])->name('invoices');
    Route::get('/{token}/quotations', [\App\Http\Controllers\Portal\ClientPortalController::class, 'quotations'])->name('quotations');
    Route::get('/{token}/services', [\App\Http\Controllers\Portal\ClientPortalController::class, 'services'])->name('services');

    // Portal Tickets
    Route::get('/{token}/tickets', [\App\Http\Controllers\Portal\ClientPortalController::class, 'tickets'])->name('tickets.index');
    Route::get('/{token}/tickets/create', [\App\Http\Controllers\Portal\ClientPortalController::class, 'createTicket'])->name('tickets.create');
    Route::post('/{token}/tickets', [\App\Http\Controllers\Portal\ClientPortalController::class, 'storeTicket'])->name('tickets.store');
    Route::get('/{token}/tickets/{ticket}', [\App\Http\Controllers\Portal\ClientPortalController::class, 'showTicket'])->name('tickets.show');
    Route::post('/{token}/tickets/{ticket}/reply', [\App\Http\Controllers\Portal\ClientPortalController::class, 'replyTicket'])->name('tickets.reply');
});

Route::post('logout', [AuthController::class, 'destroy'])
    ->middleware('auth')
    ->name('logout');

Route::middleware([
    'auth',
])->group(function () {

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

    // Programmer Dashboard (for users with 'view own projects' permission only)
    Route::prefix('programmer')->name('programmer.')->group(function () {
        Route::get('/', [\App\Http\Controllers\ProgrammerDashboardController::class, 'index'])->name('dashboard');
        Route::get('/payments', [\App\Http\Controllers\ProgrammerDashboardController::class, 'payments'])->name('payments');
        Route::get('/project/{project}', [\App\Http\Controllers\ProgrammerDashboardController::class, 'showProject'])->name('project');
        Route::patch('/project/{project}/progress', [\App\Http\Controllers\ProgrammerDashboardController::class, 'updateProgress'])->name('update-progress');
    });


    // Products
    Route::group(['prefix' => 'products', 'as' => 'products.'], function () {
        Route::get('import', [\App\Http\Controllers\ProductController::class, 'import'])->name('import');
        Route::post('import', [\App\Http\Controllers\ProductController::class, 'storeImport'])->name('import.store');
    });
    Route::resource('products', \App\Http\Controllers\ProductController::class);

    Route::resource('units', \App\Http\Controllers\Accounting\UnitController::class);

    // Customers
    Route::prefix('customers')->name('customers.')->group(function () {
        Route::get('/', [CustomerController::class, 'index'])->name('index');
        Route::get('/create', [CustomerController::class, 'create'])->name('create');
        Route::post('/', [CustomerController::class, 'store'])->name('store');
        Route::get('/export', [CustomerController::class, 'export'])->name('export'); // Before show
        Route::post('/sync-whmcs', [CustomerController::class, 'syncWhmcs'])->name('sync-whmcs');
        Route::get('/{customer}', [CustomerController::class, 'show'])->name('show');
        Route::get('/{customer}/edit', [CustomerController::class, 'edit'])->name('edit');
        Route::put('/{customer}', [CustomerController::class, 'update'])->name('update');
        Route::delete('/{customer}', [CustomerController::class, 'destroy'])->name('destroy');

        // Customer sub-actions
        Route::post('/{customer}/notes', [CustomerController::class, 'addNote'])->name('notes.store');
        Route::put('/{customer}/notes/{note}', [CustomerController::class, 'updateNote'])->name('notes.update');
        Route::delete('/{customer}/notes/{note}', [CustomerController::class, 'deleteNote'])->name('notes.destroy');

        Route::post('/{customer}/documents', [CustomerController::class, 'uploadDocument'])->name('documents.store');
        Route::delete('/{customer}/documents/{document}', [CustomerController::class, 'deleteDocument'])->name('documents.destroy');
        Route::post('/{customer}/whatsapp', [CustomerController::class, 'sendWhatsApp'])->name('whatsapp.send');
        Route::post('/{customer}/portal-invite', [CustomerController::class, 'sendPortalInvite'])->name('portal.invite');
        Route::post('/{customer}/wallet', [CustomerController::class, 'storeWalletTransaction'])->name('wallet.store');
        Route::delete('/{customer}/wallet/{transaction}', [CustomerController::class, 'destroyWalletTransaction'])->name('wallet.destroy');
        Route::put('/{customer}/wallet/{transaction}', [CustomerController::class, 'updateWalletTransaction'])->name('wallet.update');
        Route::post('/{customer}/loyalty', [CustomerController::class, 'storeLoyaltyTransaction'])->name('loyalty.store');
        Route::delete('/{customer}/loyalty/{transaction}', [CustomerController::class, 'destroyLoyaltyTransaction'])->name('loyalty.destroy');
        Route::put('/{customer}/loyalty/{transaction}', [CustomerController::class, 'updateLoyaltyTransaction'])->name('loyalty.update');
    });

    // Settings
    Route::prefix('settings')->name('settings.')->group(function () {
        Route::get('/', [SettingController::class, 'index'])->name('index');

        // Backup
        Route::get('/backup', [App\Http\Controllers\Settings\BackupController::class, 'index'])->name('backup.index');
        Route::put('/backup', [App\Http\Controllers\Settings\BackupController::class, 'update'])->name('backup.update');
        Route::post('/backup/download', [App\Http\Controllers\Settings\BackupController::class, 'download'])->name('backup.download');


        Route::post('/general', [SettingController::class, 'updateGeneral'])->name('general.update');

        Route::post('/whmcs', [SettingController::class, 'updateWhmcs'])->name('whmcs.update');
        Route::post('/whmcs/test', [SettingController::class, 'testWhmcs'])->name('whmcs.test');

        Route::post('/close-month', [SettingController::class, 'closeMonth'])->name('close-month');

        Route::post('/wasender', [SettingController::class, 'updateWaSender'])->name('wasender.update');
        Route::post('/wasender/test', [SettingController::class, 'testWaSender'])->name('wasender.test');

        Route::post('/smtp', [SettingController::class, 'updateSmtp'])->name('smtp.update');
        Route::post('/smtp/test', [SettingController::class, 'testSmtp'])->name('smtp.test');

        // Email Templates
        Route::post('/templates', [SettingController::class, 'storeTemplate'])->name('templates.store');
        Route::put('/templates/{template}', [SettingController::class, 'updateTemplate'])->name('templates.update');
        Route::delete('/templates/{template}', [SettingController::class, 'destroyTemplate'])->name('templates.destroy');

        // User & Role Management
        Route::resource('users', \App\Http\Controllers\Settings\UserController::class);
        Route::resource('roles', \App\Http\Controllers\Settings\RoleController::class);

        // System Management
        Route::prefix('system')->group(function () {
            Route::resource('whatsapp', \App\Http\Controllers\Settings\WhatsAppTemplateController::class)->names('whatsapp');

            Route::get('updates', [\App\Http\Controllers\Settings\SystemUpdateController::class, 'index'])->name('updates.index');
            Route::post('updates/upload', [\App\Http\Controllers\Settings\SystemUpdateController::class, 'upload'])->name('updates.upload');
            Route::post('updates/run', [\App\Http\Controllers\Settings\SystemUpdateController::class, 'run'])->name('updates.run');
        });

        // Customer Groups
        Route::resource('customer-groups', \App\Http\Controllers\Settings\CustomerGroupController::class);
    });

    // Loyalty Dashboard
    Route::get('loyalty', [\App\Http\Controllers\LoyaltyController::class, 'index'])->name('loyalty.index');

    // Accounting
    Route::prefix('accounting')->name('accounting.')->group(function () {
        // Accounting Settings
        Route::get('settings', [\App\Http\Controllers\Accounting\AccountingSettingsController::class, 'index'])->name('settings.index');
        Route::post('settings/closing', [\App\Http\Controllers\Accounting\AccountingSettingsController::class, 'updateClosing'])->name('settings.closing');

        // Categories
        Route::post('categories', [\App\Http\Controllers\Accounting\AccountingSettingsController::class, 'storeCategory'])->name('categories.store');
        Route::put('categories/{category}', [\App\Http\Controllers\Accounting\AccountingSettingsController::class, 'updateCategory'])->name('categories.update');
        Route::delete('categories/{category}', [\App\Http\Controllers\Accounting\AccountingSettingsController::class, 'destroyCategory'])->name('categories.destroy');

        // Treasuries
        Route::resource('treasuries', \App\Http\Controllers\Accounting\TreasuryController::class);
        Route::resource('warehouses', \App\Http\Controllers\Accounting\WarehouseController::class); // Added Warehouses
        Route::post('treasuries/transfer', [\App\Http\Controllers\Accounting\TreasuryController::class, 'storeTransfer'])->name('treasuries.transfer');
        Route::post('treasuries/transaction', [\App\Http\Controllers\Accounting\TreasuryController::class, 'storeTransaction'])->name('treasuries.transaction');
        Route::get('treasuries/vouchers/{transaction}/print', [\App\Http\Controllers\Accounting\TreasuryController::class, 'printVoucher'])->name('treasuries.vouchers.print');

        // Treasuries
        Route::resource('treasuries', \App\Http\Controllers\Accounting\TreasuryController::class);
        Route::resource('warehouses', \App\Http\Controllers\Accounting\WarehouseController::class); // Added Warehouses
        Route::post('treasuries/transfer', [\App\Http\Controllers\Accounting\TreasuryController::class, 'storeTransfer'])->name('treasuries.transfer');
        Route::post('treasuries/transaction', [\App\Http\Controllers\Accounting\TreasuryController::class, 'storeTransaction'])->name('treasuries.transaction');
        Route::get('treasuries/vouchers/{transaction}/print', [\App\Http\Controllers\Accounting\TreasuryController::class, 'printVoucher'])->name('treasuries.vouchers.print');

        // Transactions Log
        Route::resource('transactions', \App\Http\Controllers\Accounting\FinancialTransactionController::class)->only(['index', 'destroy']);

        // Invoices
        Route::get('invoices/get-customer-data/{customer}', [\App\Http\Controllers\Accounting\InvoiceController::class, 'getCustomerData'])->name('invoices.get-customer-data');
        Route::get('invoices/sync-whmcs', [\App\Http\Controllers\Accounting\InvoiceController::class, 'syncWhmcs'])->name('invoices.sync-whmcs');

        Route::resource('invoices', \App\Http\Controllers\Accounting\InvoiceController::class);
        Route::post('invoices/{invoice}/payment', [\App\Http\Controllers\Accounting\InvoiceController::class, 'addPayment'])->name('invoices.payment');
        Route::get('invoices/{invoice}/print', [\App\Http\Controllers\Accounting\InvoiceController::class, 'print'])->name('invoices.print');
        Route::post('invoices/{invoice}/cancel', [\App\Http\Controllers\Accounting\InvoiceController::class, 'cancel'])->name('invoices.cancel');
        Route::get('invoices/{invoice}/payments/{transaction}/print', [\App\Http\Controllers\Accounting\InvoiceController::class, 'printPayment'])->name('invoices.payments.print');
        Route::post('invoices/{invoice}/whatsapp', [\App\Http\Controllers\Accounting\InvoiceController::class, 'sendWhatsapp'])->name('invoices.whatsapp');

        Route::prefix('reports')->name('reports.')->group(function () {
            Route::get('/', [\App\Http\Controllers\Accounting\ReportController::class, 'index'])->name('index');
            Route::get('/profit-loss', [\App\Http\Controllers\Accounting\ReportController::class, 'profitLoss'])->name('profit_loss');
            Route::get('/expenses-breakdown', [\App\Http\Controllers\Accounting\ReportController::class, 'expensesBreakdown'])->name('expenses_breakdown');
            Route::get('/cash-flow', [\App\Http\Controllers\Accounting\ReportController::class, 'cashFlow'])->name('cash_flow');
            Route::get('/vat-return', [\App\Http\Controllers\Accounting\ReportController::class, 'vatReturn'])->name('vat_return');
            Route::get('/customer-statement', [\App\Http\Controllers\Accounting\ReportController::class, 'customerStatement'])->name('customer_statement');
            Route::get('/customer-statement/print', [\App\Http\Controllers\Accounting\ReportController::class, 'printCustomerStatement'])->name('customer_statement.print');
            Route::get('/treasury-balance', [\App\Http\Controllers\Accounting\ReportController::class, 'treasuryBalance'])->name('treasury_balance');
            Route::get('/equity-statement', [\App\Http\Controllers\Accounting\ReportController::class, 'equityStatement'])->name('equity_statement');

            // New Comprehensive Reports
            Route::get('/sales-analysis', [\App\Http\Controllers\Accounting\ReportController::class, 'salesAnalysis'])->name('sales_analysis');
            Route::get('/inventory-report', [\App\Http\Controllers\Accounting\ReportController::class, 'inventoryReport'])->name('inventory_report');
            Route::get('/hr-report', [\App\Http\Controllers\Accounting\ReportController::class, 'hrReport'])->name('hr_report');
            Route::get('/operations-report', [\App\Http\Controllers\Accounting\ReportController::class, 'operationsReport'])->name('operations_report');
        });

        // Accounts Payable & Expenses
        Route::resource('suppliers', \App\Http\Controllers\Accounting\SupplierController::class);
        Route::post('suppliers/{supplier}/payment', [\App\Http\Controllers\Accounting\SupplierController::class, 'addPayment'])->name('suppliers.payment');

        Route::resource('bills', \App\Http\Controllers\Accounting\BillController::class);
        Route::post('bills/{bill}/payment', [\App\Http\Controllers\Accounting\BillController::class, 'addPayment'])->name('bills.payment');
        Route::get('bills/{bill}/print', [\App\Http\Controllers\Accounting\BillController::class, 'print'])->name('bills.print');
        Route::post('bills/{bill}/cancel', [\App\Http\Controllers\Accounting\BillController::class, 'cancel'])->name('bills.cancel');
        Route::delete('bills/{bill}/transactions/{transaction}', [\App\Http\Controllers\Accounting\BillController::class, 'deleteTransaction'])->name('bills.transactions.destroy');

        Route::resource('expenses', \App\Http\Controllers\Accounting\ExpenseController::class)->only(['index', 'create', 'store', 'destroy']);

        // Recurring Invoices
        Route::resource('recurring', \App\Http\Controllers\Accounting\RecurringInvoiceController::class);

        // Journal Entries
        Route::resource('journals', \App\Http\Controllers\Accounting\JournalEntryController::class)->parameters(['journals' => 'journal']);

        // Partners & Shares
        Route::get('partners/calculate', [\App\Http\Controllers\Accounting\PartnerController::class, 'calculateProfits'])->name('partners.calculate');
        Route::post('partners/distribute', [\App\Http\Controllers\Accounting\PartnerController::class, 'storeDistribution'])->name('partners.distribute');
        Route::resource('partners', \App\Http\Controllers\Accounting\PartnerController::class);

        Route::resource('currencies', \App\Http\Controllers\Accounting\CurrencyController::class);
        Route::resource('supplier-services', \App\Http\Controllers\Accounting\SupplierServiceController::class);

        Route::post('projects/{project}/progress', [\App\Http\Controllers\Accounting\ProjectController::class, 'updateProgress'])->name('projects.progress');
        Route::post('projects/{project}/payment', [\App\Http\Controllers\Accounting\ProjectController::class, 'storePayment'])->name('projects.payment');
        Route::get('programmers/{user}/statement', [\App\Http\Controllers\Accounting\ProjectController::class, 'programmerStatement'])->name('programmers.statement');
        Route::resource('programmers', \App\Http\Controllers\Accounting\ProgrammerController::class)->names('programmers');

        // Sales Management
        Route::resource('sales-people', \App\Http\Controllers\Accounting\SalesPersonController::class);
        Route::post('sales-people/{sales_person}/payment', [\App\Http\Controllers\Accounting\SalesPersonController::class, 'storePayment'])->name('sales-people.payment');
        Route::get('sales-people/{sales_person}/print-statement', [\App\Http\Controllers\Accounting\SalesPersonController::class, 'printStatement'])->name('sales-people.print-statement');
        Route::get('commission-payments/{payment}/print', [\App\Http\Controllers\Accounting\SalesPersonController::class, 'printPayment'])->name('commission-payments.print');
        Route::delete('commission-payments/{payment}', [\App\Http\Controllers\Accounting\SalesPersonController::class, 'deletePayment'])->name('commission-payments.destroy');

        // License Management
        Route::post('customers/{customer}/licenses/sync', [\App\Http\Controllers\Accounting\LicenseController::class, 'sync'])->name('licenses.sync');
        Route::post('customers/{customer}/licenses/whatsapp', [\App\Http\Controllers\Accounting\LicenseController::class, 'sendWhatsapp'])->name('licenses.whatsapp');

        // Tickets
        Route::get('tickets', [\App\Http\Controllers\Accounting\TicketController::class, 'index'])->name('tickets.index');
        Route::post('tickets', [\App\Http\Controllers\Accounting\TicketController::class, 'storeGeneric'])->name('tickets.store_generic');
        Route::post('customers/{customer}/tickets/sync', [\App\Http\Controllers\Accounting\TicketController::class, 'sync'])->name('tickets.sync');
        Route::post('customers/{customer}/tickets', [\App\Http\Controllers\Accounting\TicketController::class, 'store'])->name('tickets.store');
        Route::get('tickets/{ticket}', [\App\Http\Controllers\Accounting\TicketController::class, 'show'])->name('tickets.show');
        Route::post('tickets/{ticket}/reply', [\App\Http\Controllers\Accounting\TicketController::class, 'reply'])->name('tickets.reply');

        // Subscriptions
        Route::post('subscriptions/sync/{customer}', [\App\Http\Controllers\SubscriptionController::class, 'sync'])->name('subscriptions.sync');
        Route::resource('subscriptions', \App\Http\Controllers\SubscriptionController::class);

        Route::resource('projects', \App\Http\Controllers\Accounting\ProjectController::class);

        // WHMCS Unified Sync
        Route::get('whmcs', [\App\Http\Controllers\Accounting\WhmcsSyncController::class, 'index'])->name('whmcs.index');
        Route::post('whmcs/sync-clients', [\App\Http\Controllers\Accounting\WhmcsSyncController::class, 'syncClients'])->name('whmcs.sync-clients');
        Route::post('whmcs/sync-invoices', [\App\Http\Controllers\Accounting\WhmcsSyncController::class, 'syncInvoices'])->name('whmcs.sync-invoices');
        Route::post('whmcs/sync-licenses', [\App\Http\Controllers\Accounting\WhmcsSyncController::class, 'syncLicenses'])->name('whmcs.sync-licenses');
        Route::post('whmcs/sync-subscriptions', [\App\Http\Controllers\Accounting\WhmcsSyncController::class, 'syncSubscriptions'])->name('whmcs.sync-subscriptions');

        Route::get('shares', [\App\Http\Controllers\Accounting\ShareController::class, 'index'])->name('shares.index');
        Route::get('shares/investors/create', [\App\Http\Controllers\Accounting\ShareController::class, 'createInvestor'])->name('shares.investors.create');
        Route::post('shares/investors', [\App\Http\Controllers\Accounting\ShareController::class, 'storeInvestor'])->name('shares.investors.store');
        Route::post('shares/buy', [\App\Http\Controllers\Accounting\ShareController::class, 'buyShares'])->name('shares.buy');

        // Quotations
        Route::post('quotations/{quotation}/convert', [App\Http\Controllers\Accounting\QuotationController::class, 'convertToInvoice'])->name('quotations.convert');
        Route::get('quotations/{quotation}/print', [App\Http\Controllers\Accounting\QuotationController::class, 'print'])->name('quotations.print');
        Route::resource('quotations', App\Http\Controllers\Accounting\QuotationController::class);
    });

    // Settings (Non-Accounting)
    Route::get('settings/modules', [App\Http\Controllers\SettingsController::class, 'modules'])->name('settings.modules');
    Route::post('settings/modules', [App\Http\Controllers\SettingsController::class, 'updateModules'])->name('settings.modules.update');

    // HR & Payroll
    Route::prefix('hr')->name('hr.')->group(function () {
        Route::resource('employees', \App\Http\Controllers\HR\EmployeeController::class);
        Route::resource('departments', \App\Http\Controllers\HR\DepartmentController::class)->except(['create', 'edit', 'show']);
        Route::resource('designations', \App\Http\Controllers\HR\DesignationController::class)->except(['create', 'edit', 'show']);

        // Attendance
        Route::get('attendance', [\App\Http\Controllers\HR\AttendanceController::class, 'index'])->name('attendance.index');
        Route::post('attendance', [\App\Http\Controllers\HR\AttendanceController::class, 'store'])->name('attendance.store');
        Route::post('attendance/bulk-checkin', [\App\Http\Controllers\HR\AttendanceController::class, 'bulkCheckIn'])->name('attendance.bulk-checkin');
        Route::post('attendance/{employee}/checkout', [\App\Http\Controllers\HR\AttendanceController::class, 'checkOut'])->name('attendance.checkout');

        // Payroll
        Route::get('payroll', [\App\Http\Controllers\HR\PayrollController::class, 'index'])->name('payroll.index');
        Route::post('payroll/generate', [\App\Http\Controllers\HR\PayrollController::class, 'generate'])->name('payroll.generate');
        Route::get('payroll/{payroll}', [\App\Http\Controllers\HR\PayrollController::class, 'show'])->name('payroll.show');
        Route::post('payroll/{payroll}/item', [\App\Http\Controllers\HR\PayrollController::class, 'addItem'])->name('payroll.add-item');
        Route::delete('payroll/{payroll}/item/{item}', [\App\Http\Controllers\HR\PayrollController::class, 'removeItem'])->name('payroll.remove-item');
        Route::post('payroll/{payroll}/approve', [\App\Http\Controllers\HR\PayrollController::class, 'approve'])->name('payroll.approve');
        Route::post('payroll/{payroll}/pay', [\App\Http\Controllers\HR\PayrollController::class, 'pay'])->name('payroll.pay');
    });


});
