<?php

use Illuminate\Support\Facades\Route;
use App\Models\{Category, Product};
use App\Http\Controllers\{
    ProfileController, CategoryController, WishlistController,
    ProductController, ProductVariantController, ProductImageController,
    StockLogController, CartController, DashboardController, OtpController, 
    CheckoutController, OrderController, AddressController, ReviewController, PaymentController
};
use Laravolt\Indonesia\Models\{Province, City, District, Village};

/*
|--------------------------------------------------------------------------
| 1. Public & Webhook Routes
|--------------------------------------------------------------------------
*/
Route::get('/', function () {
    $categories = \App\Models\Category::all();
    $latestProducts = \App\Models\Product::latest()->limit(8)->get();
    
    $topRatedProducts = \App\Models\Product::withAvg('reviews', 'rating') // Menghitung rata-rata kolom 'rating' di tabel 'reviews'
    ->orderByDesc('reviews_avg_rating') 
    ->limit(5)
    ->get();

    return view('welcome', [
        'categories' => $categories,
        'latestProducts' => $latestProducts,
        'topRatedProducts' => $topRatedProducts
    ]);
})->name('home');

Route::post('/verify-otp', [OtpController::class, 'verifyOtp'])->name('verify.otp');
Route::post('/send-otp', [OtpController::class, 'sendRegisterOtp'])->name('send.otp');
Route::post('/webhook/midtrans', [PaymentController::class, 'handleNotification'])->name('payment.notification');

/*
|--------------------------------------------------------------------------
| 2. Admin & Staff Routes (Ditaruh di atas agar /create tidak dianggap ID)
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'role:admin'])->group(function () {
    // Resource Admin (Create, Edit, Store, Update, Destroy)
    Route::resource('categories', CategoryController::class)->except(['index', 'show']);
    Route::resource('products', ProductController::class)->except(['index', 'show']);
    Route::resource('products.variants', ProductVariantController::class);

    // Stock & Product Management
    Route::controller(StockLogController::class)->group(function () {
        Route::get('/stock/riwayat', 'index')->name('stock-logs.index');
        Route::post('/stock/quick-update', 'quickUpdate')->name('stock.quickUpdate');
        Route::get('/stock/download-pdf', 'downloadPDF')->name('stock.pdf');
    });

    Route::post('/products/restock/{variant}', [ProductController::class, 'restock'])->name('products.restock');
    Route::delete('/products/images/{image}', [ProductImageController::class, 'destroy'])->name('products.images.destroy');

    Route::get('/orders/download-rekap', [App\Http\Controllers\OrderController::class, 'downloadAllPDF'])->name('orders.download_all');

    // Order Management
    Route::post('/orders/{order}/confirm', [OrderController::class, 'confirmOrder'])->name('orders.confirm');
    Route::post('/orders/{order}/assign', [OrderController::class, 'assignCourier'])->name('orders.assign');

    Route::get('/orders/financial', [OrderController::class, 'financialReport'])->name('orders.financial');
    Route::get('/orders/financial/pdf', [OrderController::class, 'downloadPDF'])->name('orders.financial.pdf');

    Route::get('/orders/pending-count', [OrderController::class, 'pendingCount'])
    ->name('pending-orders.count')
    ->middleware('auth');

    Route::patch('/products/{product}/toggle-status', [ProductController::class, 'toggleStatus'])->name('products.toggleStatus');
});

/*
|--------------------------------------------------------------------------
| 3. Authenticated Routes (Semua Role)
|--------------------------------------------------------------------------
*/
Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

    // Profile & Address
    Route::controller(ProfileController::class)->group(function () {
        Route::get('/profile', 'show')->name('profile.show');
        Route::get('/profile/edit', 'edit')->name('profile.edit');
        Route::patch('/profile', 'update')->name('profile.update');
        Route::delete('/profile', 'destroy')->name('profile.destroy');
    });

    Route::resource('addresses', AddressController::class);
    Route::post('/addresses/{address}/default', [AddressController::class, 'setDefault'])->name('addresses.default');

    // Catalog (Hanya Read-Only)
    Route::get('/categories', [CategoryController::class, 'index'])->name('categories.index');
    Route::get('/categories/{id}', [CategoryController::class, 'show'])->name('categories.show');
    
    Route::get('/products', [ProductController::class, 'index'])->name('products.index');
    // Rute wildcard {product} diletakkan paling bawah di bagian produk
    Route::get('/products/{product}', [ProductController::class, 'show'])->name('products.show');

    // Orders
    Route::get('/orders', [OrderController::class, 'index'])->name('orders.index');
    Route::get('/orders/{order}', [OrderController::class, 'show'])->name('orders.show');
    Route::get('/orders/{order}/print', [OrderController::class, 'print'])->name('orders.print');
});

/*
|--------------------------------------------------------------------------
| 4. Customer Routes
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'role:customer'])->group(function () {
    Route::post('/wishlist/toggle/{product}', [WishlistController::class, 'toggle'])->name('wishlist.toggle');
    Route::get('/wishlist', [WishlistController::class, 'index'])->name('wishlist.index');
    
    Route::prefix('cart')->name('cart.')->group(function () {
        Route::get('/', [CartController::class, 'index'])->name('index');
        Route::get('/count', fn() => response()->json(['count' => \App\Models\Cart::where('user_id', auth()->id())->count()]))->name('count');
        Route::post('/store', [CartController::class, 'store'])->name('store');
        Route::post('/update/{id}', [CartController::class, 'updateQuantity'])->name('update');
        Route::delete('/remove/{id}', [CartController::class, 'remove'])->name('remove');
        Route::post('/toggle/{id}', [CartController::class, 'toggleSelect'])->name('toggle');
        Route::post('/direct-checkout', [CartController::class, 'directCheckout'])->name('directCheckout');
        Route::post('/toggle-all', [CartController::class, 'toggleAll'])->name('toggle-all');
    });

    Route::get('/checkout', [CheckoutController::class, 'index'])->name('checkout.index');
    Route::post('/checkout/process', [OrderController::class, 'checkout'])->name('checkout.process');
    Route::post('/checkout/snap-token', [CheckoutController::class, 'generateSnapToken'])->name('checkout.snap');
    
    Route::post('/orders/{order}/confirm-received', [OrderController::class, 'confirmReceived'])->name('orders.confirm_received');
    Route::get('/products/{product}/reviews', [ReviewController::class, 'index'])->name('reviews.index');
    Route::post('/products/{product}/reviews', [ReviewController::class, 'store'])->name('reviews.store');
    Route::get('/orders/{order}/recheckout', [OrderController::class, 'recheckout'])->name('orders.recheckout');
});

/*
|--------------------------------------------------------------------------
| 5. Courier Routes
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'role:kurir'])->group(function () {
    Route::post('/orders/{order}/pickup', [OrderController::class, 'courierPickup'])->name('orders.pickup');
    Route::post('/orders/{order}/deliver', [OrderController::class, 'courierDeliver'])->name('orders.deliver');
});

/*
|--------------------------------------------------------------------------
| 6. API Wilayah
|--------------------------------------------------------------------------
*/
Route::prefix('api/wilayah')->name('wilayah.')->group(function () {
    Route::get('/provinces', fn() => Province::all())->name('provinces');
    Route::get('/cities/{code}', fn($code) => City::where('province_code', $code)->get())->name('cities');
    Route::get('/districts/{code}', fn($code) => District::where('city_code', $code)->get())->name('districts');
    Route::get('/villages/{code}', fn($code) => Village::where('district_code', $code)->get())->name('villages');
});

require __DIR__.'/auth.php';