<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\KategoriController;
use App\Http\Controllers\ProdukController;
use App\Http\Controllers\KeranjangController;
use App\Http\Controllers\PesananController;
use App\Http\Controllers\DetailPesananController;
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\Admin\DashboardController as AdminDashboardController;
use App\Http\Controllers\Customer\DashboardController as CustomerDashboardController;
use App\Http\Controllers\PembayaranController;
use App\Http\Controllers\EkspedisiController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\RegionController;

/*
|--------------------------------------------------------------------------
| Home
|--------------------------------------------------------------------------
*/
Route::get('/', function (\Illuminate\Http\Request $request) {
    $kategoris = \App\Models\Kategori::all();
    $query = \App\Models\Produk::with(['kategori', 'varians'])->latest();
    
    if ($request->filled('q')) {
        $query->where('nama', 'like', '%' . $request->q . '%');
    }
    if ($request->filled('kategori')) {
        $query->where('kategori_id', $request->kategori);
    }
    
    $produks = $query->take(12)->get();
    return view('welcome', compact('kategoris', 'produks'));
});

/*
|--------------------------------------------------------------------------
| Authentication
|--------------------------------------------------------------------------
*/
Route::get('/login',    [AuthController::class, 'showLogin'])->name('login');
Route::post('/login',   [AuthController::class, 'login']);
Route::get('/register', [AuthController::class, 'showRegister'])->name('register');
Route::post('/register',[AuthController::class, 'register']);
Route::post('/logout',  [AuthController::class, 'logout'])->name('logout');

/*
|--------------------------------------------------------------------------
| Dashboard
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'cekRole:admin'])
    ->get('/admin/dashboard', [AdminDashboardController::class, 'index'])
    ->name('admin.dashboard');

Route::middleware(['auth', 'cekRole:customer'])->group(function () {
    Route::get('/customer/dashboard', [CustomerDashboardController::class, 'index'])
        ->name('customer.dashboard');
});

/*
|--------------------------------------------------------------------------
| Produk (Customer)
|--------------------------------------------------------------------------
*/
Route::get('/produk/{id}', [ProdukController::class, 'showUser'])
    ->name('customer.produk.show');

/*
|--------------------------------------------------------------------------
| Ekspedisi
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'cekRole:ekspedisi'])
    ->prefix('ekspedisi')
    ->name('ekspedisi.')
    ->group(function () {

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

        Route::get('/pesanan-masuk',    [EkspedisiController::class, 'pesananMasuk'])->name('pesanan-masuk');
        Route::get('/dalam-pengiriman', [EkspedisiController::class, 'dalamPengiriman'])->name('dalam-pengiriman');
        Route::get('/terkirim',         [EkspedisiController::class, 'terkirim'])->name('terkirim');
        Route::get('/laporan',          [EkspedisiController::class, 'laporan'])->name('laporan');

        Route::get('/profil', [EkspedisiController::class, 'profil'])->name('profil');
        Route::post('/profil/update', [EkspedisiController::class, 'updateProfil'])->name('profil.update');
        Route::post('/profil/update-password', [EkspedisiController::class, 'updatePassword'])->name('profil.update-password');

        Route::post('/pesanan/{pesanan}/ambil',   [EkspedisiController::class, 'ambil'])->name('ambil');
        Route::post('/pesanan/{pesanan}/selesai', [EkspedisiController::class, 'selesai'])->name('selesai');
        Route::post('/pesanan/{pesanan}/masalah', [EkspedisiController::class, 'masalah'])->name('masalah');
});

/*
|--------------------------------------------------------------------------
| Profile
|--------------------------------------------------------------------------
*/
Route::middleware(['auth'])->group(function () {
    Route::get('/profile',        [ProfileController::class, 'index'])->name('profile.index');
    Route::get('/profile/edit',   [ProfileController::class, 'edit'])->name('profile.edit');
    Route::put('/profile/update', [ProfileController::class, 'update'])->name('profile.update');
});

/*
|--------------------------------------------------------------------------
| Admin CRUD
|--------------------------------------------------------------------------
*/
Route::post('/notifications/mark-all-read', function() {
    auth()->user()->unreadNotifications->markAsRead();
    return back();
})->middleware('auth')->name('notifications.markAllRead');

Route::resource('users', UserController::class);
Route::resource('kategoris', KategoriController::class);
Route::resource('produks', ProdukController::class);
Route::resource('detail_pesanans', DetailPesananController::class);

Route::middleware(['auth', 'cekRole:admin'])->prefix('admin')->group(function () {
    Route::get('/stock-logs', [\App\Http\Controllers\StockLogController::class, 'index'])->name('admin.stock_logs.index');
    Route::get('/stock-logs/create', [\App\Http\Controllers\StockLogController::class, 'create'])->name('admin.stock_logs.create');
    Route::post('/stock-logs', [\App\Http\Controllers\StockLogController::class, 'store'])->name('admin.stock_logs.store');
});

/*
|--------------------------------------------------------------------------
| Keranjang (User)
|--------------------------------------------------------------------------
*/
Route::middleware(['auth'])->prefix('cart')->name('cart.')->group(function () {
    Route::get('/',            [KeranjangController::class, 'index'])->name('index');
    Route::post('/add',        [KeranjangController::class, 'tambah'])->name('add');
    Route::patch('/item/{id}', [KeranjangController::class, 'updateItem'])->name('update');
    Route::delete('/item/{id}',[KeranjangController::class, 'hapusItem'])->name('remove');
    Route::get('/count',       [KeranjangController::class, 'getCartCount'])->name('count');
});

/*
|--------------------------------------------------------------------------
| Keranjang (Legacy / Compatibility)
|--------------------------------------------------------------------------
*/
Route::middleware(['auth'])->prefix('keranjang')->name('keranjang.')->group(function () {
    Route::get('/',            [KeranjangController::class, 'index'])->name('index');
    Route::post('/add',        [KeranjangController::class, 'tambah'])->name('add');
    Route::patch('/item/{id}', [KeranjangController::class, 'updateItem'])->name('update');
    Route::delete('/item/{id}',[KeranjangController::class, 'hapusItem'])->name('hapus');
    Route::get('/count',       [KeranjangController::class, 'getCartCount'])->name('count');
});

/*
|--------------------------------------------------------------------------
| Keranjang Admin
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'cekRole:admin'])->prefix('admin')->group(function () {
    Route::get('/keranjangs', [KeranjangController::class, 'adminIndex'])->name('keranjangs.index');
    Route::get('/keranjangs/create', [KeranjangController::class, 'create'])->name('keranjangs.create');
    Route::post('/keranjangs', [KeranjangController::class, 'store'])->name('keranjangs.store');
    Route::get('/keranjangs/{keranjang}', [KeranjangController::class, 'show'])->name('keranjangs.show');
    Route::get('/keranjangs/{keranjang}/edit', [KeranjangController::class, 'edit'])->name('keranjangs.edit');
    Route::put('/keranjangs/{keranjang}', [KeranjangController::class, 'update'])->name('keranjangs.update');
    Route::delete('/keranjangs/{keranjang}', [KeranjangController::class, 'destroy'])->name('keranjangs.destroy');
});

/*
|--------------------------------------------------------------------------
| Pesanan
|--------------------------------------------------------------------------
*/
Route::middleware('auth')->group(function () {
    Route::get('/pesanans/laporan-pdf', [PesananController::class, 'cetakLaporan'])->name('pesanans.laporan');
    Route::get('/pesanans/{pesanan}/invoice-pdf', [PesananController::class, 'cetakInvoiceAdmin'])->name('pesanans.invoice');
    Route::resource('pesanans', PesananController::class);
    Route::get('/pesanans/{pesanan}/bayar', [PesananController::class, 'bayar'])
        ->name('pesanans.bayar');
    Route::post('/pesanans/{pesanan}/batalkan', [PesananController::class, 'batalkanCheckout'])
        ->name('pesanans.batalkan');
    Route::get('/pesanans/{pesanan}/cetak-resi', [PesananController::class, 'cetakResi'])
        ->name('pesanans.cetak-resi');
    Route::post('/pesanans/{pesanan}/konfirmasi-selesai', [PesananController::class, 'konfirmasiSelesai'])
        ->name('pesanans.konfirmasi-selesai');
});

Route::middleware(['auth'])->prefix('customer')->name('customer.')->group(function () {
    Route::get('/pesanan/{id}', [PesananController::class, 'detail'])
        ->name('pesanan.detail_pesanan');
});

Route::middleware(['auth'])->post('/pesanan/{id}/alamat', function(\Illuminate\Http\Request $request, $id) {
    $request->validate([
        'label' => 'nullable|string',
        'nama_penerima' => 'required|string',
        'no_telp' => 'required|string',
        'provinsi_id' => 'required',
        'kota_id' => 'required',
        'kecamatan_id' => 'required',
        'desa_id' => 'required',
        'alamat_tujuan' => 'required',
        'kode_pos' => 'required'
    ]);
    
    $user = auth()->user();
    $pesanan = \App\Models\Pesanan::findOrFail($id);
    if($pesanan->user_id !== $user->id) abort(403);

    \Illuminate\Support\Facades\DB::beginTransaction();
    try {
        $kotaName = \App\Models\Regency::find($request->kota_id)?->name ?? '';

        // Cek apakah user belum punya alamat utama
        $hasUtama = \App\Models\AlamatUser::where('user_id', $user->id)->where('is_utama', true)->exists();

        // Save ke address book
        $alamat = \App\Models\AlamatUser::create([
            'user_id' => $user->id,
            'label' => $request->label ?? 'Rumah',
            'nama_penerima' => $request->nama_penerima,
            'no_telp' => $request->no_telp,
            'provinsi_id' => $request->provinsi_id,
            'kota_id' => $request->kota_id,
            'kecamatan_id' => $request->kecamatan_id,
            'desa_id' => $request->desa_id,
            'kode_pos' => $request->kode_pos,
            'alamat_lengkap' => $request->alamat_tujuan,
            'is_utama' => !$hasUtama, // jadikan utama jika ini yang pertama
        ]);

        $pesanan->update([
            'provinsi_id' => $request->provinsi_id,
            'kota_id' => $request->kota_id,
            'kecamatan_id' => $request->kecamatan_id,
            'desa_id' => $request->desa_id,
            'kota' => $kotaName,
            'alamat_tujuan' => $request->alamat_tujuan,
            'kode_pos' => $request->kode_pos,
        ]);
        
        \Illuminate\Support\Facades\DB::commit();
        return back()->with('success', 'Alamat baru berhasil ditambahkan dan diterapkan ke pesanan!');
    } catch (\Exception $e) {
        \Illuminate\Support\Facades\DB::rollBack();
        return back()->with('error', 'Gagal menambahkan alamat: ' . $e->getMessage());
    }
})->name('pesanans.simpan_alamat');

Route::middleware(['auth'])->post('/pesanan/{id}/alamat/pilih', function(\Illuminate\Http\Request $request, $id) {
    $request->validate([
        'alamat_id' => 'required|exists:alamat_users,id'
    ]);
    
    $user = auth()->user();
    $pesanan = \App\Models\Pesanan::findOrFail($id);
    if($pesanan->user_id !== $user->id) abort(403);

    $alamat = \App\Models\AlamatUser::findOrFail($request->alamat_id);
    if($alamat->user_id !== $user->id) abort(403);

    $pesanan->update([
        'provinsi_id' => $alamat->provinsi_id,
        'kota_id' => $alamat->kota_id,
        'kecamatan_id' => $alamat->kecamatan_id,
        'desa_id' => $alamat->desa_id,
        'kota' => $alamat->regency?->name ?? '',
        'alamat_tujuan' => $alamat->alamat_lengkap,
        'kode_pos' => $alamat->kode_pos,
    ]);

    return back()->with('success', 'Alamat pesanan berhasil diubah!');
})->name('pesanans.pilih_alamat');

/*
|--------------------------------------------------------------------------
| Checkout
|--------------------------------------------------------------------------
*/
Route::middleware(['auth'])->group(function () {
    Route::get('/checkout', [CheckoutController::class, 'index'])->name('pesanan.index');
    Route::post('/checkout', [CheckoutController::class, 'process'])->name('pesanan.process_checkout');
    Route::post('/checkout/direct', [CheckoutController::class, 'processDirect'])->name('pesanan.process_direct');
});

/*
|--------------------------------------------------------------------------
| Pembayaran (Midtrans)
|--------------------------------------------------------------------------
*/
Route::get('/pembayarans/create', [PembayaranController::class, 'create'])
    ->name('pembayarans.create');

// ✅ CALLBACK (WAJIB, TANPA AUTH, HANYA SATU)
Route::post('/midtrans/callback', [PembayaranController::class, 'callback'])
    ->name('midtrans.callback');

Route::post('/midtrans/frontend-callback', [PembayaranController::class, 'frontendCallback'])
    ->name('midtrans.frontend_callback');

/*
|--------------------------------------------------------------------------
| Regions API
|--------------------------------------------------------------------------
*/
Route::get('/regions/provinces', [RegionController::class, 'provinces'])->name('regions.provinces');
Route::get('/regions/cities/{province}', [RegionController::class, 'cities'])->name('regions.cities');
Route::get('/regions/districts/{city}', [RegionController::class, 'districts'])->name('regions.districts');
Route::get('/regions/villages/{district}', [RegionController::class, 'villages'])->name('regions.villages');