<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

// =========================================================================
// IMPORT CONTROLLERS
// =========================================================================
use App\Http\Controllers\Api\PosController;
use App\Http\Controllers\Api\HoldCartController;
use App\Http\Controllers\Api\ExpenseApiController;
use App\Http\Controllers\Api\OnlineStoreController;
use App\Http\Controllers\Api\PosOnlineOrderController;
use App\Http\Controllers\Api\OwnerController;
use App\Http\Controllers\Api\AuthOTPController;
use App\Http\Controllers\Api\AdminAuthController;
use App\Http\Controllers\Api\DeliveryController;
use App\Http\Controllers\Api\AdminCategoryController;
use App\Http\Controllers\Api\AdminProductController;
use App\Http\Controllers\Api\ExpenseCategoryApiController;
use App\Http\Controllers\Api\AdminSupplierController;
use App\Http\Controllers\Api\AdminBranchController;
use App\Http\Controllers\Api\AdminUserController;
use App\Http\Controllers\Api\AdminSalesmanController;
use App\Http\Controllers\Api\AdminArmadaController;
use App\Http\Controllers\Api\AdminCustomerController;
use App\Http\Controllers\Api\AdminCustomerTypeController; 
use App\Http\Controllers\Api\SalesProgramController;
use App\Http\Controllers\SearchController;
use App\Http\Controllers\Api\SettingApiController;
use App\Http\Controllers\Api\AppSettingApiController;
use App\Http\Controllers\Api\MigrationStockApiController;
use App\Http\Controllers\Api\MigrationCustomerDebtApiController;
use App\Http\Controllers\Api\MigrationSupplierDebtApiController;
use App\Http\Controllers\Api\AccountingMappingApiController;
use App\Http\Controllers\Api\AdminExpenseController;
use App\Http\Controllers\Api\AccountingCoaApiController;
use App\Http\Controllers\Api\AccountingJournalApiController;
use App\Http\Controllers\Api\CashMutationApiController;
use App\Http\Controllers\Api\JournalApiController;
use App\Http\Controllers\Api\RegionApiController;
use App\Http\Controllers\Api\AdminRegionController;
use App\Http\Controllers\Api\LedgerController;
use App\Http\Controllers\Api\PurchasingController; 
use App\Http\Controllers\Api\AccountPayableController;
use App\Http\Controllers\Api\PurchaseReturnController;
use App\Http\Controllers\Api\SalesOrderController;
use App\Http\Controllers\Api\SalesInvoiceController;
use App\Http\Controllers\Api\SalesReturnController;
use App\Http\Controllers\Api\ReceivablePaymentController;
use App\Http\Controllers\Api\Report\SalesReportController;
use App\Http\Controllers\Api\Report\StockMovementController;
use App\Http\Controllers\Api\StockTransferController;
use App\Http\Controllers\Api\AdminJourneyPlanController;
use App\Http\Controllers\Api\SalesmanTargetController;
use App\Http\Controllers\Api\AdminCompetitorController;
use App\Http\Controllers\Api\SalesmanCustomerController;
use App\Http\Controllers\Api\BranchAccountController;
use App\Http\Controllers\Api\InterbranchTransferController;
use App\Http\Controllers\Api\PositionController;
use App\Http\Controllers\Api\EmployeeController;
use App\Http\Controllers\Api\EmployeeLoanController;
use App\Http\Controllers\Api\PayrollController;
use App\Http\Controllers\Api\AttendanceController;
use App\Http\Controllers\Api\EmployeeAllowanceController;
use App\Http\Controllers\Api\MasterAllowanceController;
use App\Http\Controllers\Api\MasterCalendarController;
use App\Http\Controllers\Api\FinancePayrollController;


/*
|--------------------------------------------------------------------------
| API Routes - P-LINK ENTERPRISE DISTRIBUTION SYSTEM
|--------------------------------------------------------------------------
*/

// =========================================================================
// 1. RUTE PUBLIK (Tanpa Token Sanctum)
// =========================================================================

// --- AUTHENTICATION ---
Route::post('/login', [PosController::class, 'login']); // Login POS Kasir
Route::post('/admin/login', [AdminAuthController::class, 'login']); // Login Admin/Owner/Gudang

// --- POS PUBLIC ---
//Route::get('/pos/products', [PosController::class, 'getProducts']); // Produk POS untuk C# / Flutter

// --- PWA TOKO ONLINE (PUBLIC) ---
Route::prefix('online')->group(function () {
    Route::post('/check-coverage', [OnlineStoreController::class, 'checkCoverage']);
    Route::get('/products', [OnlineStoreController::class, 'getProducts']);
    Route::post('/checkout', [OnlineStoreController::class, 'checkout']);
    Route::post('/register', [AdminCustomerController::class, 'onlineRegister']);

    // Auth PWA
    Route::post('/login/request-otp', [AuthOTPController::class, 'requestOtp']);
    Route::post('/login/verify-otp', [AuthOTPController::class, 'verifyOtp']);
    Route::post('/login/password', [AuthOTPController::class, 'loginPassword']); 

    // Auto-Suggest Search
    Route::prefix('search')->group(function () {
        Route::get('/product', [SearchController::class, 'product']);
        Route::get('/category', [SearchController::class, 'category']);
    });
});

// --- WILAYAH / REGIONAL (PUBLIC) ---
Route::prefix('regions')->group(function () {
    Route::get('/provinces', [RegionApiController::class, 'getProvinces']);
    Route::get('/cities/{provinceId}', [RegionApiController::class, 'getCities']);
    Route::get('/districts/{cityId}', [RegionApiController::class, 'getDistricts']);
});


// =========================================================================
// 2. RUTE TERTUTUP (Membutuhkan Token Sanctum)
// =========================================================================
Route::middleware('auth:sanctum')->group(function () {

    // ---------------------------------------------------------------------
    // A. PROFIL & AUTENTIKASI LANJUTAN
    // ---------------------------------------------------------------------
    Route::get('/user-profile', function (Request $request) {
        return response()->json(['success' => true, 'data' => $request->user()]);
    });
    
    // RUTE BARU: Switch Branch Khusus Owner
    Route::post('/admin/switch-branch', [AdminAuthController::class, 'switchBranch']);

    Route::get('/admin/executive-dashboard', [\App\Http\Controllers\Api\ExecutiveDashboardController::class, 'index']);
    Route::get('/admin/live-dashboard-metrics', [\App\Http\Controllers\Api\AdminReportController::class, 'getLiveDashboardMetrics']);

    // ---------------------------------------------------------------------
    // B. MANAJEMEN MASTER DATA (ADMIN & OPERASIONAL)
    // ---------------------------------------------------------------------
    
    // Master Users
    Route::get('/admin/users', [AdminUserController::class, 'index']);
    Route::post('/admin/users', [AdminUserController::class, 'store']);
    Route::put('/admin/users/{id}', [AdminUserController::class, 'update']);
    Route::delete('/admin/users/{id}', [AdminUserController::class, 'destroy']);

    // Rute Ganti Password Karyawan (Bisa dipanggil dari Next.js maupun Flutter)
    Route::post('/admin/users/change-password', [\App\Http\Controllers\Api\AdminUserController::class, 'changePassword']);
    Route::post('/mobile/user/change-password', [\App\Http\Controllers\Api\AdminUserController::class, 'changePassword']); 

    // Master Cabang
    Route::get('/admin/branches', [AdminBranchController::class, 'index']);
    Route::post('/admin/branches', [AdminBranchController::class, 'store']);
    Route::post('/admin/branches/{id}', [AdminBranchController::class, 'update']);
    Route::delete('/admin/branches/{id}', [AdminBranchController::class, 'destroy']);

    // Master Kategori Produk
    Route::get('/categories', [AdminCategoryController::class, 'index']);
    Route::get('/admin/categories', [AdminCategoryController::class, 'index']);
    Route::post('/categories', [AdminCategoryController::class, 'store']);
    Route::post('/categories/{id}', [AdminCategoryController::class, 'update']);
    Route::post('/categories/{id}/toggle', [AdminCategoryController::class, 'toggleStatus']);
    Route::delete('/categories/{id}', [AdminCategoryController::class, 'destroy']);

    // Master Produk
    Route::get('/admin/products', [AdminProductController::class, 'index']);
    Route::get('/products', [AdminProductController::class, 'index']);
    Route::post('/admin/products', [AdminProductController::class, 'store']);
    Route::post('/admin/products/{id}', [AdminProductController::class, 'update']);

    // Master Kategori Biaya
    Route::get('/admin/master/expense-categories', [ExpenseCategoryApiController::class, 'index']);
    Route::post('/admin/master/expense-categories', [ExpenseCategoryApiController::class, 'store']);
    Route::put('/admin/master/expense-categories/{id}', [ExpenseCategoryApiController::class, 'update']);
    Route::delete('/admin/master/expense-categories/{id}', [ExpenseCategoryApiController::class, 'destroy']);

    // Master Supplier
    Route::get('/admin/suppliers', [AdminSupplierController::class, 'index']);
    Route::post('/admin/suppliers', [AdminSupplierController::class, 'store']);
    Route::post('/admin/suppliers/{id}', [AdminSupplierController::class, 'update']);
    Route::delete('/admin/suppliers/{id}', [AdminSupplierController::class, 'destroy']);

    // Master Salesman & Armada
    Route::get('/admin/salesmen', [AdminSalesmanController::class, 'index']);
    Route::post('/admin/salesmen', [AdminSalesmanController::class, 'store']);
    Route::post('/admin/salesmen/{id}', [AdminSalesmanController::class, 'update']);
    Route::delete('/admin/salesmen/{id}', [AdminSalesmanController::class, 'destroy']);

    Route::get('/admin/armadas', [AdminArmadaController::class, 'index']);
    Route::post('/admin/armadas', [AdminArmadaController::class, 'store']);
    Route::post('/admin/armadas/{id}', [AdminArmadaController::class, 'update']);
    Route::delete('/admin/armadas/{id}', [AdminArmadaController::class, 'destroy']);

    // Master Pelanggan & Tipe Outlet
    Route::get('/admin/customer-type', [AdminCustomerTypeController::class, 'index']);
    Route::post('/admin/customer-type', [AdminCustomerTypeController::class, 'store']);
    Route::put('/admin/customer-type/{id}', [AdminCustomerTypeController::class, 'update']);
    Route::delete('/admin/customer-type/{id}', [AdminCustomerTypeController::class, 'destroy']);

    Route::get('/admin/customers', [AdminCustomerController::class, 'index']);
    Route::post('/admin/customers', [AdminCustomerController::class, 'store']);
    Route::post('/admin/customers/{id}', [AdminCustomerController::class, 'update']);
    Route::delete('/admin/customers/{id}', [AdminCustomerController::class, 'destroy']);
    Route::post('/admin/customers/{id}/upload-ktp', [\App\Http\Controllers\Api\CustomerKtpController::class, 'upload']);
    Route::post('/admin/customers/{id}/approve', [AdminCustomerController::class, 'approveRegistration']);

    Route::get('/customers', function (Request $request) {
        $user = $request->user();
        $customers = \App\Models\Customer::where('branch_id', $user->branch_id)
            ->where('is_active', true) 
            ->orderBy('name', 'asc')
            ->get();
        return response()->json(['success' => true, 'data' => $customers]);
    });

    // Master Wilayah
    Route::prefix('admin/regions')->group(function () {
        Route::post('/provinces', [AdminRegionController::class, 'storeProvince']);
        Route::delete('/provinces/{id}', [AdminRegionController::class, 'deleteProvince']);
        Route::post('/cities', [AdminRegionController::class, 'storeCity']);
        Route::delete('/cities/{id}', [AdminRegionController::class, 'deleteCity']);
        Route::post('/districts', [AdminRegionController::class, 'storeDistrict']);
        Route::delete('/districts/{id}', [AdminRegionController::class, 'deleteDistrict']);
    });

    // Master Banner
    Route::apiResource('admin/banners', \App\Http\Controllers\Api\AdminBannerController::class);


    // ---------------------------------------------------------------------
    // C. PENGATURAN APLIKASI & SETUP AWAL
    // ---------------------------------------------------------------------
    
    Route::prefix('admin/app-settings')->group(function () {
        Route::get('/', [SettingApiController::class, 'index']);
        Route::put('/{id}', [SettingApiController::class, 'update']);
    });

    Route::prefix('admin/core-settings')->group(function () {
        Route::get('/', [AppSettingApiController::class, 'index']);
        Route::post('/', [AppSettingApiController::class, 'update']); 
        Route::post('/command/recalculate', [AppSettingApiController::class, 'recalculateStock']);
        Route::post('/command/close-stock', [AppSettingApiController::class, 'closeStock']);
        Route::post('/command/reopen-stock', [AppSettingApiController::class, 'reopenStock']);
    });


    // ---------------------------------------------------------------------
    // D. MIGRASI DATA (SALDO AWAL)
    // ---------------------------------------------------------------------
    
    Route::prefix('admin/migration/stock')->group(function () {
        Route::get('/', [MigrationStockApiController::class, 'index']);
        Route::get('/branches', [MigrationStockApiController::class, 'getBranches']);
        Route::get('/products', [MigrationStockApiController::class, 'getProducts']);
        Route::post('/manual', [MigrationStockApiController::class, 'storeManual']);
        Route::put('/{id}', [MigrationStockApiController::class, 'update']);
        Route::delete('/{id}', [MigrationStockApiController::class, 'destroy']);
        Route::post('/preview', [MigrationStockApiController::class, 'previewCsv']);
        Route::post('/import', [MigrationStockApiController::class, 'importData']);
    });

    Route::prefix('admin/migration/piutang')->group(function () {
        Route::get('/', [MigrationCustomerDebtApiController::class, 'index']);
        Route::get('/customers', [MigrationCustomerDebtApiController::class, 'getCustomers']);
        Route::post('/manual', [MigrationCustomerDebtApiController::class, 'storeManual']);
        Route::put('/{id}', [MigrationCustomerDebtApiController::class, 'update']);
        Route::delete('/{id}', [MigrationCustomerDebtApiController::class, 'destroy']);
        Route::post('/preview', [MigrationCustomerDebtApiController::class, 'previewCsv']);
        Route::post('/import', [MigrationCustomerDebtApiController::class, 'importData']);
    });

    Route::prefix('admin/migration/hutang')->group(function () {
        Route::get('/', [MigrationSupplierDebtApiController::class, 'index']);
        Route::get('/suppliers', [MigrationSupplierDebtApiController::class, 'getSuppliers']);
        Route::get('/branches', [MigrationSupplierDebtApiController::class, 'getBranches']);
        Route::post('/manual', [MigrationSupplierDebtApiController::class, 'storeManual']);
        Route::put('/{id}', [MigrationSupplierDebtApiController::class, 'update']);
        Route::delete('/{id}', [MigrationSupplierDebtApiController::class, 'destroy']);
        Route::post('/preview', [MigrationSupplierDebtApiController::class, 'previewCsv']);
        Route::post('/import', [MigrationSupplierDebtApiController::class, 'importData']);
    });


    // ---------------------------------------------------------------------
    // E. ORDER TO CASH (PENJUALAN & PENGIRIMAN)
    // ---------------------------------------------------------------------
    
    Route::prefix('admin/sales-orders')->group(function () {
        Route::get('/pending', [SalesOrderController::class, 'getPendingQueue']);
        Route::post('/process-delivery', [SalesOrderController::class, 'processBulkDelivery']);
        Route::post('/manifest', [SalesOrderController::class, 'generateManifest']);
        Route::post('/report-failed', [SalesOrderController::class, 'reportFailedDelivery']);
        Route::post('/cancel', [SalesOrderController::class, 'cancelOrder']);
        Route::get('/master-data', [SalesOrderController::class, 'getMasterData']); 
        Route::get('/check-credit/{customerId}', [SalesOrderController::class, 'checkCustomerCredit']); 
        Route::post('/calculate-cart', [SalesOrderController::class, 'calculateCart']);
        Route::post('/manual-order', [SalesOrderController::class, 'storeManualOrder']);
        Route::get('/credit-hold', [SalesOrderController::class, 'getCreditHoldOrders']);
        Route::post('/credit-approval', [SalesOrderController::class, 'processCreditApproval']);
        Route::get('/delivery-history', [SalesOrderController::class, 'getDeliveryHistory']);
        Route::post('/authorize-reprint', [SalesOrderController::class, 'authorizeReprint']);
        Route::post('/transfer-branch', [SalesOrderController::class, 'updateFulfillmentBranch']);
        Route::post('/mark-delivered', [SalesOrderController::class, 'markDelivered']);
        
        // 2. RUTE DINAMIS (Harus di paling bawah dalam grup ini)
        Route::get('/{id}', [SalesOrderController::class, 'show']);
        Route::put('/{id}', [SalesOrderController::class, 'updateManualOrder']);

    });

    
    
    Route::get('/admin/orders/pending-count', [SalesOrderController::class, 'getPendingCount']);

    Route::prefix('admin/sales-returns')->group(function () {
        Route::get('/search-invoice', [SalesReturnController::class, 'searchInvoice']);
        Route::post('/store', [SalesReturnController::class, 'storeRequest']);
        Route::get('/pending', [SalesReturnController::class, 'getPendingReturns']);
        Route::get('/{id}', [SalesReturnController::class, 'getReturnDetail']);
        Route::post('/{id}/verify', [SalesReturnController::class, 'verifyIncomingReturn']);
        Route::post('/{id}/authorize', [SalesReturnController::class, 'authorizeFinance']);
        Route::post('/{id}/cancel', [SalesReturnController::class, 'cancelReturn']);
        Route::get('/maintenance/sync-journals', [SalesReturnController::class, 'syncMissingInventoryJournals']);
    });

    // ---------------------------------------------------------------------
    // F. PURCHASING & ACCOUNT PAYABLE (PEMBELIAN)
    // ---------------------------------------------------------------------
    
    Route::prefix('admin/purchasing')->group(function () {
        Route::get('/', [PurchasingController::class, 'index']);
        Route::post('/po', [PurchasingController::class, 'storePo']);
        Route::put('/po/{id}', [PurchasingController::class, 'updatePo']);
        Route::delete('/po/{id}', [PurchasingController::class, 'destroyPo']);
        
        Route::post('/{id}/receive', [PurchasingController::class, 'receiveGoods']);
        Route::post('/{id}/invoice', [PurchasingController::class, 'createInvoice']);
        
        Route::get('/po/{id}/outstanding', [PurchasingController::class, 'getOutstandingItems']);
        Route::post('/po/{id}/close', [PurchasingController::class, 'closePo']);
        Route::post('/po/{id}/invoice', [PurchasingController::class, 'createInvoice']);
        
        Route::get('/receipts', [PurchasingController::class, 'getReceiptHistory']);
        Route::delete('/receipts/{id}', [PurchasingController::class, 'voidReceipt']);
    });

    Route::prefix('admin/purchasing/payables')->group(function () {
        Route::get('/accounts', [AccountPayableController::class, 'getAccounts']);
        Route::get('/list', [AccountPayableController::class, 'getPayables']);
        Route::get('/history', [AccountPayableController::class, 'getPaymentHistory']);
        Route::get('/giro', [AccountPayableController::class, 'getPendingGiros']);
        Route::post('/pay', [AccountPayableController::class, 'pay']);
        Route::post('/giro/{id}/clear', [AccountPayableController::class, 'clearGiro']);
        Route::post('/giro/{id}/reject', [AccountPayableController::class, 'rejectGiro']);
        Route::delete('/{id}/void', [AccountPayableController::class, 'voidPayment']);
    });

    Route::prefix('admin/purchasing/returns')->group(function () {
        Route::get('/', [PurchaseReturnController::class, 'index']);
        Route::get('/eligible-purchases', [PurchaseReturnController::class, 'getEligiblePurchases']);
        Route::get('/purchase-items/{purchaseId}', [PurchaseReturnController::class, 'getPurchaseItemsForReturn']);
        Route::post('/', [PurchaseReturnController::class, 'store']);
        Route::delete('/{id}', [PurchaseReturnController::class, 'destroy']);
        Route::post('/{id}/receive-refund', [PurchaseReturnController::class, 'receiveRefund']);
        Route::post('/{id}/receive-replacement', [PurchaseReturnController::class, 'receiveReplacement']);
    });


    // ---------------------------------------------------------------------
    // G. KEUANGAN & AKUNTANSI (FINANCE & ACCOUNTING)
    // ---------------------------------------------------------------------

    Route::prefix('admin/finance')->group(function () {
        Route::get('/accounts', [SalesInvoiceController::class, 'getCashBankAccounts']);

        Route::prefix('invoices')->group(function () {
            Route::get('/ready-print', [SalesInvoiceController::class, 'getReadyPrint']);
            Route::get('/receivables', [SalesInvoiceController::class, 'getReceivables']);
            Route::get('/history', [SalesInvoiceController::class, 'getHistory']);
            Route::post('/authorize-reprint', [SalesInvoiceController::class, 'authorizeReprint']);
            Route::post('/{id}/pay', [SalesInvoiceController::class, 'payInvoice']);
            Route::post('/{id}/mark-printed', [SalesInvoiceController::class, 'markPrinted']);
            Route::get('/{id}', [SalesInvoiceController::class, 'getInvoiceDetail']);
        });

        // Eksekusi Pencairan Gaji
        Route::post('/payroll-disbursements/{id}/pay', [FinancePayrollController::class, 'pay']);
    });

    Route::prefix('admin/receivable-payments')->group(function () {
        Route::get('/unpaid', [ReceivablePaymentController::class, 'getUnpaidReceivables']);
        Route::post('/store', [ReceivablePaymentController::class, 'storePayment']);
        Route::get('/giro/pending', [ReceivablePaymentController::class, 'getPendingGiro']);
        Route::post('/giro/{id}/process', [ReceivablePaymentController::class, 'processGiro']);
        Route::post('/{id}/cancel', [ReceivablePaymentController::class, 'cancelPayment']);
        Route::get('/history', [ReceivablePaymentController::class, 'getPaymentHistory']);
        Route::get('/pending-setoran', [ReceivablePaymentController::class, 'getPendingSetoran']);
        Route::post('/approve-setoran/{id}', [ReceivablePaymentController::class, 'approveSetoran']);
        Route::post('/reject-setoran/{id}', [ReceivablePaymentController::class, 'rejectSetoran']);
    });

    Route::prefix('admin/accounting')->group(function () {
        Route::get('/coas/active', [AccountingMappingApiController::class, 'getActiveCoas']);
        Route::get('/mappings', [AccountingMappingApiController::class, 'getMappings']);
        Route::post('/mappings', [AccountingMappingApiController::class, 'updateMappings']);
        Route::apiResource('coas', AccountingCoaApiController::class);
        Route::get('/journals', [AccountingJournalApiController::class, 'index']);
        Route::get('/laba-rugi', [\App\Http\Controllers\Api\AccountingReportController::class, 'getLabaRugi']);
        Route::get('/periods', [\App\Http\Controllers\Api\AccountingPeriodController::class, 'index']);
        Route::post('/periods/toggle', [\App\Http\Controllers\Api\AccountingPeriodController::class, 'toggleStatus']);
    });

    Route::get('/admin/accounts', [SalesOrderController::class, 'getCashBankAccounts']);
    Route::get('/admin/laporan/neraca', [\App\Http\Controllers\Api\AccountingReportController::class, 'getNeraca']);

    Route::prefix('admin/ledger')->group(function () {
        Route::get('/accounts', [LedgerController::class, 'getCashAccounts']);
        Route::get('/mutations', [LedgerController::class, 'getCashMutations']);
    });

    Route::get('/admin/cash-mutations', [CashMutationApiController::class, 'index']);
    Route::post('/admin/cash-mutations', [CashMutationApiController::class, 'store']);
    Route::get('/journals', [JournalApiController::class, 'index']);

    Route::prefix('admin/expenses')->group(function () {
        Route::get('/', [AdminExpenseController::class, 'index']);
        Route::post('/', [AdminExpenseController::class, 'store']);
        Route::put('/{id}', [AdminExpenseController::class, 'update']);
        Route::delete('/{id}', [AdminExpenseController::class, 'destroy']);
    });

    Route::get('/admin/branch-accounts', [BranchAccountController::class, 'index']);
    Route::post('/admin/branch-accounts/sync', [BranchAccountController::class, 'sync']);

    Route::post('/admin/interbranch-transfers', [InterbranchTransferController::class, 'store']);
    Route::post('/admin/interbranch-transfers/{id}/confirm', [InterbranchTransferController::class, 'confirm']);
    Route::get('/admin/interbranch-transfers', [InterbranchTransferController::class, 'index']);


    // ---------------------------------------------------------------------
    // H. MODUL KANVAS & DROPPING
    // ---------------------------------------------------------------------

    Route::prefix('admin/canvas')->group(function () {
        Route::get('/products', [\App\Http\Controllers\Api\CanvasLoadingController::class, 'getAvailableProducts']);
        Route::get('/loadings', [\App\Http\Controllers\Api\CanvasLoadingController::class, 'index']);
        Route::post('/loadings', [\App\Http\Controllers\Api\CanvasLoadingController::class, 'store']);
        Route::post('/loadings/{id}/void', [\App\Http\Controllers\Api\CanvasLoadingController::class, 'void']);
        Route::post('/loadings/{id}/unload', [\App\Http\Controllers\Api\CanvasLoadingController::class, 'unloadCanvas']);
        Route::post('/loadings/{id}/revise', [\App\Http\Controllers\Api\CanvasLoadingController::class, 'revisePhysicalCount']);
        Route::post('/loadings/{id}/settle', [\App\Http\Controllers\Api\CanvasLoadingController::class, 'settleCanvas']);
    });

    Route::prefix('admin/canvas/sales')->group(function () {
        Route::get('/master-data', [\App\Http\Controllers\Api\CanvasSalesController::class, 'getMasterData']);
        Route::post('/calculate', [\App\Http\Controllers\Api\CanvasSalesController::class, 'calculateCart']);
        Route::post('/store', [\App\Http\Controllers\Api\CanvasSalesController::class, 'storeManualOrder']);
    });

    Route::prefix('admin/canvas-setoran')->group(function () {
        Route::get('/pending', [\App\Http\Controllers\Api\CanvasSetoranController::class, 'getPending']);
        Route::post('/verify/{id}', [\App\Http\Controllers\Api\CanvasSetoranController::class, 'verify']);
    });


    // ---------------------------------------------------------------------
    // I. LOGISTIK & PERSEDIAAN (INVENTORY)
    // ---------------------------------------------------------------------
    
    Route::post('/admin/inventory/transfer', [StockTransferController::class, 'store']);
    Route::get('/admin/inventory/transfer', [StockTransferController::class, 'index']);
    Route::post('/admin/inventory/transfer/{id}/receive', [StockTransferController::class, 'receiveTransit']);
    Route::get('/admin/inventory/transfer/products', [StockTransferController::class, 'getTransferProducts']);
    Route::get('/admin/inventory/transfer/{id}', [StockTransferController::class, 'show']);
    
    Route::post('/admin/inventory/quarantine', [\App\Http\Controllers\Api\StockMutationController::class, 'quarantine']);
    Route::get('/admin/inventory/quarantine/stocks', [\App\Http\Controllers\Api\StockMutationController::class, 'getQuarantinedStocks']);
    Route::post('/admin/inventory/write-off', [\App\Http\Controllers\Api\StockWriteOffController::class, 'store']);
    Route::get('/admin/inventory/write-off', [\App\Http\Controllers\Api\StockWriteOffController::class, 'index']);
    Route::get('/admin/inventory/write-off/{id}', [\App\Http\Controllers\Api\StockWriteOffController::class, 'show']);

    Route::get('/admin/inventory/adjustments/worksheet', [\App\Http\Controllers\Api\StockAdjustmentController::class, 'getWorksheet']);
    Route::post('/admin/inventory/adjustments', [\App\Http\Controllers\Api\StockAdjustmentController::class, 'store']);


    // ---------------------------------------------------------------------
    // J. MANAJEMEN SALESMAN & ARMADA (WEB ADMIN)
    // ---------------------------------------------------------------------

    Route::get('/salesman/today-routes', [\App\Http\Controllers\Api\SalesmanVisitController::class, 'getTodayRoutes']);
    Route::post('/salesman/check-in', [\App\Http\Controllers\Api\SalesmanVisitController::class, 'storeCheckIn']);

    Route::prefix('admin')->group(function () {
        Route::get('/journey-plans', [AdminJourneyPlanController::class, 'index']);
        Route::post('/journey-plans', [AdminJourneyPlanController::class, 'store']);
        Route::put('/journey-plans/{id}', [AdminJourneyPlanController::class, 'update']);
        Route::delete('/journey-plans/{id}', [AdminJourneyPlanController::class, 'destroy']);
    });

    Route::get('/admin/driver-assignments', [\App\Http\Controllers\Api\DriverAssignmentController::class, 'index']);
    Route::get('/admin/driver-assignments/form-data', [\App\Http\Controllers\Api\DriverAssignmentController::class, 'getFormData']);
    Route::post('/admin/driver-assignments', [\App\Http\Controllers\Api\DriverAssignmentController::class, 'store']);
    Route::put('/admin/driver-assignments/{id}', [\App\Http\Controllers\Api\DriverAssignmentController::class, 'update']);
    
    Route::prefix('admin/salesman')->group(function () {
        Route::get('/targets/list-salesmen', [SalesmanTargetController::class, 'getSalesmenList']);
        Route::post('/targets/store', [SalesmanTargetController::class, 'store']);
        Route::get('/targets/achievement', [SalesmanTargetController::class, 'getAchievementReport']);
        Route::get('/targets', [SalesmanTargetController::class, 'index']);
        Route::put('/targets/{id}', [SalesmanTargetController::class, 'update']);
    });


    // ---------------------------------------------------------------------
    // K. LAPORAN & ANALITIK (REPORTS)
    // ---------------------------------------------------------------------

    Route::prefix('admin/reports')->group(function () {
        Route::get('/filter-options', [SalesReportController::class, 'getFilterOptions']);
        Route::get('/sales/rekap', [SalesReportController::class, 'getRekap']);
        Route::get('/sales/detail', [SalesReportController::class, 'getDetail']);
        Route::get('/piutang/analisa', [SalesReportController::class, 'getReceivableAging']);
        Route::get('/piutang/analisa-detail', [SalesReportController::class, 'getReceivableAgingDetail']);
        Route::get('/piutang/faktur-detail', [SalesReportController::class, 'getInvoiceDetail']);
        Route::get('/sales-order', [SalesReportController::class, 'getSalesOrderReport']);
        Route::get('/delivery-order', [SalesReportController::class, 'getDeliveryOrderReport']);
        Route::get('/gagal-kirim', [SalesReportController::class, 'getFailedDeliveryReport']);
        Route::get('/sales-return', [SalesReportController::class, 'getSalesReturnReport']);
        Route::get('/bad-stock', [SalesReportController::class, 'getBadStockReport']);
        Route::get('/due-warning', [SalesReportController::class, 'getDueWarningReport']);
        Route::get('/pareto-pelanggan', [SalesReportController::class, 'getParetoPelanggan']);
        Route::get('/delivery-performance', [\App\Http\Controllers\Api\DeliveryReportController::class, 'getPerformanceReport']);
        Route::get('/stock-movement', [StockMovementController::class, 'getStockPositionReport']);
    });

    Route::prefix('admin/purchasing/reports')->group(function () {
        Route::get('/po', [\App\Http\Controllers\Api\PurchaseReportController::class, 'poReport']);
        Route::get('/receipt', [\App\Http\Controllers\Api\PurchaseReportController::class, 'receiptReport']);
        Route::get('/ap-aging', [\App\Http\Controllers\Api\PurchaseReportController::class, 'apAgingReport']);
        Route::get('/payment', [\App\Http\Controllers\Api\PurchaseReportController::class, 'paymentReport']);
        Route::get('/return', [\App\Http\Controllers\Api\PurchaseReportController::class, 'returnReport']);
        Route::get('/details/{type}/{ref}', [\App\Http\Controllers\Api\PurchaseReportController::class, 'getReportDetails']);
    });

    Route::get('/admin/laporan/target-achievement', [\App\Http\Controllers\Api\TargetReportController::class, 'getTargetAchievement']);
    Route::get('/admin/laporan/sales-performance', [\App\Http\Controllers\Api\TargetReportController::class, 'getTargetAchievement']);


    // ---------------------------------------------------------------------
    // L. FITUR POS (C# / FLUTTER DESKTOP CLIENT)
    // ---------------------------------------------------------------------
    
    Route::get('/pos/products', [PosController::class, 'getProducts']);
    Route::post('/transaction', [PosController::class, 'storeTransaction']);
    Route::get('/history', [PosController::class, 'getHistory']);
    Route::get('/sales/search', [PosController::class, 'searchSale']);
    Route::post('/sales/return', [PosController::class, 'storeReturn']);
    Route::get('/summary', [PosController::class, 'getDailySummary']);
    Route::get('/shift/check', [PosController::class, 'checkShiftStatus']);
    Route::post('/shift/open', [PosController::class, 'openShift']);
    Route::post('/shift/close', [PosController::class, 'closeShift']);
    Route::post('/stock/adjust', [PosController::class, 'storeStockAdjustment']);
    Route::get('/config', [PosController::class, 'getAppConfig']);
    Route::get('/debts', [PosController::class, 'getCustomerDebts']);
    Route::post('/debts/pay', [PosController::class, 'storeDebtPayment']);
    Route::get('/debts/summary', [PosController::class, 'getDebtSummary']);
    Route::get('/debts/{saleId}/history', [PosController::class, 'getDebtHistory']);
    
    Route::post('/hold-cart/save', [HoldCartController::class, 'saveCart']);
    Route::get('/hold-cart', [HoldCartController::class, 'fetchHeldCarts']);
    Route::get('/hold-cart/{id}', [HoldCartController::class, 'loadCart']);
    Route::delete('/hold-cart/{id}', [HoldCartController::class, 'deleteCart']);

    Route::get('/expense-categories', [ExpenseApiController::class, 'getCategories']);
    Route::post('/expenses', [ExpenseApiController::class, 'storeExpense']);
    Route::get('/expenses/today', [ExpenseApiController::class, 'getTodayExpenses']);

    Route::prefix('pos/online-orders')->group(function () {
        Route::get('/pending', [PosOnlineOrderController::class, 'getPendingOrders']);
        Route::post('/process', [PosOnlineOrderController::class, 'processOrder']);
        Route::post('/cancel', [\App\Http\Controllers\Api\OnlineStoreController::class, 'cancelOrder']);
    });


    // ---------------------------------------------------------------------
    // M. DASHBOARD OWNER
    // ---------------------------------------------------------------------
    
    Route::get('/owner/branches', [OwnerController::class, 'getBranches']);
    Route::get('/owner/stats', [OwnerController::class, 'getDashboardStats']);
    Route::get('/owner/top-products', [OwnerController::class, 'getTopProducts']);
    Route::get('/owner/recent-transactions', [OwnerController::class, 'getRecentTransactions']);
    Route::get('/owner/supplier-debts', [OwnerController::class, 'getSupplierDebts']);


    // ---------------------------------------------------------------------
    // N. FITUR PROMOSI & KOMPETITOR
    // ---------------------------------------------------------------------
    
    Route::prefix('admin/promo')->group(function () {
        Route::get('/', [SalesProgramController::class, 'index']);
        Route::post('/', [SalesProgramController::class, 'store']);
        Route::get('/{id}', [SalesProgramController::class, 'show']);
        Route::put('/{id}', [SalesProgramController::class, 'update']);
        Route::delete('/{id}', [SalesProgramController::class, 'destroy']);
    });
    Route::get('/active-promos', [SalesProgramController::class, 'getActivePrograms']);

    Route::prefix('admin/competitors')->group(function () {
        Route::get('/', [AdminCompetitorController::class, 'index']);
        Route::post('/', [AdminCompetitorController::class, 'store']);
        Route::put('/{id}', [AdminCompetitorController::class, 'update']);
        Route::delete('/{id}', [AdminCompetitorController::class, 'destroy']);
        Route::get('/reports/market-insights', [AdminCompetitorController::class, 'getMarketIntelligenceReport']);
        Route::post('/mobile-store', [AdminCompetitorController::class, 'storeMarketIntelFromMobile']);
    });


    // ---------------------------------------------------------------------
    // O. PWA PELANGGAN (AUTHENTICATED)
    // ---------------------------------------------------------------------
    
    Route::prefix('online')->group(function () {
        Route::get('/profile', function (Request $request) {
            return response()->json(['success' => true, 'data' => $request->user()]);
        });
        Route::get('/orders', [OnlineStoreController::class, 'getCustomerOrders']);
        Route::get('/orders/{id}', [OnlineStoreController::class, 'getOrderDetails']);
        Route::post('/change-password', [\App\Http\Controllers\Api\OnlineStoreController::class, 'changePassword']);
        Route::get('/customer-profile', [\App\Http\Controllers\Api\OnlineStoreController::class, 'getCustomerProfile']);
    });


    // ---------------------------------------------------------------------
    // P. JEMBATAN MODUL SUPIR / DROPPING (PWA KURIR)
    // ---------------------------------------------------------------------
    
    Route::prefix('delivery')->group(function () {
        Route::get('/tasks', [DeliveryController::class, 'getTasks']);
        Route::post('/complete/{id}', [DeliveryController::class, 'completeTask']);
        Route::post('/fail/{id}', [DeliveryController::class, 'failTask']);
    });

    Route::post('/mobile/salesman/customers/{id}/update', [SalesmanCustomerController::class, 'updateFromMobile']);

    Route::get('/mobile/canvas/loadings', [\App\Http\Controllers\Api\CanvasLoadingController::class, 'index']);
    Route::get('/mobile/canvas/products', [\App\Http\Controllers\Api\CanvasSalesController::class, 'getCanvasProducts']);
    Route::post('/mobile/canvas/store', [\App\Http\Controllers\Api\CanvasSalesController::class, 'storeManualOrder']);
    Route::get('/admin/canvas-sales/history', [\App\Http\Controllers\Api\CanvasSalesController::class, 'getHistory']);
    Route::post('/admin/canvas-sales/{id}/void', [\App\Http\Controllers\Api\CanvasSalesController::class, 'voidOrder']);

    Route::get('/admin/pos-sales/history', [\App\Http\Controllers\Api\PosController::class, 'getAdminHistory']);
    Route::post('/admin/pos-sales/{id}/void', [\App\Http\Controllers\Api\PosController::class, 'voidSale']);

    // Modul Otorisasi Supervisor
    Route::get('/mobile/supervisor/credit-approvals', [\App\Http\Controllers\Api\SupervisorMobileController::class, 'getCreditApprovals']);
    Route::post('/mobile/supervisor/credit-approval', [\App\Http\Controllers\Api\SupervisorMobileController::class, 'processCreditApproval']);

    // Route untuk Import/Export Massal Excel
    Route::get('/admin/import-export/template/{type}', [\App\Http\Controllers\Api\ImportExportController::class, 'downloadTemplate']);
    Route::post('/admin/import-export/upload/{type}', [\App\Http\Controllers\Api\ImportExportController::class, 'uploadExcel'])->middleware('auth:sanctum');

   // ---------------------------------------------------------------------
    // Q. MODUL PABRIKASI / MANUFAKTUR (NEW)
    // ---------------------------------------------------------------------
    Route::prefix('admin/fabrication')->group(function () {
        Route::get('/formulas', [\App\Http\Controllers\Api\FabricationController::class, 'getFormulas']);
        Route::post('/formulas', [\App\Http\Controllers\Api\FabricationController::class, 'storeFormula']);
        Route::put('/formulas/{id}', [\App\Http\Controllers\Api\FabricationController::class, 'updateFormula']);
        Route::get('/products-by-type', [\App\Http\Controllers\Api\FabricationController::class, 'getProductsByType']);

        Route::get('/orders', [\App\Http\Controllers\Api\FabricationController::class, 'getOrders']);
        Route::post('/orders', [\App\Http\Controllers\Api\FabricationController::class, 'createOrder']);
        Route::post('/orders/{id}/finish', [\App\Http\Controllers\Api\FabricationController::class, 'finishOrder']);
        Route::post('/orders/{id}/unpost', [\App\Http\Controllers\Api\FabricationController::class, 'unpostOrder']);
        Route::post('/orders/{id}/cancel', [\App\Http\Controllers\Api\FabricationController::class, 'cancelOrder']);

        Route::get('/report', [\App\Http\Controllers\Api\FabricationController::class, 'getReport']);
        
        // --- RUTE REKONSILIASI VARIANS (TUTUP BUKU) ---
        Route::post('/close-variance', [\App\Http\Controllers\Api\FabricationController::class, 'closeVariance']);
    });

    // ---------------------------------------------------------------------
    // R. MODUL HRIS & PAYROLL (ENTERPRISE)
    // ---------------------------------------------------------------------
    Route::prefix('admin/hr')->group(function () {

        // --- BAGIAN 1: MASTER DATA (HULU) ---
        // Semua yang bersifat konfigurasi/katalog sistem
        // --- BAGIAN 2: TRANSAKSI & OPERASIONAL (TENGAH/HILIR) ---
        // Jabatan
        Route::get('/system-roles', [PositionController::class, 'getSystemRoles']);
        Route::apiResource('positions', PositionController::class); // Menggantikan get, post, put, delete

        // Karyawan
        Route::apiResource('employees', EmployeeController::class);
        Route::post('/employees/{id}/salary', [EmployeeController::class, 'updateSalary']);

        // Tunjangan Karyawan (Menggunakan nama controller yang disepakati: EmployeeAllowanceController)
        Route::get('/employees/{id}/allowances', [EmployeeAllowanceController::class, 'show']);
        Route::post('/allowances', [EmployeeAllowanceController::class, 'store']);
        Route::delete('/allowances/{id}', [EmployeeAllowanceController::class, 'destroy']);

        // Kasbon
        Route::apiResource('loans', EmployeeLoanController::class)->only(['index', 'store', 'destroy']);

        // Payroll
        Route::get('/payroll-periods', [PayrollController::class, 'getPeriods']);
        Route::get('/payroll-periods/{id}', [PayrollController::class, 'showPeriod']);
        Route::post('/payroll-periods', [PayrollController::class, 'storePeriod']);
        Route::post('/payroll-periods/{id}/approve', [PayrollController::class, 'approvePeriod']);
        Route::get('/payrolls/{id}/print', [PayrollController::class, 'printPayslip']);
        Route::get('/payroll-periods/{id}/export-excel', [\App\Http\Controllers\Api\PayrollController::class, 'exportExcel']);
        Route::get('/payroll-periods/{id}/print-mass', [\App\Http\Controllers\Api\PayrollController::class, 'printMassPayslips']);

        // Kehadiran
        Route::get('/attendances/daily', [AttendanceController::class, 'getDailyAttendance']);
        Route::get('/attendances/summary', [AttendanceController::class, 'getSummary']);
        Route::post('/attendances/bulk', [AttendanceController::class, 'storeBulk']);
        Route::get('/attendances/template', [AttendanceController::class, 'downloadTemplate']);
        Route::post('/attendances/import', [AttendanceController::class, 'importExcel']);
    });

}); // <--- PENUTUP MIDDLEWARE AUTH:SANCTUM UTAMA UNTUK ADMIN/WEB

// --- 1. RUTE MASTER (PUBLIK / BEBAS AUTH) ---
// Ditaruh di luar middleware auth agar tidak memicu error redirect login
Route::prefix('admin/hr/master')->group(function () {
    // Tunjangan
    Route::get('/allowance-types', [MasterAllowanceController::class, 'index']);
    Route::post('/allowance-types', [MasterAllowanceController::class, 'store']);
    Route::put('/allowance-types/{id}', [MasterAllowanceController::class, 'update']);
    Route::delete('/allowance-types/{id}', [MasterAllowanceController::class, 'destroy']);
    
    // Kalender
    Route::get('/calendar', [MasterCalendarController::class, 'index']);
    Route::post('/holidays', [MasterCalendarController::class, 'storeHoliday']);
});

// =========================================================================
// 3. RUTE KHUSUS APLIKASI MOBILE FLUTTER (SALESMAN)
// =========================================================================

Route::prefix('mobile/salesman')->group(function () {
    
    Route::post('/login', [\App\Http\Controllers\Api\SalesmanMobileController::class, 'login']);

    Route::middleware('auth:sanctum')->group(function () {
        Route::get('/profile', [\App\Http\Controllers\Api\SalesmanMobileController::class, 'getProfile']);
        Route::post('/logout', [\App\Http\Controllers\Api\SalesmanMobileController::class, 'logout']);
        
        Route::get('/today-routes', [\App\Http\Controllers\Api\SalesmanMobileVisitController::class, 'getTodayRoutes']);
        Route::post('/check-in', [\App\Http\Controllers\Api\SalesmanMobileVisitController::class, 'storeCheckIn']);
        Route::post('/check-out', [\App\Http\Controllers\Api\SalesmanMobileVisitController::class, 'submitVisitWithPayment']);
        Route::get('/no-order-reasons', [\App\Http\Controllers\Api\SalesmanMobileVisitController::class, 'getNoOrderReasons']);

        Route::get('/catalog', [\App\Http\Controllers\Api\SalesmanMobileOrderController::class, 'getProducts']);
        Route::get('/promos', [\App\Http\Controllers\Api\SalesmanMobileOrderController::class, 'getActivePromos']);
        Route::post('/orders', [\App\Http\Controllers\Api\SalesmanMobileOrderController::class, 'storeOrder']);

        Route::get('/extra-customers', [\App\Http\Controllers\Api\SalesmanMobileVisitController::class, 'getExtraCustomers']);
        Route::get('/order-history', [\App\Http\Controllers\Api\SalesmanMobileOrderController::class, 'getSalesmanOrderHistory']);

        Route::get('/unpaid-invoices/{customerId}', [\App\Http\Controllers\Api\SalesmanMobileVisitController::class, 'getCustomerUnpaidInvoices']);
    });

    

});