<?php

// routes/web.php - FULL VERSION WITH LANDING PAGE PRODUCTS

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\{
    UsersController,
    KategoriController,
    ProductController,
    PelangganController,
    PenjualanController,
    DetailPenjualanController,
    AuthenController,
    LaporanController,
    DashboardController,
    CartController,
    ProfileController,
    ReviewController
};

// IMPORT MODEL DARI PACKAGE LARAVOLT
use Laravolt\Indonesia\Models\Province;
use Laravolt\Indonesia\Models\City;
use Laravolt\Indonesia\Models\District;
use Laravolt\Indonesia\Models\Village;

// IMPORT MODEL PRODUCT UNTUK LANDING PAGE
use App\Models\Product;

/*
|--------------------------------------------------------------------------
| WEB ROUTES
|--------------------------------------------------------------------------
*/

// ================= LANDING PAGE (MENAMPILKAN PRODUK DARI DATABASE) =================
Route::get('/', function () {
    // Ambil produk dari database untuk ditampilkan di landing page
    $products = Product::with(['kategori', 'images'])
        ->where('stok', '>', 0)  // Hanya produk yang tersedia
        ->orderBy('created_at', 'desc') // Atau berdasarkan terbaru
        ->get();
    
    return view('welcome', compact('products'));
})->name('welcome');

// Route welcome (alias)
Route::get('/home', function () {
    $products = Product::with(['kategori', 'images'])
        ->where('stok', '>', 0)
        ->orderBy('created_at', 'desc')
        ->get();
    
    return view('welcome', compact('products'));
})->name('home');

// ================= AUTH ROUTES (PUBLIC) =================
Route::get('/login', [AuthenController::class, 'showLogin'])->name('login');
Route::post('/login', [AuthenController::class, 'login'])->name('login.post');
Route::post('/logout', [AuthenController::class, 'logout'])->name('logout');

Route::get('/register', [AuthenController::class, 'showRegister'])->name('register');
Route::post('/register', [AuthenController::class, 'register'])->name('register.post');

// ================= VERIFIKASI EMAIL =================
Route::prefix('verify')->name('verify.')->group(function () {
    Route::get('/{email}', [AuthenController::class, 'showVerifyForm'])->name('show');
    Route::post('/check', [AuthenController::class, 'verifyCode'])->name('check');
    Route::post('/resend', [AuthenController::class, 'resendCode'])->name('resend');
});

// ================= MIDTRANS CALLBACK =================
Route::post('/midtrans/callback', [PenjualanController::class, 'midtransCallback'])->name('midtrans.callback');

// ================= PROTECTED ROUTES (WAJIB LOGIN) =================
Route::middleware(['auth'])->group(function () {

    // ================= PROFILE ROUTES =================
    Route::prefix('profile')->name('profile.')->group(function () {
        Route::get('/', [ProfileController::class, 'show'])->name('show');
        Route::get('/edit', [ProfileController::class, 'edit'])->name('edit');
        Route::put('/update', [ProfileController::class, 'update'])->name('update');
        Route::get('/settings', [ProfileController::class, 'settings'])->name('settings');
        Route::put('/settings/update', [ProfileController::class, 'updateSettings'])->name('settings.update');
        Route::post('/avatar', [ProfileController::class, 'uploadAvatar'])->name('avatar.upload');
    });

    // ================= WILAYAH API ROUTES (UNTUK AJAX) =================
    Route::prefix('api/wilayah')->name('api.wilayah.')->group(function () {
        // Get semua provinsi
        Route::get('/provinces', function () {
            $provinces = Province::orderBy('name')->get(['code', 'name']);
            return response()->json($provinces);
        })->name('provinces');

        // Get cities by province code
        Route::get('/cities/{provinceCode}', function ($provinceCode) {
            $cities = City::where('province_code', $provinceCode)
                ->orderBy('name')
                ->get(['code', 'name']);
            return response()->json($cities);
        })->name('cities');

        // Get districts by city code
        Route::get('/districts/{cityCode}', function ($cityCode) {
            $districts = District::where('city_code', $cityCode)
                ->orderBy('name')
                ->get(['code', 'name']);
            return response()->json($districts);
        })->name('districts');

        // Get villages by district code
        Route::get('/villages/{districtCode}', function ($districtCode) {
            $villages = Village::where('district_code', $districtCode)
                ->orderBy('name')
                ->get(['code', 'name']);
            return response()->json($villages);
        })->name('villages');
    });

    // ================= DASHBOARD =================
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

    // ================= PRODUCT =================
    Route::resource('product', ProductController::class);
    Route::post('/product/{id}/add-stock', [ProductController::class, 'addStock'])->name('product.addStock');

    // ================= PELANGGAN =================
    Route::resource('pelanggan', PelangganController::class);
    Route::post('/pelanggan/ajax-store', [PelangganController::class, 'ajaxStore'])->name('pelanggan.ajaxStore');

    // ================= ROUTES KHUSUS PENGGUNA (USER BIASA) =================
    Route::middleware(['role:pengguna'])->group(function () {

        Route::get('/cart', [CartController::class, 'index'])->name('cart.index');
        Route::post('/cart/add/{id}', [CartController::class, 'add'])->name('cart.add');
        Route::post('/cart/remove/{id}', [CartController::class, 'remove'])->name('cart.remove');
        Route::post('/cart/clear', [CartController::class, 'clear'])->name('cart.clear');
        Route::post('/cart/checkout', [CartController::class, 'checkout'])->name('cart.checkout');
        Route::get('/cart/payment', [CartController::class, 'payment'])->name('cart.payment');
        Route::post('/cart/process-payment', [CartController::class, 'processPayment'])->name('cart.processPayment');

        Route::get('/penjualan/create', [PenjualanController::class, 'create'])->name('penjualan.create');
        Route::post('/penjualan', [PenjualanController::class, 'store'])->name('penjualan.store');
        Route::post('/penjualan/from-cart', [PenjualanController::class, 'fromCart'])->name('penjualan.fromCart');
        Route::delete('/penjualan/{id}/cancel', [PenjualanController::class, 'cancelOrder'])->name('penjualan.cancel');
        
    });

    // ================= ROUTES KHUSUS ADMIN =================
    Route::middleware(['role:admin'])->group(function () {

        Route::resource('kategori', KategoriController::class);
        Route::resource('users', UsersController::class);

        Route::get('/laporan', [LaporanController::class, 'index'])->name('laporan.index');
        Route::get('/laporan/print', [LaporanController::class, 'print'])->name('laporan.print');

        Route::get('/penjualan', [PenjualanController::class, 'index'])->name('penjualan.index');
        Route::get('/penjualan/{id}', [PenjualanController::class, 'show'])->name('penjualan.show');
        Route::get('/penjualan/{id}/edit', [PenjualanController::class, 'edit'])->name('penjualan.edit');
        Route::put('/penjualan/{id}', [PenjualanController::class, 'update'])->name('penjualan.update');
        Route::delete('/penjualan/{id}', [PenjualanController::class, 'destroy'])->name('penjualan.destroy');
        Route::get('/penjualan/{id}/pdf', [PenjualanController::class, 'cetakPdf'])->name('penjualan.pdf');
        
        Route::put('/penjualan/{id}/status', [PenjualanController::class, 'updateStatus'])->name('penjualan.updateStatus');
        Route::get('/pengiriman', [PenjualanController::class, 'pengiriman'])->name('pengiriman.index');
        Route::post('/penjualan/{id}/kirim', [PenjualanController::class, 'kirimPesanan'])->name('penjualan.kirim');
    });

    // ================= ROUTES YANG BISA DIAKSES SEMUA USER (LOGIN) =================
    Route::get('/penjualan', [PenjualanController::class, 'index'])->name('penjualan.index');
    Route::get('/penjualan/{id}', [PenjualanController::class, 'show'])->name('penjualan.show');
    Route::get('/penjualan/{id}/struk', [PenjualanController::class, 'cetakStruk'])->name('penjualan.struk');
    
    // ================= ROUTE REVIEW =================
    Route::get('/penjualan/{id}/products-for-review', [ReviewController::class, 'getProductsForReview'])->name('penjualan.products-for-review');
    Route::post('/review', [ReviewController::class, 'store'])->name('review.store');
    Route::put('/review/{id}', [ReviewController::class, 'update'])->name('review.update');
    Route::delete('/review/{id}', [ReviewController::class, 'destroy'])->name('review.destroy');
    
    Route::put('/penjualan/{id}/status', [PenjualanController::class, 'updateStatus'])->name('penjualan.updateStatus');
});

// ================= DEBUG ROUTES (Opsional - Hapus jika production) =================
Route::get('/debug-status/{email}', [AuthenController::class, 'debugStatus'])->name('debug.status');
Route::get('/check-session', [AuthenController::class, 'checkSession'])->name('check.session');

// ================= FALLBACK ROUTE =================
Route::fallback(function () {
    return redirect()->route('welcome')->with('error', 'Halaman tidak ditemukan.');
});