<?php

use App\Http\Controllers\AdminController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\Admin\AuthController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\BlogController;
use App\Http\Controllers\Admin\BlogCategoryController;
use App\Http\Controllers\Admin\BlogCommentController;
use App\Http\Controllers\BuyerController;
use App\Http\Controllers\FactoryController;
use App\Http\Controllers\InformationLibraryController;
use App\Http\Controllers\RfqController;
use App\Http\Controllers\RfqRevisionController;
use App\Http\Controllers\RfqAccessoryController;
use App\Http\Controllers\Front;
use App\Http\Controllers\Info\BrandController;
use App\Http\Controllers\Info\ItemDescriptionController;
use App\Http\Controllers\Info\SizeRangeController;
use App\Http\Controllers\Info\ColorController;
use App\Http\Controllers\Info\FabricCompositionController;
use App\Http\Controllers\Info\FabricTypeController;
use App\Http\Controllers\Info\YarnCountController;
use App\Http\Controllers\Info\FabricWeightController;
use App\Http\Controllers\Info\PortOfLandingController;
use App\Http\Controllers\Info\CountryOfOriginController;
use App\Http\Controllers\Info\PortOfDischargeController;
use App\Http\Controllers\Info\FinalDestinationController;
use App\Http\Controllers\Info\DeliveryTermController;
use App\Http\Controllers\Info\ShipmentModeController;
use App\Http\Controllers\Info\PaymentTermController;
use App\Http\Controllers\Info\PaymentModeController;
use App\Http\Controllers\RFQsController;
use App\Http\Controllers\InquiryController; 
use App\Http\Controllers\QuotationController; 

use App\Http\Controllers\YarnTypeController;
use App\Http\Controllers\KnittingTypeController;
use App\Http\Controllers\DyeingTypeController;
use App\Http\Controllers\FabricAddonController;
use App\Http\Controllers\AccessoryController;
use App\Http\Controllers\OtherCostController;
use App\Http\Controllers\CommercialRateController;
use App\Http\Controllers\GarmentAddonController;
use App\Http\Controllers\CostController;
use App\Http\Controllers\OrderConfirmationController;
use App\Http\Controllers\OrderDocumentController;
use App\Http\Controllers\BankController;
use App\Http\Controllers\SellerController;
use App\Http\Controllers\TermController;

use App\Http\Controllers\AdvancePaymentController;
use App\Http\Controllers\PaymentAllocationController;
use App\Http\Controllers\BankInvoiceController;
use App\Http\Controllers\PaymentLedgerController;

use App\Http\Controllers\ShipmentController;
use App\Http\Controllers\CartonDetailController;
use App\Http\Controllers\BookingInvoiceController;
use App\Http\Controllers\FinalShipmentController;

use App\Http\Controllers\DocumentGeneratorController;
use App\Http\Controllers\DocumentTemplateController;
use App\Http\Controllers\ExportCenterController;
use App\Http\Controllers\EmailLogController;
use App\Http\Controllers\ReportController;

// permissions route
use App\Http\Controllers\Admin\UserManagementController;
use App\Http\Controllers\Admin\AuditLogController;
use App\Http\Controllers\Admin\RoleManagementController;

use Illuminate\Support\Facades\Route;

// admins routes start
Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('login', [AuthController::class, 'loginForm'])->name('login');
    Route::post('login', [AuthController::class, 'login']);
    Route::post('logout', [AuthController::class, 'logout'])->name('logout');

    Route::middleware('auth:admin')->group(function () {
        
        // ===============================
        // DASHBOARD & PROFILE ROUTES
        // ===============================
        Route::middleware('permission:view.dashboard')->group(function () {
            Route::get('dashboard', [DashboardController::class, 'index'])->name('dashboard');
            Route::get('profile', [DashboardController::class, 'profile'])->name('profile');
            Route::post('profile', [DashboardController::class, 'updateProfile'])->name('profile.update');
        });

        // ===============================
        // ADMIN CREATION (Super Admin Only)
        // ===============================
        Route::middleware('permission:create.users')->group(function () {
            Route::get('create', [DashboardController::class, 'create'])->name('create');
            Route::post('store', [DashboardController::class, 'store'])->name('store');
        });

        // ===============================
        // REPORTS & ANALYTICS
        // ===============================
        Route::middleware('permission:view.reports')->group(function () {
            Route::get('reports-dashboard', [ReportController::class, 'dashboard'])->name('reports.dashboard');
        });

        // ===============================
        // USER MANAGEMENT ROUTES
        // ===============================
        Route::middleware('permission:view.users')->group(function () {
            Route::get('users', [UserManagementController::class, 'index'])->name('users.index');
            Route::get('users/create', [UserManagementController::class, 'create'])
                ->middleware('permission:create.users')
                ->name('users.create');
            Route::post('users', [UserManagementController::class, 'store'])
                ->middleware('permission:create.users')
                ->name('users.store');
            Route::get('users/{user}/edit', [UserManagementController::class, 'edit'])
                ->middleware('permission:edit.users')
                ->name('users.edit');
            Route::put('users/{user}', [UserManagementController::class, 'update'])
                ->middleware('permission:edit.users')
                ->name('users.update');
            Route::delete('users/{user}', [UserManagementController::class, 'destroy'])
                ->middleware('permission:delete.users')
                ->name('users.destroy');
        });

        // ===============================
        // ROLE MANAGEMENT ROUTES
        // ===============================
        Route::middleware('permission:manage.roles')->group(function () {
            Route::get('roles', [RoleManagementController::class, 'index'])->name('roles.index');
            Route::get('/roles/create', [RoleManagementController::class, 'create'])->name('roles.create');
            Route::post('/roles', [RoleManagementController::class, 'store'])->name('roles.store');
            Route::get('/roles/{role}/edit', [RoleManagementController::class, 'edit'])->name('roles.edit');
            Route::put('/roles/{role}', [RoleManagementController::class, 'update'])->name('roles.update');
            Route::delete('/roles/{role}', [RoleManagementController::class, 'destroy'])->name('roles.destroy');
            Route::get('roles/{role}/permissions', [RoleManagementController::class, 'editPermissions'])
                ->name('roles.permissions');
            Route::put('roles/{role}/permissions', [RoleManagementController::class, 'updatePermissions'])
                ->name('roles.permissions.update');
        });

        // ===============================
        // AUDIT LOGS
        // ===============================
        Route::middleware('permission:view.audit.logs')->group(function () {
            Route::get('audit-logs', [AuditLogController::class, 'index'])->name('audit-logs.index');
            Route::get('audit-logs/{auditLog}', [AuditLogController::class, 'show'])->name('audit-logs.show');
        });

        // ===============================
        // PAYMENT MANAGEMENT
        // ===============================
        Route::middleware('permission:view.payments')->group(function () {
            Route::resource('advance-payments', AdvancePaymentController::class);
            Route::get('payment-ledger', [AdvancePaymentController::class, 'ledger'])->name('payment.ledger');
            Route::get('payment-ledger/{buyer}', [AdvancePaymentController::class, 'buyerLedger'])->name('payment.ledger.buyer');
            Route::resource('payment-allocations', PaymentAllocationController::class);
            Route::resource('bank-invoices', BankInvoiceController::class);
            Route::get('bank-invoices/{bankInvoice}/export-pdf', [BankInvoiceController::class, 'exportPdf'])->name('bank-invoices.export-pdf');
            Route::post('bank-invoices/{bankInvoice}/mark-sent', [BankInvoiceController::class, 'markAsSent'])->name('bank-invoices.mark-sent');
            Route::post('bank-invoices/{bankInvoice}/mark-paid', [BankInvoiceController::class, 'markAsPaid'])->name('bank-invoices.mark-paid');
            Route::get('payment-ledgers', [PaymentLedgerController::class, 'index'])->name('payment-ledger.index');
            Route::get('payment-ledgers/{buyer}', [PaymentLedgerController::class, 'show'])->name('payment-ledger.show');
            Route::post('payment-ledgers/update-all', [PaymentLedgerController::class, 'updateAllLedgers'])->name('payment-ledger.update-all');
            Route::get('payment-ledgers/{buyer}/report', [PaymentLedgerController::class, 'buyerReport'])->name('payment-ledger.buyer-report');
        });

        // ===============================
        // SHIPMENT & LOGISTICS
        // ===============================
        Route::middleware('permission:view.shipments')->group(function () {
            Route::resource('shipments', ShipmentController::class);
            Route::get('shipments/{shipment}/carton-details', [CartonDetailController::class, 'index'])->name('shipments.carton-details.index');
            Route::get('shipments/{shipment}/carton-details/create', [CartonDetailController::class, 'create'])->name('shipments.carton-details.create');
            Route::post('shipments/{shipment}/carton-details', [CartonDetailController::class, 'store'])->name('shipments.carton-details.store');
            Route::get('shipments/{shipment}/carton-details/{cartonDetail}/edit', [CartonDetailController::class, 'edit'])->name('shipments.carton-details.edit');
            Route::put('shipments/{shipment}/carton-details/{cartonDetail}', [CartonDetailController::class, 'update'])->name('shipments.carton-details.update');
            Route::delete('shipments/{shipment}/carton-details/{cartonDetail}', [CartonDetailController::class, 'destroy'])->name('shipments.carton-details.destroy');
            Route::get('shipments/{shipment}/booking-invoices', [BookingInvoiceController::class, 'index'])->name('shipments.booking-invoices.index');
            Route::get('shipments/{shipment}/booking-invoices/create', [BookingInvoiceController::class, 'create'])->name('shipments.booking-invoices.create');
            Route::post('shipments/{shipment}/booking-invoices', [BookingInvoiceController::class, 'store'])->name('shipments.booking-invoices.store');
            Route::get('shipments/{shipment}/booking-invoices/{bookingInvoice}', [BookingInvoiceController::class, 'show'])->name('shipments.booking-invoices.show');
            Route::get('shipments/{shipment}/booking-invoices/{bookingInvoice}/edit', [BookingInvoiceController::class, 'edit'])->name('shipments.booking-invoices.edit');
            Route::put('shipments/{shipment}/booking-invoices/{bookingInvoice}', [BookingInvoiceController::class, 'update'])->name('shipments.booking-invoices.update');
            Route::delete('shipments/{shipment}/booking-invoices/{bookingInvoice}', [BookingInvoiceController::class, 'destroy'])->name('shipments.booking-invoices.destroy');
            Route::get('shipments/{shipment}/booking-invoices/{bookingInvoice}/export-pdf', [BookingInvoiceController::class, 'exportPdf'])->name('shipments.booking-invoices.export-pdf');
            Route::get('shipments/{shipment}/final-shipments', [FinalShipmentController::class, 'index'])->name('shipments.final-shipments.index');
            Route::get('shipments/{shipment}/final-shipments/create', [FinalShipmentController::class, 'create'])->name('shipments.final-shipments.create');
            Route::post('shipments/{shipment}/final-shipments', [FinalShipmentController::class, 'store'])->name('shipments.final-shipments.store');
            Route::get('shipments/{shipment}/final-shipments/{finalShipment}', [FinalShipmentController::class, 'show'])->name('shipments.final-shipments.show');
            Route::get('shipments/{shipment}/final-shipments/{finalShipment}/edit', [FinalShipmentController::class, 'edit'])->name('shipments.final-shipments.edit');
            Route::put('shipments/{shipment}/final-shipments/{finalShipment}', [FinalShipmentController::class, 'update'])->name('shipments.final-shipments.update');
            Route::delete('shipments/{shipment}/final-shipments/{finalShipment}', [FinalShipmentController::class, 'destroy'])->name('shipments.final-shipments.destroy');
            Route::get('shipments/{shipment}/final-shipments/{finalShipment}/export-packing-list', [FinalShipmentController::class, 'exportPackingList'])->name('shipments.final-shipments.export-packing-list');
            Route::get('shipments/{shipment}/final-shipments/{finalShipment}/export-final-invoice', [FinalShipmentController::class, 'exportFinalInvoice'])->name('shipments.final-shipments.export-final-invoice');
        });

        // ===============================
        // DOCUMENT MANAGEMENT
        // ===============================
        Route::middleware('permission:view.documents')->group(function () {
            Route::get('document-generator', [DocumentGeneratorController::class, 'index'])->name('document-generator.index');
            Route::post('document-generator/generate-documents', [DocumentGeneratorController::class, 'generateDocuments'])->name('document-generator.generate-documents');
            Route::get('document-generator/preview-document', [DocumentGeneratorController::class, 'previewDocument'])->name('document-generator.preview-document');
            Route::get('document-generator/generated-documents/{document}/download', [DocumentGeneratorController::class, 'downloadDocument'])->name('document-generator.generated-documents.download');
            Route::get('document-templates', [DocumentTemplateController::class, 'index'])->name('document-templates.index');
            Route::get('document-templates/create', [DocumentTemplateController::class, 'create'])->name('document-templates.create');
            Route::post('document-templates', [DocumentTemplateController::class, 'store'])->name('document-templates.store');
            Route::get('document-templates/{documentTemplate}/edit', [DocumentTemplateController::class, 'edit'])->name('document-templates.edit');
            Route::put('document-templates/{documentTemplate}', [DocumentTemplateController::class, 'update'])->name('document-templates.update');
            Route::delete('document-templates/{documentTemplate}', [DocumentTemplateController::class, 'destroy'])->name('document-templates.destroy');
            Route::post('document-templates/{documentTemplate}/set-default', [DocumentTemplateController::class, 'setDefault'])->name('document-templates.set-default');
        });

        // ===============================
        // EXPORT & EMAIL
        // ===============================
        Route::middleware('permission:export.reports')->group(function () {
            Route::get('export-center', [ExportCenterController::class, 'index'])->name('export-center.index');
            Route::post('export-center/bulk-download', [ExportCenterController::class, 'bulkDownload'])->name('export-center.bulk-download');
            Route::post('export-center/excel-report', [ExportCenterController::class, 'createExcelReport'])->name('export-center.excel-report');
            Route::post('export-center/send-email', [ExportCenterController::class, 'sendEmail'])->name('export-center.send-email');
            Route::get('export-center/export-jobs/{exportJob}/status', [ExportCenterController::class, 'getExportJobStatus'])->name('export-center.export-job-status');
            Route::get('email-logs', [EmailLogController::class, 'index'])->name('email-logs.index');
            Route::get('email-logs/{emailLog}', [EmailLogController::class, 'show'])->name('email-logs.show');
            Route::post('email-logs/{emailLog}/resend', [EmailLogController::class, 'resend'])->name('email-logs.resend');
        });

        // ===============================
        // BUYER MANAGEMENT
        // ===============================
        Route::middleware('permission:view.buyers')->group(function () {
            Route::resource('buyers', BuyerController::class);
            Route::get('buyers/{id}/orders', [BuyerController::class, 'orderHistory'])->name('buyers.orders');
        });

        // ===============================
        // FACTORY MANAGEMENT
        // ===============================
        Route::middleware('permission:view.factories')->group(function () {
            Route::resource('factories', FactoryController::class);
        });

        // ===============================
        // INFORMATION LIBRARY
        // ===============================
        Route::middleware('permission:view.library')->group(function () {
            Route::resource('information-library', InformationLibraryController::class);
            Route::resource('brands', BrandController::class);
            Route::resource('item-descriptions', ItemDescriptionController::class);
            Route::resource('size-ranges', SizeRangeController::class);
            Route::resource('colors', ColorController::class);
            Route::resource('fabric-compositions', FabricCompositionController::class);
            Route::resource('fabric-types', FabricTypeController::class);
            Route::resource('yarn-counts', YarnCountController::class);
            Route::resource('fabric-weights', FabricWeightController::class);
            Route::resource('port-of-landings', PortOfLandingController::class);
            Route::resource('country-of-origins', CountryOfOriginController::class);
            Route::resource('port-of-discharges', PortOfDischargeController::class);
            Route::resource('final-destinations', FinalDestinationController::class);
            Route::resource('delivery-terms', DeliveryTermController::class);
            Route::resource('shipment-modes', ShipmentModeController::class);
            Route::resource('payment-terms', PaymentTermController::class);
            Route::resource('payment-modes', PaymentModeController::class);
            Route::resource('rfq', RFQsController::class); 
            Route::resource('inquiries', InquiryController::class); 
        });

        // ===============================
        // QUOTATION MANAGEMENT
        // ===============================
        Route::middleware('permission:view.quotations')->group(function () {
            Route::get('/admin/quotations/create', [QuotationController::class, 'create'])->name('admin.quotations.create');
            Route::resource('quotations', QuotationController::class); 
            Route::post('quotations/{quotation}/status', [QuotationController::class, 'updateStatus'])->name('quotations.update-status');
            Route::post('quotations/{quotation}/convert-to-order', [QuotationController::class, 'convertToOrder'])->name('quotations.convert-to-order');
            Route::get('quotations/{quotation}/convert-to-order-form', [QuotationController::class, 'showConvertToOrderForm'])->name('quotations.convert-to-order-form');
            Route::get('quotations/status/{status}', [QuotationController::class, 'getByStatus'])->name('quotations.by-status');
            Route::post('quotations/bulk-update-status', [QuotationController::class, 'bulkUpdateStatus'])->name('quotations.bulk-update-status');
        });

        // ===============================
        // ORDER CONFIRMATION
        // ===============================
        Route::middleware('permission:view.orders')->group(function () {
            Route::resource('order-confirmations', OrderConfirmationController::class);
            Route::post('order-confirmations/{orderConfirmation}/status', [OrderConfirmationController::class, 'updateStatus'])->name('order-confirmations.update-status');
            Route::post('order-confirmations/{orderConfirmation}/documents', [OrderConfirmationController::class, 'uploadDocument'])->name('order-confirmations.upload-document');
            Route::get('order-confirmations/{orderConfirmation}/documents/{document}/download', [OrderConfirmationController::class, 'downloadDocument'])->name('order-confirmations.download-document');
            Route::delete('order-confirmations/{orderConfirmation}/documents/{document}', [OrderConfirmationController::class, 'deleteDocument'])->name('order-confirmations.delete-document');
            Route::get('order-confirmations-dashboard', [OrderConfirmationController::class, 'dashboard'])->name('order-confirmations.dashboard');
            Route::get('/order-confirmations/{id}/pi-pdf', [OrderConfirmationController::class, 'generatePiPdf'])->name('order-confirmations.pdf');
            Route::get('/order-confirmations/{id}/sc-pdf', [OrderConfirmationController::class,'generateScPdf'])->name('order-confirmations.sc');
            Route::post('/order-confirmations/{id}/pi_file', [OrderConfirmationController::class, 'uploadBuyerPo'])->name('order-confirmations.upload-po');
        });

        // ===============================
        // ORDER DOCUMENTS
        // ===============================
        Route::middleware('permission:view.documents')->group(function () {
            Route::get("order-documents/create/{order_confirmation_id}", [App\Http\Controllers\OrderDocumentController::class, "create"])->name("order-documents.create");
            Route::post("order-documents", [App\Http\Controllers\OrderDocumentController::class, "store"])->name("order-documents.store");
            Route::get("order-documents/{orderDocument}/download", [App\Http\Controllers\OrderDocumentController::class, "download"])->name("order-documents.download");
            Route::delete("order-documents/{orderDocument}", [App\Http\Controllers\OrderDocumentController::class, "destroy"])->name("order-documents.destroy");
        });

        // ===============================
        // COST & PRICING MANAGEMENT
        // ===============================
        Route::middleware('permission:view.costs')->group(function () {
            Route::resource("yarn_types", YarnTypeController::class);
            Route::resource("knitting_types", KnittingTypeController::class);
            Route::resource("dyeing_types", DyeingTypeController::class);
            Route::resource("fabric_addons", FabricAddonController::class);
            Route::resource("accessories", AccessoryController::class);
            Route::resource("other_costs", OtherCostController::class);
            Route::resource("commercial_rates", CommercialRateController::class);
            Route::resource("garment_addons", GarmentAddonController::class);
            Route::resource('costs', CostController::class);
        });

        // ===============================
        // BANK & SELLER MANAGEMENT
        // ===============================
        Route::middleware('permission:view.banks')->group(function () {
            Route::resource('banks', BankController::class);
            Route::get('banks/{bank}/json', [BankController::class,'json'])->name('banks.json');
            Route::resource('sellers', SellerController::class);
            Route::resource('terms', TermController::class);
        });

        // ===============================
        // BLOG MANAGEMENT
        // ===============================
        Route::middleware('permission:view.blogs')->group(function () {
            Route::resource('categories', BlogCategoryController::class);
            Route::resource('admin/posts', BlogController::class);
            Route::get('blogs', [BlogController::class, 'index'])->name('blogs.index');
        });

    });
});

// admins routes end

Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');