<?php
// routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\CartController;
use App\Http\Controllers\AddressController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\StockHistoryController;
use App\Http\Controllers\ShippingController;
use App\Http\Controllers\InvoiceController;

/*
|--------------------------------------------------------------------------
| PUBLIC ROUTES
|--------------------------------------------------------------------------
*/

Route::get('/', fn() => redirect()->route('product.index'));

Route::get('/products', [ProductController::class, 'index'])->name('product.index');
Route::get('/products/{id}', [ProductController::class, 'show'])
    ->whereNumber('id')
    ->name('product.show');

/*
|--------------------------------------------------------------------------
| DASHBOARD
|--------------------------------------------------------------------------
*/

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

    // NOTIFICATION (admin & user bisa akses)
    Route::post('/notifications/{id}/mark-as-read', [DashboardController::class, 'markNotificationAsRead']);
    Route::post('/notifications/mark-all-as-read', [DashboardController::class, 'markAllNotificationsAsRead']);

    // PROFILE (semua role bisa akses)
    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');
});

Route::middleware(['auth'])->group(function () {
    Route::post('/api/shipping/calculate', [ShippingController::class, 'calculate'])
        ->name('shipping.calculate');
});
/*
|--------------------------------------------------------------------------
| USER ROUTES (AUTH ONLY)
|--------------------------------------------------------------------------
*/

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

    // CART
    Route::get('/cart', [CartController::class, 'index'])->name('cart.index');
    Route::post('/cart/add', [CartController::class, 'store'])->name('cart.store');
    Route::post('/cart/increase/{cart_id}', [CartController::class, 'increase'])->name('cart.increase');
    Route::post('/cart/decrease/{cart_id}', [CartController::class, 'decrease'])->name('cart.decrease');
    Route::delete('/cart/{cart_id}', [CartController::class, 'destroy'])->name('cart.destroy');
    Route::post('/cart/batch-delete', [CartController::class, 'batchDelete'])->name('cart.batchDelete');

    // ─── CHECKOUT PREVIEW (BELUM MASUK DB) ────────────────────────────────
    // POST: dipanggil saat user klik "Checkout" dari keranjang
    Route::post('/checkout', [CartController::class, 'checkoutPreview'])->name('cart.checkout');
    // GET: dipanggil saat user kembali dari halaman tambah/edit alamat
    Route::get('/checkout', [CartController::class, 'checkoutPreview'])->name('cart.checkout.get');

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

    // POST checkout: buat Order + Payment + kembalikan snap_token (AJAX JSON atau redirect COD)
    Route::post('/orders/checkout', [OrderController::class, 'checkout'])->name('order.checkout');

    Route::post('/orders/{order}/cancel', [OrderController::class, 'cancel'])->name('order.cancel');
    Route::post('/orders/{order}/confirm-payment', [OrderController::class, 'confirmPayment'])
        ->name('order.confirm-payment');

    // Buy Now (dari halaman produk)
    Route::post('/buy-now', [OrderController::class, 'buyNow'])->name('order.buyNow');

    // ─── PAYMENT (hanya show & check-status, store sudah di OrderController) ─
    Route::get('/payment/{payment}', [PaymentController::class, 'show'])->name('payment.show');
    Route::post('/payment/{payment}/check-status', [PaymentController::class, 'checkStatus'])
        ->name('payment.check-status');

    // ─── ADDRESS ──────────────────────────────────────────────────────────
    Route::get('/address', [AddressController::class, 'index'])->name('address.index');
    Route::get('/address/create', [AddressController::class, 'create'])->name('address.create');
    Route::post('/address', [AddressController::class, 'store'])->name('address.store');
    Route::get('/address/{address}/edit', [AddressController::class, 'edit'])->name('address.edit');
    Route::put('/address/{address}', [AddressController::class, 'update'])->name('address.update');
    Route::delete('/address/{address}', [AddressController::class, 'destroy'])->name('address.destroy');
    Route::post('/address/{address}/select-for-checkout', [AddressController::class, 'selectForCheckout'])
        ->name('address.select-for-checkout');


    Route::post('/products/{id}/reviews', [ProductController::class, 'storeReview'])->name('product.review.store');
    Route::post('/orders/{order}/review/{product}', [OrderController::class, 'storeOrderReview'])->name('order.review.store');


    // Tampilkan invoice di browser (HTML)
    Route::get('/orders/{order}/invoice', [InvoiceController::class, 'show'])
        ->name('invoice.show');
 
    // Stream PDF inline di browser
    Route::get('/orders/{order}/invoice/pdf', [InvoiceController::class, 'stream'])
        ->name('invoice.stream');
 
    // Download PDF
    Route::get('/orders/{order}/invoice/download', [InvoiceController::class, 'download'])
        ->name('invoice.download');
});

/*
|--------------------------------------------------------------------------
| ADMIN ROUTES (AUTH + ADMIN)
|--------------------------------------------------------------------------
*/

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

    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard.admin');
    Route::get('/report', [\App\Http\Controllers\ReportController::class, 'index'])->name('admin.report.index');
    Route::get('/sales-report/pdf', [\App\Http\Controllers\ReportController::class, 'downloadPdf'])->name('admin.report.pdf');

    // CATEGORY
    Route::get('/category', [CategoryController::class, 'index'])->name('admin.category.index');
    Route::get('/category/create', [CategoryController::class, 'create'])->name('admin.category.create');
    Route::post('/category/store', [CategoryController::class, 'store'])->name('category.store');
    Route::get('/category/edit/{id}', [CategoryController::class, 'edit'])->name('admin.category.edit');
    Route::put('/category/update/{id}', [CategoryController::class, 'update'])->name('admin.category.update');
    Route::delete('/category/delete/{id}', [CategoryController::class, 'destroy'])->name('admin.category.destroy');

    // PRODUCT
    Route::get('/products', [ProductController::class, 'adminIndex'])->name('admin.product.index');
    Route::get('/products/create', [ProductController::class, 'create'])->name('admin.product.create');
    Route::post('/products/store', [ProductController::class, 'store'])->name('admin.product.store');
    Route::get('/admin/products/{id}/edit', [ProductController::class, 'edit'])->name('admin.product.edit');
    Route::put('/products/update/{id}', [ProductController::class, 'update'])->name('admin.product.update');
    Route::delete('/products/delete/{id}', [ProductController::class, 'destroy'])->name('admin.product.destroy');

    // REVIEWS
    Route::post('/reviews/{id}/reply', [ProductController::class, 'replyReview'])->name('admin.review.reply');

    // STOCK HISTORY
    Route::get('/stock-history', [StockHistoryController::class, 'index'])->name('product.admin.stock-history');
    Route::get('/stock-history/{product_id}', [StockHistoryController::class, 'history'])->name('admin.product.stock.history');
    Route::post('/stock/action', [StockHistoryController::class, 'stockAction'])->name('admin.stock.action');
    Route::post('/stock/restock', [StockHistoryController::class, 'restock'])->name('admin.stock.restock');
    Route::post('/stock/adjustment', [StockHistoryController::class, 'adjustment'])->name('admin.stock.adjustment');

    // ORDER ADMIN
    Route::get('/orders', [OrderController::class, 'adminIndex'])->name('admin.order.index');
    Route::get('/orders/{order}', [OrderController::class, 'adminShow'])->name('admin.order.show');
    Route::put('/orders/{order}/update-status', [OrderController::class, 'updateStatus'])->name('admin.order.update-status');
    Route::post('/orders/{order}/cancel', [OrderController::class, 'adminCancel'])->name('admin.order.cancel');

    Route::get('/shipping', [ShippingController::class, 'adminSettings'])->name('admin.shipping.settings');
Route::post('/shipping/settings', [ShippingController::class, 'adminSaveSettings'])->name('admin.shipping.settings.save');
Route::put('/shipping/zones/{zone}', [ShippingController::class, 'adminZoneUpdate'])->name('admin.shipping.zones.update');
Route::put('/shipping/couriers/{code}', [ShippingController::class, 'adminCourierUpdate'])->name('admin.shipping.couriers.update');
Route::post('/orders/{order}/tracking', [OrderController::class, 'updateTracking'])->name('admin.order.update-tracking');

Route::post('/orders/{order}/invoice/send', [InvoiceController::class, 'sendEmail'])
        ->name('invoice.send');
});

/*
|--------------------------------------------------------------------------
| TEST ROUTES (hapus di production)
|--------------------------------------------------------------------------
*/

Route::get('/test-notification', function () {
    $user  = \App\Models\User::first();
    $order = \App\Models\Order::first();
    if ($order && $user) {
        $user->notify(new \App\Notifications\NewOrderNotification($order));
        return 'Notifikasi berhasil dikirim!';
    }
    return 'Gagal: order atau user tidak ditemukan';
});

Route::get('/test-email', function () {
    \Illuminate\Support\Facades\Mail::raw('Ini email test dari Laravel', function ($m) {
        $m->to('test@mailtrap.io')->subject('Test Email');
    });
    return 'Email dikirim!';
});

/*
|--------------------------------------------------------------------------
| INDONESIA API
|--------------------------------------------------------------------------
*/

Route::get('/indonesia/provinces', fn() => response()->json(
    \Laravolt\Indonesia\Models\Province::select('code', 'name')->orderBy('name')->get()
));

Route::get('/indonesia/cities/{provinceCode}', fn($c) => response()->json(
    \Laravolt\Indonesia\Models\City::where('province_code', $c)->select('code', 'name')->orderBy('name')->get()
));

Route::get('/indonesia/districts/{cityCode}', fn($c) => response()->json(
    \Laravolt\Indonesia\Models\District::where('city_code', $c)->select('code', 'name')->orderBy('name')->get()
));

Route::get('/indonesia/villages/{districtCode}', fn($c) => response()->json(
    \Laravolt\Indonesia\Models\Village::where('district_code', $c)->select('code', 'name')->orderBy('name')->get()
));

require __DIR__ . '/auth.php';