<?php

use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\UserController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\AdminContactController;
use App\Http\Controllers\ProductInquiryController;
use App\Http\Controllers\MaterialController;
use App\Http\Controllers\ProductionController;
use App\Http\Controllers\SaleController;
use App\Http\Controllers\PurchaseController;
use App\Http\Controllers\Admin\BackOfficeIncomeController;
use App\Http\Controllers\Admin\BackOfficeExpenseController;
use App\Http\Controllers\Admin\StockOpnameController;
use Illuminate\Validation\Rule;

// ------------------------------
// PUBLIC ROUTES
// ------------------------------

// Home & Katalog
Route::get('/', [HomeController::class, 'home'])->name('index');

// all produk
Route::get('/all', [HomeController::class, 'all'])->name('all');

// produk terlaris
Route::get('/best-selling', [HomeController::class, 'bestSelling'])->name('best-selling');

// portfolio detail
Route::get('/portfolio/{id}', [HomeController::class, 'portfolioDetail'])->name('portfolio.detail');

// Kontak (redirect to new contact system)
Route::get('/kontak', function () {
    return redirect()->route('guest.contact');
})->name('kontak');

// konsultasi
Route::get('/konsultasi', [HomeController::class, 'konsultasi'])->name('konsultasi');

// kebijakan
Route::get('/kebijakan', [HomeController::class, 'kebijakan'])->name('kebijakan');

// kategori
Route::get('/kategori/{id}', [HomeController::class, 'kategori'])->name('katalog.kategori');

// Detail Produk
Route::get('/product_details/{id}', [ProductController::class, 'productDetails'])->name('product_details');

// Route untuk submit tanya produk (guest-friendly)
Route::post('/product-inquiry', [ProductInquiryController::class, 'store'])->name('product.inquiry.store');

// Guest Contact Routes (tidak perlu login)
Route::get('/contact', [App\Http\Controllers\GuestContactController::class, 'index'])->name('guest.contact');
Route::post('/contact', [App\Http\Controllers\GuestContactController::class, 'store'])->name('guest.contact.store');
Route::get('/track/{trackingCode}', [App\Http\Controllers\GuestContactController::class, 'track'])->name('guest.contact.track');

// Guest Inquiry Routes (tidak perlu login) 
Route::get('/inquiry', [App\Http\Controllers\GuestInquiryController::class, 'index'])->name('guest.inquiry');
Route::get('/inquiry/{inquiry}', [App\Http\Controllers\GuestInquiryController::class, 'show'])->name('guest.inquiry.show');
Route::get('/track-inquiry/{trackingCode}', [App\Http\Controllers\GuestInquiryController::class, 'track'])->name('guest.inquiry.track');

// Customer Delivery Confirmation (Public - tidak perlu login)
Route::get('/confirm-delivery/{id}', [App\Http\Controllers\CustomerConfirmationController::class, 'show'])->name('user.orders.confirm-delivery');
Route::post('/confirm-delivery/{id}', [App\Http\Controllers\CustomerConfirmationController::class, 'confirm'])->name('user.orders.confirm-delivery.submit');
Route::get('/confirmation-success/{id}', [App\Http\Controllers\CustomerConfirmationController::class, 'success'])->name('user.orders.confirmation-success');
Route::post('/inquiry/{inquiry}/accept', [App\Http\Controllers\GuestInquiryController::class, 'accept'])->name('guest.inquiry.accept');
Route::post('/inquiry/{inquiry}/counter', [App\Http\Controllers\GuestInquiryController::class, 'counter'])->name('guest.inquiry.counter');

// Midtrans Notification (webhook) - public (tanpa CSRF)
Route::post('/midtrans/notification', [OrderController::class, 'handleNotification'])
    ->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class])
    ->name('midtrans.notification');

// halaman berdasarkan login admin/user
Route::get('/dashboard', function () {
    if (Auth::check()) {
        if (Auth::user()->user_type === 'admin') {
            return redirect()->route('admin.dashboard');
        } else {
            return redirect()->route('user.dashboard');
        }
    }
    return redirect()->route('login');
})->middleware(['auth', 'verified'])->name('dashboard');

// User Dashboard Routes
Route::middleware(['auth'])->prefix('user')->group(function () {
    Route::get('/dashboard', [App\Http\Controllers\UserDashboardController::class, 'index'])->name('user.dashboard');

    // User Inquiries - Penawaran Produk
    Route::get('/inquiries', [App\Http\Controllers\UserInquiryController::class, 'index'])->name('user.inquiries.index');
    Route::get('/inquiries/{id}', [App\Http\Controllers\UserInquiryController::class, 'show'])->name('user.inquiries.show');

    // User Notifications
    Route::get('/notifications', [App\Http\Controllers\UserNotificationController::class, 'getNotifications'])->name('user.notifications');
    Route::post('/notifications/{id}/mark-read', [App\Http\Controllers\UserNotificationController::class, 'markAsRead'])->name('user.notifications.mark-read');
    Route::post('/notifications/mark-all-read', [App\Http\Controllers\UserNotificationController::class, 'markAllAsRead'])->name('user.notifications.mark-all-read');

    // User Contacts
    Route::get('/contacts/{id}', [App\Http\Controllers\UserContactController::class, 'show'])->name('user.contacts.show');
});

// Admin Notifications (untuk navbar halaman depan) - hanya untuk admin
Route::middleware(['auth'])->group(function () {
    Route::get('/admin-notifications', [App\Http\Controllers\NotificationController::class, 'getNotifications'])->name('admin.notifications.frontend');
    Route::post('/admin-notifications/mark-all-read', [App\Http\Controllers\NotificationController::class, 'markAllAsRead'])->name('admin.notifications.frontend.mark-all-read');
});


// ------------------------------
// AUTH ROUTES
// ------------------------------
Route::middleware('auth')->group(function () {

    // Checkout Routes
    Route::get('/checkout/{product}', [OrderController::class, 'create'])->name('checkout.form');
    Route::post('/checkout/{product}', [OrderController::class, 'store'])->name('checkout.store');

    // Konfirmasi Transfer
    Route::get('/orders/{order}/confirm', [OrderController::class, 'showConfirmForm'])->name('orders.confirm.form');
    Route::post('/orders/{order}/confirm', [OrderController::class, 'confirm'])->name('orders.confirm');

    // View Payment Proof - gunakan {id} untuk menghindari route model binding issue di production
    Route::get('/orders/{id}/proof', [OrderController::class, 'showProof'])->name('orders.proof');

    // Success Page
    Route::get('/orders/{order}/success', [OrderController::class, 'showSuccess'])->name('orders.success');


    // Products (dari sebelumnya)
    Route::get('/products', [ProductController::class, 'indexUser'])->name('products.index');
    Route::get('/products/{product}', [ProductController::class, 'showUser'])->name('products.show');

    // Products Routes - Daftar Produk (sudah didefinisikan di atas, hindari duplikasi)

    // My Orders - User Dashboard
    Route::get('/my-orders', [OrderController::class, 'myOrders'])->name('my.orders.index');
    Route::get('/my-orders/{order}', [OrderController::class, 'myOrderShow'])->name('my.orders.show');  // Opsional: Detail satu order
    Route::post('/my-orders/{id}/cancel-midtrans', [OrderController::class, 'cancelMidtransOrder'])->name('my.orders.cancel-midtrans');
    Route::post('/my-orders/{id}/retry-midtrans', [OrderController::class, 'retryMidtransPayment'])->name('my.orders.retry-midtrans');
    Route::post('/my-orders/{id}/change-payment-method', [OrderController::class, 'changePaymentMethod'])->name('my.orders.change-payment-method');


    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});


// ------------------------------
// ADMIN ROUTES
// ------------------------------
Route::middleware(['admin'])->prefix('admin')->group(function () {
    // Clear Cache Route (untuk cPanel tanpa SSH)
    Route::get('/clear-cache', [App\Http\Controllers\CacheController::class, 'clearAll'])->name('admin.clear-cache');

    // contact sidebar admin
    Route::get('/contacts', [AdminContactController::class, 'index'])->name('admin.contacts.index');
    Route::delete('/contacts/{contact}', [AdminContactController::class, 'destroy'])->name('admin.contacts.destroy');
    Route::post('/contacts/{contact}/reply', [AdminContactController::class, 'reply'])->name('admin.contacts.reply');
    Route::post('/contacts/{contact}/mark-read', [AdminContactController::class, 'markAsRead'])->name('admin.contacts.mark-read');
    Route::post('/contacts/bulk-mark-read', [AdminContactController::class, 'bulkMarkAsRead'])->name('admin.contacts.bulk-mark-read');
    Route::post('/contacts/bulk-mark-unread', [AdminContactController::class, 'bulkMarkAsUnread'])->name('admin.contacts.bulk-mark-unread');
    Route::post('/contacts/bulk-delete', [AdminContactController::class, 'bulkDelete'])->name('admin.contacts.bulk-delete');

    // Notification routes
    Route::get('/notifications', [App\Http\Controllers\NotificationController::class, 'getNotifications'])->name('admin.notifications');
    Route::post('/notifications/{id}/mark-read', [App\Http\Controllers\NotificationController::class, 'markAsRead'])->name('admin.notifications.mark-read');
    Route::post('/notifications/mark-all-read', [App\Http\Controllers\NotificationController::class, 'markAllAsRead'])->name('admin.notifications.mark-all-read');

    // Dashboard Admin
    Route::get('/', [App\Http\Controllers\DashboardController::class, 'index'])->name('admin.dashboard');

    // Test route
    Route::get('/test-create', [App\Http\Controllers\TestController::class, 'testCreate'])->name('admin.test.create');
    Route::get('/test-form-submission', [App\Http\Controllers\TestController::class, 'testFormSubmission'])->name('admin.test.form-submission');

    /**
     * CATEGORIES ROUTES
     */
    Route::get('/categories', [CategoryController::class, 'index'])->name('admin.categories.index');
    Route::get('/categories/create', [CategoryController::class, 'create'])->name('admin.categories.create');
    Route::post('/categories', [CategoryController::class, 'store'])->name('admin.categories.store');
    Route::get('/categories/{id}/edit', [CategoryController::class, 'edit'])->name('admin.categories.edit');
    Route::put('/categories/{id}', [CategoryController::class, 'update'])->name('admin.categories.update');
    Route::delete('/categories/{id}', [CategoryController::class, 'destroy'])->name('admin.categories.destroy');
    Route::delete('/categories/bulk/delete', [CategoryController::class, 'bulkDestroy'])->name('admin.categories.bulkDestroy');

    /**
     * HEROES ROUTES
     */
    Route::get('/heroes', [App\Http\Controllers\Admin\AdminHeroController::class, 'index'])->name('admin.heroes.index');
    Route::get('/heroes/create', [App\Http\Controllers\Admin\AdminHeroController::class, 'create'])->name('admin.heroes.create');
    Route::post('/heroes', [App\Http\Controllers\Admin\AdminHeroController::class, 'store'])->name('admin.heroes.store');
    Route::get('/heroes/{id}/edit', [App\Http\Controllers\Admin\AdminHeroController::class, 'edit'])->name('admin.heroes.edit');
    Route::put('/heroes/{id}', [App\Http\Controllers\Admin\AdminHeroController::class, 'update'])->name('admin.heroes.update');
    Route::delete('/heroes/{id}', [App\Http\Controllers\Admin\AdminHeroController::class, 'destroy'])->name('admin.heroes.destroy');
    Route::delete('/heroes/bulk/delete', [App\Http\Controllers\Admin\AdminHeroController::class, 'bulkDestroy'])->name('admin.heroes.bulkDestroy');

    /**
     * USER MANAGEMENT ROUTES
     */
    Route::get('/users', [App\Http\Controllers\Admin\UserController::class, 'index'])->name('admin.users.index');
    Route::get('/users/create', [App\Http\Controllers\Admin\UserController::class, 'create'])->name('admin.users.create');
    Route::post('/users', [App\Http\Controllers\Admin\UserController::class, 'store'])->name('admin.users.store');
    Route::get('/users/{id}', [App\Http\Controllers\Admin\UserController::class, 'show'])->name('admin.users.show');
    Route::get('/users/{id}/edit', [App\Http\Controllers\Admin\UserController::class, 'edit'])->name('admin.users.edit');
    Route::put('/users/{id}', [App\Http\Controllers\Admin\UserController::class, 'update'])->name('admin.users.update');
    Route::delete('/users/{id}', [App\Http\Controllers\Admin\UserController::class, 'destroy'])->name('admin.users.destroy');
    Route::post('/users/{id}/reset-password', [App\Http\Controllers\Admin\UserController::class, 'resetPassword'])->name('admin.users.reset-password');
    Route::post('/users/{id}/toggle-status', [App\Http\Controllers\Admin\UserController::class, 'toggleStatus'])->name('admin.users.toggle-status');
    Route::post('/users/bulk-action', [App\Http\Controllers\Admin\UserController::class, 'bulkAction'])->name('admin.users.bulk-action');

    /**
     * SETTINGS ROUTES
     */
    Route::get('/settings', [App\Http\Controllers\Admin\SettingsController::class, 'index'])->name('admin.settings.index');
    Route::post('/settings', [App\Http\Controllers\Admin\SettingsController::class, 'update'])->name('admin.settings.update');

    /**
     * MASTER ROUTES - PRODUCTS
     */
    Route::prefix('master/products')->group(function () {
        Route::get('/', [ProductController::class, 'index'])->name('admin.master.products.index');
        Route::get('/create', [ProductController::class, 'create'])->name('admin.master.products.create');
        Route::post('/', [ProductController::class, 'store'])->name('admin.master.products.store');
        Route::get('/{id}', [ProductController::class, 'show'])->name('admin.master.products.show');
        // Preview dan Export template dokumen lengkap produk jasa (PDF)
        Route::get('/{id}/preview-template', [ProductController::class, 'previewTemplate'])->name('admin.master.products.preview-template');
        Route::get('/{id}/export-template', [ProductController::class, 'exportTemplate'])->name('admin.master.products.export-template');
        Route::get('/{id}/edit', [ProductController::class, 'edit'])->name('admin.master.products.edit');
        Route::put('/{id}', [ProductController::class, 'update'])->name('admin.master.products.update');
        Route::delete('/{id}', [ProductController::class, 'destroy'])->name('admin.master.products.destroy');
        Route::delete('/bulk/delete', [ProductController::class, 'bulkDestroy'])->name('admin.master.products.bulkDestroy');
    });

    // Admin Orders - Lihat Pesanan
    Route::get('/master/orders', [OrderController::class, 'adminIndex'])->name('admin.master.orders.index');
    Route::post('/master/orders', [OrderController::class, 'adminStore'])->name('admin.master.orders.store');
    Route::post('/master/orders/backfill-user-ids', [OrderController::class, 'backfillUserIds'])->name('admin.master.orders.backfill-user-ids');
    Route::get('/master/orders/{order}', [OrderController::class, 'adminShow'])->name('admin.master.orders.show');  // Opsional: Detail satu order
    Route::patch('/master/orders/{id}/status', [OrderController::class, 'updateStatus'])->name('admin.master.orders.updateStatus');
    Route::patch('/master/orders/{id}/payment-status', [OrderController::class, 'updatePaymentStatus'])->name('admin.master.orders.updatePaymentStatus');
    Route::patch('/master/orders/{id}/dp-percentage', [OrderController::class, 'updateDpPercentage'])->name('admin.master.orders.updateDpPercentage');
    Route::patch('/master/orders/{id}/production-status', [OrderController::class, 'updateProductionStatus'])->name('admin.master.orders.updateProductionStatus');
    Route::post('/master/orders/{id}/read', [OrderController::class, 'markAsRead'])->name('admin.master.orders.markAsRead');
    // Route khusus admin untuk melihat bukti pembayaran
    Route::get('/master/orders/{id}/proof', [OrderController::class, 'showProof'])->name('admin.master.orders.proof');

    // Product Inquiries
    Route::get('/product-inquiries', [ProductInquiryController::class, 'index'])->name('admin.product-inquiries.index');
    Route::post('/product-inquiries/{id}/read', [ProductInquiryController::class, 'markAsRead'])->name('admin.product-inquiries.read');
    Route::post('/product-inquiries/{inquiry}/reply', [ProductInquiryController::class, 'reply'])->name('admin.product-inquiries.reply');
    Route::post('/product-inquiries/{inquiry}/follow-up', [ProductInquiryController::class, 'followUp'])->name('admin.product-inquiries.follow-up');
    Route::delete('/product-inquiries/{id}', [ProductInquiryController::class, 'destroy'])->name('admin.product-inquiries.destroy');
    Route::post('/product-inquiries/bulk-mark-read', [ProductInquiryController::class, 'bulkMarkAsRead'])->name('admin.product-inquiries.bulk-mark-read');
    Route::post('/product-inquiries/bulk-mark-unread', [ProductInquiryController::class, 'bulkMarkAsUnread'])->name('admin.product-inquiries.bulk-mark-unread');
    Route::post('/product-inquiries/bulk-delete', [ProductInquiryController::class, 'bulkDelete'])->name('admin.product-inquiries.bulk-delete');

    // Quotation workflow routes
    Route::post('/product-inquiries/{id}/forward-supervisor', [ProductInquiryController::class, 'forwardToSupervisor'])->name('admin.product-inquiries.forward-supervisor');
    Route::post('/product-inquiries/{id}/forward-teknisi', [ProductInquiryController::class, 'forwardToTeknisi'])->name('admin.product-inquiries.forward-teknisi');
    Route::post('/product-inquiries/{id}/final-approval', [ProductInquiryController::class, 'finalApproval'])->name('admin.product-inquiries.final-approval');
    Route::post('/product-inquiries/{id}/convert-to-order', [ProductInquiryController::class, 'convertToOrder'])->name('admin.product-inquiries.convert-to-order');
    Route::get('/product-inquiries/get-user-address', [ProductInquiryController::class, 'getUserAddress'])->name('admin.product-inquiries.get-user-address');

    /**
     * MASTER ROUTES - MATERIALS
     */
    Route::prefix('master/materials')->group(function () {
        Route::get('/', [MaterialController::class, 'index'])->name('admin.master.materials.index');
        Route::get('/create', [MaterialController::class, 'create'])->name('admin.master.materials.create');
        Route::post('/', [MaterialController::class, 'store'])->name('admin.master.materials.store');
        Route::get('/{id}', [MaterialController::class, 'show'])->name('admin.master.materials.show');
        Route::get('/{id}/edit', [MaterialController::class, 'edit'])->name('admin.master.materials.edit');
        Route::put('/{id}', [MaterialController::class, 'update'])->name('admin.master.materials.update');
        Route::delete('/{id}', [MaterialController::class, 'destroy'])->name('admin.master.materials.destroy');
        Route::delete('/bulk/delete', [MaterialController::class, 'bulkDestroy'])->name('admin.master.materials.bulkDestroy');
    });

    /**
     * MASTER ROUTES - SPAREPARTS (Redirect to materials)
     */
    Route::prefix('master/spareparts')->group(function () {
        Route::get('/', function() { return redirect()->route('admin.master.materials.index'); })->name('admin.master.spareparts.index');
        Route::get('/create', function() { return redirect()->route('admin.master.materials.create', ['type' => 'sparepart']); })->name('admin.master.spareparts.create');
        Route::post('/', [MaterialController::class, 'store'])->name('admin.master.spareparts.store');
        Route::get('/{id}', function($id) { return redirect()->route('admin.master.materials.show', ['id' => $id, 'type' => 'sparepart']); })->name('admin.master.spareparts.show');
        Route::get('/{id}/edit', function($id) { return redirect()->route('admin.master.materials.edit', ['id' => $id, 'type' => 'sparepart']); })->name('admin.master.spareparts.edit');
        Route::put('/{id}', [MaterialController::class, 'update'])->name('admin.master.spareparts.update');
        Route::delete('/{id}', [MaterialController::class, 'destroy'])->name('admin.master.spareparts.destroy');
    });


    /**
     * PRODUCTIONS ROUTES (Separated from Master)
     * Catatan: Route spesifik (complete, cancel) harus SEBELUM route dinamis ({production})
     */
    Route::prefix('productions')->group(function () {
        // List
        Route::get('/', [ProductionController::class, 'index'])->name('admin.productions.index');

        // Action Routes (HARUS SEBELUM route dinamis!)
        Route::post('/{production}/complete', [ProductionController::class, 'complete'])
            ->name('admin.productions.complete');
        Route::post('/{production}/cancel', [ProductionController::class, 'cancel'])
            ->name('admin.productions.cancel');
        Route::post('/{production}/assign-teknisi', [ProductionController::class, 'assignToTeknisi'])
            ->name('admin.productions.assign-teknisi');
        Route::post('/{production}/unassign-teknisi', [ProductionController::class, 'unassignFromTeknisi'])
            ->name('admin.productions.unassign-teknisi');
        Route::post('/{production}/prepare-materials', [ProductionController::class, 'prepareMaterials'])
            ->name('admin.productions.prepare-materials');
        Route::post('/{production}/prepare-spareparts', [ProductionController::class, 'prepareSpareparts'])
            ->name('admin.productions.prepare-spareparts');
        // Admin: Input bahan/sparepart sebagai suggested
        Route::post('/{production}/suggest-materials-spareparts', [ProductionController::class, 'suggestMaterialsAndSpareparts'])
            ->name('admin.productions.suggest-materials-spareparts');
        // Admin: Kirim bahan/sparepart ke teknisi
        Route::post('/{production}/send-to-teknisi', [ProductionController::class, 'sendToTeknisi'])
            ->name('admin.productions.send-to-teknisi');

        // Standard Resource Routes
        Route::get('/{production}', [ProductionController::class, 'show'])->name('admin.productions.show');
        Route::put('/{production}', [ProductionController::class, 'update'])->name('admin.productions.update');
        Route::delete('/{production}', [ProductionController::class, 'destroy'])->name('admin.productions.destroy');

        // Utilities
        Route::post('/check-stock', [ProductionController::class, 'checkStock'])
            ->name('admin.productions.check-stock');
        
        // Item Request Management
        Route::post('/{production}/item-requests/{itemRequest}/approve', [ProductionController::class, 'approveItemRequest'])
            ->name('admin.productions.item-requests.approve');
        Route::post('/{production}/item-requests/{itemRequest}/reject', [ProductionController::class, 'rejectItemRequest'])
            ->name('admin.productions.item-requests.reject');
        Route::post('/{production}/item-requests/{itemRequest}/mark-purchased', [ProductionController::class, 'markItemRequestPurchased'])
            ->name('admin.productions.item-requests.mark-purchased');
        Route::post('/{production}/item-requests/{itemRequest}/send', [ProductionController::class, 'sendItemRequest'])
            ->name('admin.productions.send-item-request');
        
        // Check all stock availability
        Route::get('/{production}/check-all-stock', [ProductionController::class, 'checkAllStockAvailability'])
            ->name('admin.productions.check-all-stock');
    });


    /**
     * TRANSACTION ROUTES - TRANSAKSI
     */

    /**
     * SALES(PENJUALAN) ROUTES - DEPRECATED
     * 
     * Data Sale sekarang ditampilkan dalam menu Orders dengan tab terpisah
     * Route ini tetap ada untuk kompatibilitas dengan link yang sudah ada
     */
    Route::prefix('transaksi/sales')->group(function () {
        Route::get('/', [SaleController::class, 'index'])->name('admin.transaksi.sales.index');
        Route::get('/{sale}', [SaleController::class, 'show'])->name('admin.transaksi.sales.show');
    });

    /**
     * PURCHASES(PEMBELIAN) ROUTES
     */
    Route::prefix('transaksi/purchases')->group(function () {
        Route::get('/', [PurchaseController::class, 'index'])->name('admin.transaksi.purchases.index');
        Route::get('/create', [PurchaseController::class, 'create'])->name('admin.transaksi.purchases.create');
        Route::post('/', [PurchaseController::class, 'store'])->name('admin.transaksi.purchases.store');
        Route::get('/{purchase}', [PurchaseController::class, 'show'])->name('admin.transaksi.purchases.show');
        Route::get('/{purchase}/preview-pdf', [PurchaseController::class, 'previewPdf'])->name('admin.transaksi.purchases.preview-pdf');
        Route::get('/{purchase}/download-pdf', [PurchaseController::class, 'downloadPdf'])->name('admin.transaksi.purchases.download-pdf');
        Route::get('/{purchase}/edit', [PurchaseController::class, 'edit'])->name('admin.transaksi.purchases.edit');
        Route::put('/{purchase}', [PurchaseController::class, 'update'])->name('admin.transaksi.purchases.update');
        Route::delete('/{purchase}', [PurchaseController::class, 'destroy'])->name('admin.transaksi.purchases.destroy');
    });

    // ============================================
    // BACK OFFICE - PEMASUKAN (INCOME)
    // ============================================
    Route::prefix('backoffice/income')
        ->name('admin.backoffice.income.')
        ->group(function () {
            Route::get('/', [BackOfficeIncomeController::class, 'index'])->name('index');
            Route::get('/create', [BackOfficeIncomeController::class, 'create'])->name('create');
            Route::post('/', [BackOfficeIncomeController::class, 'store'])->name('store');
            Route::get('/{id}', [BackOfficeIncomeController::class, 'show'])->name('show');
            Route::get('/{id}/edit', [BackOfficeIncomeController::class, 'edit'])->name('edit');
            Route::put('/{id}', [BackOfficeIncomeController::class, 'update'])->name('update');
            Route::delete('/{id}', [BackOfficeIncomeController::class, 'destroy'])->name('destroy');
        });


    // ============================================
    // BACK OFFICE - PENGELUARAN (EXPENSE)
    // ============================================
    Route::prefix('backoffice/expense')
        ->name('admin.backoffice.expense.')
        ->group(function () {
            Route::get('/', [BackOfficeExpenseController::class, 'index'])->name('index');
            Route::get('/create', [BackOfficeExpenseController::class, 'create'])->name('create');
            Route::post('/', [BackOfficeExpenseController::class, 'store'])->name('store');
            Route::get('/{id}', [BackOfficeExpenseController::class, 'show'])->name('show');
            Route::get('/{id}/edit', [BackOfficeExpenseController::class, 'edit'])->name('edit');
            Route::put('/{id}', [BackOfficeExpenseController::class, 'update'])->name('update');
            Route::delete('/{id}', [BackOfficeExpenseController::class, 'destroy'])->name('destroy');
        });

    // ============================================
    // BACK OFFICE - STOCK OPNAME
    // ============================================
    Route::prefix('backoffice/stock-opname')
        ->name('admin.backoffice.stock-opname.')
        ->group(function () {
            Route::get('/', [StockOpnameController::class, 'index'])->name('index');
            Route::get('/create', [StockOpnameController::class, 'create'])->name('create');
            Route::post('/', [StockOpnameController::class, 'store'])->name('store');
            Route::get('/{id}', [StockOpnameController::class, 'show'])->name('show');
            Route::get('/{id}/edit', [StockOpnameController::class, 'edit'])->name('edit');
            Route::put('/{id}', [StockOpnameController::class, 'update'])->name('update');
            Route::delete('/{id}', [StockOpnameController::class, 'destroy'])->name('destroy');

            // Approve stock opname
            Route::post('/{id}/approve', [StockOpnameController::class, 'approve'])->name('approve');

            // API untuk get items (digunakan di form create/edit)
            Route::get('/api/items', [StockOpnameController::class, 'getItems'])->name('api.items');
        });

    // ============================================
    // BACK OFFICE - CATATAN PIUTANG
    // ============================================
    Route::prefix('receivables')
        ->name('admin.receivables.')
        ->group(function () {
            // Standard routes
            Route::get('/', [App\Http\Controllers\Admin\ReceivableController::class, 'index'])->name('index');
            Route::get('/export', [App\Http\Controllers\Admin\ReceivableController::class, 'export'])->name('export');
            Route::get('/dashboard', [App\Http\Controllers\Admin\ReceivableController::class, 'dashboard'])->name('dashboard');

            // Dynamic routes (harus di bawah untuk avoid conflict)
            Route::get('/{receivable}', [App\Http\Controllers\Admin\ReceivableController::class, 'show'])->name('show');
            Route::get('/{receivable}/create-payment', [App\Http\Controllers\Admin\ReceivableController::class, 'createPayment'])->name('create-payment');
            Route::post('/{receivable}/store-payment', [App\Http\Controllers\Admin\ReceivableController::class, 'storePayment'])->name('store-payment');
            Route::put('/{receivable}/update-due-date', [App\Http\Controllers\Admin\ReceivableController::class, 'updateDueDate'])->name('update-due-date');
            Route::put('/{receivable}/update-notes', [App\Http\Controllers\Admin\ReceivableController::class, 'updateNotes'])->name('update-notes');
            Route::put('/{receivable}/cancel', [App\Http\Controllers\Admin\ReceivableController::class, 'cancel'])->name('cancel');
        });

    // ============================================
    // PRINT ROUTES
    // ============================================
    Route::prefix('print')->name('admin.print.')->group(function () {
        // Preview routes (untuk lihat dulu)
        Route::get('/order/{order}/invoice', [App\Http\Controllers\Admin\PrintController::class, 'orderInvoicePreview'])->name('order.invoice');
        Route::get('/receivable/{receivable}/receipt', [App\Http\Controllers\Admin\PrintController::class, 'receivableReceiptPreview'])->name('receivable.receipt');
        Route::get('/sale/{sale}/invoice', [App\Http\Controllers\Admin\PrintController::class, 'salesInvoicePreview'])->name('sale.invoice');

        // Download PDF routes
        Route::get('/order/{order}/invoice/download', [App\Http\Controllers\Admin\PrintController::class, 'orderInvoice'])->name('order.invoice.download');
        Route::get('/receivable/{receivable}/receipt/download', [App\Http\Controllers\Admin\PrintController::class, 'receivableReceipt'])->name('receivable.receipt.download');
        Route::get('/sale/{sale}/invoice/download', [App\Http\Controllers\Admin\PrintController::class, 'salesInvoice'])->name('sale.invoice.download');
        // Quotation offer
        Route::get('/quotation/{inquiry}/offer', [App\Http\Controllers\Admin\PrintController::class, 'quotationOffer'])->name('quotation.offer');
        Route::get('/quotation/{inquiry}/offer/preview', [App\Http\Controllers\Admin\PrintController::class, 'quotationOfferPreview'])->name('quotation.offer.preview');
    });

    // ============================================
    // HANDOVER / SERAH TERIMA
    // ============================================
    Route::prefix('handover')->name('admin.handover.')->group(function () {
        Route::get('/', [App\Http\Controllers\Admin\HandoverController::class, 'index'])->name('index');
        Route::get('/{order}', [App\Http\Controllers\Admin\HandoverController::class, 'show'])->name('show');
        Route::post('/{order}/prepare', [App\Http\Controllers\Admin\HandoverController::class, 'prepare'])->name('prepare');
        Route::post('/{order}/deliver', [App\Http\Controllers\Admin\HandoverController::class, 'deliver'])->name('deliver');
        Route::post('/{order}/force-complete', [App\Http\Controllers\Admin\HandoverController::class, 'forceComplete'])->name('force-complete');
        Route::get('/{order}/print', [App\Http\Controllers\Admin\HandoverController::class, 'printDocument'])->name('print');
    });

    // ============================================
    // LAPORAN ROUTES
    // ============================================
    Route::prefix('reports')->name('admin.reports.')->group(function () {
        // Laporan Penjualan
        Route::get('/sales', [App\Http\Controllers\Admin\ReportController::class, 'sales'])->name('sales');
        Route::get('/sales/export', [App\Http\Controllers\Admin\ReportController::class, 'salesExport'])->name('sales.export');
        Route::get('/sales/pdf', [App\Http\Controllers\Admin\ReportController::class, 'salesPdf'])->name('sales.pdf');

        // Laporan Pembelian
        Route::get('/purchases', [App\Http\Controllers\Admin\ReportController::class, 'purchases'])->name('purchases');
        Route::get('/purchases/export', [App\Http\Controllers\Admin\ReportController::class, 'purchasesExport'])->name('purchases.export');
        Route::get('/purchases/pdf', [App\Http\Controllers\Admin\ReportController::class, 'purchasesPdf'])->name('purchases.pdf');

        // Laporan Barang Limit
        Route::get('/stock-limit', [App\Http\Controllers\Admin\ReportController::class, 'stockLimit'])->name('stock-limit');
        Route::get('/stock-limit/export', [App\Http\Controllers\Admin\ReportController::class, 'stockLimitExport'])->name('stock-limit.export');
        Route::get('/stock-limit/pdf', [App\Http\Controllers\Admin\ReportController::class, 'stockLimitPdf'])->name('stock-limit.pdf');

        // Laporan Barang Rusak
        Route::get('/damaged-items', [App\Http\Controllers\Admin\ReportController::class, 'damagedItems'])->name('damaged-items');
        Route::get('/damaged-items/export', [App\Http\Controllers\Admin\ReportController::class, 'damagedItemsExport'])->name('damaged-items.export');
        Route::get('/damaged-items/pdf', [App\Http\Controllers\Admin\ReportController::class, 'damagedItemsPdf'])->name('damaged-items.pdf');

        // Laporan Produksi
        Route::get('/productions', [App\Http\Controllers\Admin\ReportController::class, 'productions'])->name('productions');
        Route::get('/productions/export', [App\Http\Controllers\Admin\ReportController::class, 'productionsExport'])->name('productions.export');
        Route::get('/productions/pdf', [App\Http\Controllers\Admin\ReportController::class, 'productionsPdf'])->name('productions.pdf');
    });
});

// ============================================
// SUPERVISOR ROUTES
// ============================================
Route::middleware(['auth', 'supervisor'])->prefix('supervisor')->name('supervisor.')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'supervisorDashboard'])->name('dashboard');
    
    // Supervisor Notifications
    Route::get('/notifications', [App\Http\Controllers\Supervisor\NotificationController::class, 'getNotifications'])->name('notifications');
    Route::post('/notifications/{id}/mark-read', [App\Http\Controllers\Supervisor\NotificationController::class, 'markAsRead'])->name('notifications.mark-read');
    Route::post('/notifications/mark-all-read', [App\Http\Controllers\Supervisor\NotificationController::class, 'markAllAsRead'])->name('notifications.mark-all-read');

    // Approval routes
    Route::prefix('approvals')->name('approvals.')->group(function () {
        Route::get('/', [App\Http\Controllers\Supervisor\ApprovalController::class, 'index'])->name('index');
        Route::get('/orders', [App\Http\Controllers\Supervisor\ApprovalController::class, 'orders'])->name('orders');
        Route::post('/orders/{order}/approve', [App\Http\Controllers\Supervisor\ApprovalController::class, 'approveOrder'])->name('orders.approve');
        Route::post('/orders/{order}/reject', [App\Http\Controllers\Supervisor\ApprovalController::class, 'rejectOrder'])->name('orders.reject');
        Route::post('/productions/{production}/approve', [App\Http\Controllers\Supervisor\ApprovalController::class, 'approveProduction'])->name('productions.approve');
        Route::post('/purchases/{purchase}/approve', [App\Http\Controllers\Supervisor\ApprovalController::class, 'approvePurchase'])->name('purchases.approve');
        Route::post('/purchases/{purchase}/reject', [App\Http\Controllers\Supervisor\ApprovalController::class, 'rejectPurchase'])->name('purchases.reject');
    });

    // Monitoring routes (read-only)
    Route::prefix('monitoring')->name('monitoring.')->group(function () {
        Route::get('/orders', [App\Http\Controllers\Supervisor\MonitoringController::class, 'orders'])->name('orders');
        Route::get('/productions', [App\Http\Controllers\Supervisor\MonitoringController::class, 'productions'])->name('productions');
        Route::get('/sales', [App\Http\Controllers\Supervisor\MonitoringController::class, 'sales'])->name('sales');
        Route::get('/purchases', [App\Http\Controllers\Supervisor\MonitoringController::class, 'purchases'])->name('purchases');
    });

    // Quotation routes
    Route::prefix('quotations')->name('quotations.')->group(function () {
        Route::get('/', [App\Http\Controllers\Supervisor\QuotationController::class, 'index'])->name('index');
        Route::post('/{id}/approve', [App\Http\Controllers\Supervisor\QuotationController::class, 'approve'])->name('approve');
        Route::post('/{id}/reject', [App\Http\Controllers\Supervisor\QuotationController::class, 'reject'])->name('reject');
    });

    // Reports routes (read-only)
    Route::prefix('reports')->name('reports.')->group(function () {
        Route::get('/sales', [App\Http\Controllers\Supervisor\ReportController::class, 'sales'])->name('sales');
        Route::get('/purchases', [App\Http\Controllers\Supervisor\ReportController::class, 'purchases'])->name('purchases');
        Route::get('/productions', [App\Http\Controllers\Supervisor\ReportController::class, 'productions'])->name('productions');
        Route::get('/stock-limit', [App\Http\Controllers\Supervisor\ReportController::class, 'stockLimit'])->name('stock-limit');
        Route::get('/damaged-items', [App\Http\Controllers\Supervisor\ReportController::class, 'damagedItems'])->name('damaged-items');
    });

    // Production approval routes
    Route::prefix('productions')->name('productions.')->group(function () {
        Route::get('/', [App\Http\Controllers\Supervisor\ProductionController::class, 'index'])->name('index');
        Route::get('/{production}', [App\Http\Controllers\Supervisor\ProductionController::class, 'show'])->name('show');
        Route::post('/{production}/approve', [App\Http\Controllers\Supervisor\ProductionController::class, 'approve'])->name('approve');
        Route::post('/{production}/reject', [App\Http\Controllers\Supervisor\ProductionController::class, 'reject'])->name('reject');
        Route::post('/{production}/approve-completion', [App\Http\Controllers\Supervisor\ProductionController::class, 'approveCompletion'])->name('approve-completion');
        Route::post('/{production}/reject-completion', [App\Http\Controllers\Supervisor\ProductionController::class, 'rejectCompletion'])->name('reject-completion');
    });

    // Purchase approval routes
    Route::prefix('purchases')->name('purchases.')->group(function () {
        Route::get('/', [App\Http\Controllers\Supervisor\PurchaseController::class, 'index'])->name('index');
        Route::get('/{purchase}', [App\Http\Controllers\Supervisor\PurchaseController::class, 'show'])->name('show');
        Route::post('/{purchase}/approve', [App\Http\Controllers\Supervisor\PurchaseController::class, 'approve'])->name('approve');
        Route::post('/{purchase}/reject', [App\Http\Controllers\Supervisor\PurchaseController::class, 'reject'])->name('reject');
    });
});

// ============================================
// TEKNISI ROUTES
// ============================================
Route::middleware(['auth', 'teknisi'])->prefix('teknisi')->name('teknisi.')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'teknisiDashboard'])->name('dashboard');

    // Production routes
    Route::prefix('productions')->name('productions.')->group(function () {
        // Static routes harus sebelum dynamic routes
        Route::get('/', [App\Http\Controllers\Teknisi\ProductionController::class, 'index'])->name('index');
        Route::get('/history', [App\Http\Controllers\Teknisi\ProductionController::class, 'history'])->name('history');
        Route::get('/history/{production}', [App\Http\Controllers\Teknisi\ProductionController::class, 'showHistory'])->name('history.show');
        
        // Dynamic routes dengan production parameter
        Route::get('/{production}', [App\Http\Controllers\Teknisi\ProductionController::class, 'show'])->name('show');
        
        // POST routes untuk actions
        Route::post('/{production}/materials', [App\Http\Controllers\Teknisi\ProductionController::class, 'addMaterials'])->name('materials.add');
        Route::put('/{production}/materials/{productionMaterial}/revise', [App\Http\Controllers\Teknisi\ProductionController::class, 'reviseMaterial'])->name('materials.revise');
        Route::delete('/{production}/materials/{productionMaterial}', [App\Http\Controllers\Teknisi\ProductionController::class, 'deleteMaterial'])->name('materials.delete');
        Route::post('/{production}/spareparts', [App\Http\Controllers\Teknisi\ProductionController::class, 'addSpareparts'])->name('spareparts.add');
        Route::put('/{production}/spareparts/{productionSparepart}/revise', [App\Http\Controllers\Teknisi\ProductionController::class, 'reviseSparepart'])->name('spareparts.revise');
        Route::delete('/{production}/spareparts/{productionSparepart}', [App\Http\Controllers\Teknisi\ProductionController::class, 'deleteSparepart'])->name('spareparts.delete');
        Route::post('/{production}/update-status', [App\Http\Controllers\Teknisi\ProductionController::class, 'updateStatus'])->name('update-status');
        Route::post('/{production}/submit', [App\Http\Controllers\Teknisi\ProductionController::class, 'submit'])->name('submit');
        Route::post('/{production}/start', [App\Http\Controllers\Teknisi\ProductionController::class, 'startProduction'])->name('start');
        Route::post('/{production}/revise', [App\Http\Controllers\Teknisi\ProductionController::class, 'revisePlanning'])->name('revise');
        Route::post('/{production}/labor-cost', [App\Http\Controllers\Teknisi\ProductionController::class, 'updateLaborCost'])->name('labor-cost');
        Route::post('/{production}/submit-completion', [App\Http\Controllers\Teknisi\ProductionController::class, 'submitCompletion'])->name('submit-completion');
        Route::post('/{production}/confirm-materials', [App\Http\Controllers\Teknisi\ProductionController::class, 'confirmMaterialsReceived'])->name('confirm-materials');
        Route::post('/{production}/confirm-spareparts', [App\Http\Controllers\Teknisi\ProductionController::class, 'confirmSparepartsReceived'])->name('confirm-spareparts');
        
        // Checklist individual item
        Route::post('/{production}/materials/{productionMaterial}/toggle-received', [App\Http\Controllers\Teknisi\ProductionController::class, 'toggleMaterialReceived'])->name('materials.toggle-received');
        Route::post('/{production}/spareparts/{productionSparepart}/toggle-received', [App\Http\Controllers\Teknisi\ProductionController::class, 'toggleSparepartReceived'])->name('spareparts.toggle-received');
        
        // Bulk confirm
        Route::post('/{production}/bulk-confirm-materials', [App\Http\Controllers\Teknisi\ProductionController::class, 'bulkConfirmMaterials'])->name('bulk-confirm-materials');
        Route::post('/{production}/bulk-confirm-spareparts', [App\Http\Controllers\Teknisi\ProductionController::class, 'bulkConfirmSpareparts'])->name('bulk-confirm-spareparts');
        Route::post('/{production}/confirm-all-items', [App\Http\Controllers\Teknisi\ProductionController::class, 'confirmAllItemsReceived'])->name('confirm-all-items');
        
        // Request item baru/tambahan
        Route::post('/{production}/request-item', [App\Http\Controllers\Teknisi\ProductionController::class, 'requestItem'])->name('request-item');
        Route::post('/{production}/confirm-item-request/{itemRequest}', [App\Http\Controllers\Teknisi\ProductionController::class, 'confirmItemRequest'])->name('confirm-item-request');
        
        // Submit hasil produksi
        Route::post('/{production}/submit-result', [App\Http\Controllers\Teknisi\ProductionController::class, 'submitProductionResult'])->name('submit-result');
    });

    // Stock routes
    Route::prefix('materials')->name('materials.')->group(function () {
        Route::get('/', [App\Http\Controllers\Teknisi\MaterialController::class, 'index'])->name('index');
    });

    Route::prefix('spareparts')->name('spareparts.')->group(function () {
        Route::get('/', [App\Http\Controllers\Teknisi\SparepartController::class, 'index'])->name('index');
    });

    // Quotation routes
    Route::prefix('quotations')->name('quotations.')->group(function () {
        Route::get('/', [App\Http\Controllers\Teknisi\QuotationController::class, 'index'])->name('index');
        Route::post('/{id}/estimate', [App\Http\Controllers\Teknisi\QuotationController::class, 'estimate'])->name('estimate');
        Route::post('/{id}/mark-read', [App\Http\Controllers\Teknisi\QuotationController::class, 'markAsRead'])->name('mark-read');
        Route::get('/materials/search', [App\Http\Controllers\Teknisi\QuotationController::class, 'materialsSearch'])->name('materials.search');
        Route::get('/spareparts/search', [App\Http\Controllers\Teknisi\QuotationController::class, 'sparepartsSearch'])->name('spareparts.search');
    });

    // Notification routes
    Route::get('/notifications', [App\Http\Controllers\Teknisi\NotificationController::class, 'getNotifications'])->name('notifications');
    Route::post('/notifications/{id}/mark-read', [App\Http\Controllers\Teknisi\NotificationController::class, 'markAsRead'])->name('notifications.mark-read');
    Route::post('/notifications/mark-all-read', [App\Http\Controllers\Teknisi\NotificationController::class, 'markAllAsRead'])->name('notifications.mark-all-read');

    // Reports routes (own-only)
    Route::prefix('reports')->name('reports.')->group(function () {
        Route::get('/productions', [App\Http\Controllers\Teknisi\ReportController::class, 'productions'])->name('productions');
        Route::get('/productions/{production}', [App\Http\Controllers\Teknisi\ReportController::class, 'showProduction'])->name('productions.show');
    });
});


require __DIR__ . '/auth.php';
