<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\KategoriController;
use App\Http\Controllers\KeranjangController;
use App\Http\Controllers\ProdukController;
use App\Http\Controllers\RestokController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\PesananController;
use App\Http\Controllers\UserAlamatController;
use App\Http\Controllers\PembayaranController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\TokoController;
use App\Http\Controllers\PesananMasukController;
use App\Http\Controllers\UlasanController;
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\PasswordResetLinkController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\KurirController;
use App\Http\Controllers\TrackingController;
use App\Http\Controllers\Api\UlasanApiController;
use App\Http\Controllers\Api\ProdukApiController; // TAMBAHKAN INI
use App\Http\Controllers\ChatController;

use App\Models\User; // TAMBAHKAN INI untuk update email
use Laravolt\Indonesia\Models\City;
use Laravolt\Indonesia\Models\District;
use Laravolt\Indonesia\Models\Village;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

/*
|--------------------------------------------------------------------------
| LOGIN & LOGOUT
|--------------------------------------------------------------------------
*/
Route::middleware('guest')->group(function () {

    Route::get('login', [AuthenticatedSessionController::class, 'create'])->name('login');
    Route::post('login', [AuthenticatedSessionController::class, 'store']);

    Route::get('register', [RegisteredUserController::class, 'create'])->name('register');
    Route::post('register', [RegisteredUserController::class, 'store']);

    Route::get('forgot-password', [PasswordResetLinkController::class, 'create'])->name('password.request');
    Route::post('forgot-password', [PasswordResetLinkController::class, 'store'])->name('password.email');

    Route::get('reset-password/{token}', [NewPasswordController::class, 'create'])->name('password.reset');
    Route::post('reset-password', [NewPasswordController::class, 'update'])->name('password.update');
});

/*
|--------------------------------------------------------------------------
| LOGOUT
|--------------------------------------------------------------------------
*/
Route::middleware('auth')->group(function () {
    Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])->name('logout');
});

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

Route::get('/', [ProdukController::class, 'welcome'])->name('welcome');

Route::get('/register', [RegisteredUserController::class, 'create'])->name('register');
Route::post('/register', [RegisteredUserController::class, 'store']);

Route::prefix('produk')->name('produk.')->group(function () {
    Route::get('/public', [ProdukController::class, 'publicIndex'])->name('public.index');
    Route::get('/public/kategori/{id?}', [ProdukController::class, 'publicByKategori'])->name('public.kategori');
    Route::get('/public/{id}', [ProdukController::class, 'publicShow'])->name('public.show');
});

/*
|--------------------------------------------------------------------------
| API ROUTES (TANPA AUTH)
|--------------------------------------------------------------------------
*/
Route::prefix('api')->name('api.')->group(function () {
    // API Produk - PUBLIC (untuk modal detail)
    Route::get('/produk/{id}/detail', [ProdukApiController::class, 'detail'])->name('produk.detail');
    
    // Ulasan routes - PUBLIC
    Route::get('/ulasan/produk/{produkId}', [UlasanApiController::class, 'getByProduk'])->name('ulasan.produk');
});

/*
|--------------------------------------------------------------------------
| AUTH (LOGIN WAJIB)
|--------------------------------------------------------------------------
*/

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

    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::post('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::get('/produk', [ProdukController::class, 'index'])->name('produk.index');

    // API dengan Auth (untuk tracking dll)
    Route::prefix('api')->name('api.')->group(function () {
        // Tracking routes
        Route::get('/tracking/toko/{pesananId}', [TrackingController::class, 'getTokoAlamat'])->name('tracking.toko');
        Route::get('/tracking/tujuan/{pesananId}', [TrackingController::class, 'getTujuanAlamat'])->name('tracking.tujuan');
        Route::get('/tracking/kurir/{pesananId}', [TrackingController::class, 'getKurirLocation'])->name('tracking.kurir');
        Route::get('/tracking/route/{pesananId}', [TrackingController::class, 'getRoute'])->name('tracking.route');
        
        // Geocoding routes
        Route::get('/geocode', [TrackingController::class, 'geocode'])->name('geocode');
        Route::post('/geocode/batch', [TrackingController::class, 'batchGeocode'])->name('geocode.batch');
    });

    // ROUTES UNTUK CUSTOMER (USER BIASA)
    Route::middleware(['role:user'])->group(function () {
        Route::get('/keranjang', [KeranjangController::class, 'index'])->name('keranjang.index');
        Route::post('/keranjang', [KeranjangController::class, 'store'])->name('keranjang.store');
        Route::patch('/keranjang/{id}', [KeranjangController::class, 'update'])->name('keranjang.update');
        Route::post('/keranjang-hapus/{id}', [KeranjangController::class, 'destroy'])->name('keranjang.destroy');
        Route::post('/keranjang-hapus-multiple', [KeranjangController::class, 'deleteMultiple'])->name('keranjang.delete-multiple');
        Route::post('/beli-produk', [PesananController::class, 'store'])->name('produk.beli');
        Route::post('/checkout/buy-now', [PesananController::class, 'buyNow'])->name('checkout.buynow');
        Route::get('/checkout/process/{alamat}', [PesananController::class, 'processBuyNow'])->name('checkout.process');
        Route::get('/pembayaran/{id}', [PembayaranController::class, 'create'])->name('pembayaran.create');
        Route::post('/pembayaran/{id}', [PembayaranController::class, 'store'])->name('pembayaran.store');
        Route::get('/pembayaran/{id}/token', [PembayaranController::class, 'getToken'])->name('pembayaran.token');
        Route::get('/pembayaran/{id}/check', [PembayaranController::class, 'checkStatus'])->name('pembayaran.check');
        Route::get('/pembayaran/{id}/finish', [PembayaranController::class, 'finish'])->name('pembayaran.finish');
        Route::post('/pembayaran/{id}/alamat', [PembayaranController::class, 'saveAlamat'])->name('pembayaran.saveAlamat');
        
        // ROUTES PESANAN UNTUK CUSTOMER
        Route::get('/pesanan', [PesananController::class, 'index'])->name('pesanan.index');
        Route::get('/pesanan/{id}', [PesananController::class, 'show'])->name('pesanan.show');
        Route::post('/pesanan/{id}/batal', [PesananController::class, 'batal'])->name('pesanan.batal');
        Route::put('/pesanan/{id}/selesai', [PesananController::class, 'selesai'])->name('pesanan.selesai');
        Route::get('/pesanan/{id}/cek-status-kurir', [PesananController::class, 'cekStatusKurir'])->name('pesanan.cek-status-kurir');
        Route::get('/pesanan/riwayat', [PesananController::class, 'riwayat'])->name('pesanan.riwayat');
        
        // ROUTES CETAK UNTUK CUSTOMER
        Route::get('/pesanan/{id}/cetak-invoice', [PesananController::class, 'cetakInvoice'])->name('pesanan.cetak-invoice');
        
        Route::post('/ulasan', [UlasanController::class, 'store'])->name('ulasan.store');
        
        // ROUTES ALAMAT UNTUK CUSTOMER
        Route::get('/user/alamat', [UserAlamatController::class, 'index'])->name('user-alamat.index');
        Route::get('/user/alamat/create', [UserAlamatController::class, 'create'])->name('user-alamat.create');
        Route::post('/user/alamat', [UserAlamatController::class, 'store'])->name('user-alamat.store');
        Route::get('/user/alamat/{id}/edit', [UserAlamatController::class, 'edit'])->name('user-alamat.edit');
        Route::put('/user/alamat/{id}', [UserAlamatController::class, 'update'])->name('user-alamat.update');
        Route::delete('/user/alamat/{id}', [UserAlamatController::class, 'destroy'])->name('user-alamat.destroy');
    });

// ROUTES UNTUK PENJUAL
Route::middleware(['role:penjual'])->group(function () {
    // PRODUK
    Route::prefix('produk')->name('produk.')->group(function () {
        Route::get('/create', [ProdukController::class, 'create'])->name('create');
        Route::post('/', [ProdukController::class, 'store'])->name('store');
        Route::get('/{produk}/edit', [ProdukController::class, 'edit'])->name('edit');
        Route::put('/{produk}', [ProdukController::class, 'update'])->name('update');
        Route::delete('/{produk}', [ProdukController::class, 'destroy'])->name('destroy');
    });
    
    // KATEGORI
    Route::resource('kategori', KategoriController::class);
    
    // USER MANAGEMENT (UNTUK ADMIN JUGA BISA, TAPI KITA BATASI DULU)
    Route::resource('user', UserController::class);
    
    // TOKO
    Route::get('/buka-toko', [TokoController::class, 'create'])->name('toko.create');
    Route::post('/buka-toko', [TokoController::class, 'store'])->name('toko.store');    
    Route::get('/toko/{id}/edit', [TokoController::class, 'edit'])->name('toko.edit');
    Route::put('/toko/{id}', [TokoController::class, 'update'])->name('toko.update');
    Route::delete('/toko/{id}', [TokoController::class, 'destroy'])->name('toko.destroy');
    
    // PESANAN MASUK (UNTUK PENJUAL)
    Route::prefix('pesanan-masuk')->name('pesanan.masuk.')->group(function () {
        Route::get('/', [PesananMasukController::class, 'index'])->name('index');
        Route::get('/detail/{id}', [PesananMasukController::class, 'show'])->name('detail');
        Route::get('/{id}/pilih-kurir', [PesananMasukController::class, 'pilihKurir'])->name('pilih-kurir');
        Route::post('/{id}/proses-dengan-kurir', [PesananMasukController::class, 'prosesDenganKurir'])->name('proses-dengan-kurir');
        Route::post('/{id}/proses', [PesananMasukController::class, 'proses'])->name('proses');
        Route::post('/{id}/selesai', [PesananMasukController::class, 'selesai'])->name('selesai');
        Route::post('/{id}/assign-kurir', [PesananMasukController::class, 'assignKurirManual'])->name('assign-kurir');
        
        // ROUTES INVOICE UNTUK PENJUAL
        Route::get('/{id}/invoice', [PesananController::class, 'cetakInvoice'])->name('invoice');
        Route::post('/{id}/kirim-invoice', [PesananController::class, 'kirimInvoice'])->name('kirim-invoice');
        
        // TAMBAHKAN ROUTE INI UNTUK CETAK RESI - PASTIKAN NAMA ROUTE NYA SESUAI
        Route::get('/{id}/cetak-resi', [PesananMasukController::class, 'cetakResi'])->name('cetak-resi');
    });
    
    // RESTOK
    Route::prefix('restok')->name('restok.')->group(function () {
        Route::get('/', [RestokController::class, 'index'])->name('index');
        Route::get('/{id}', [RestokController::class, 'show'])->name('show');
        Route::post('/', [RestokController::class, 'store'])->name('store');
        Route::get('/api/count', [RestokController::class, 'countNotifikasi'])->name('count');
        Route::get('/api/list', [RestokController::class, 'listNotifikasi'])->name('list');
    });
});
    // ROUTES UNTUK ADMIN
    Route::middleware(['role:admin'])->prefix('admin')->name('admin.')->group(function () {
        // Bisa ditambahkan nanti
    });

    // ROUTES PRODUK DETAIL (BISA DIAKSES SEMUA YANG LOGIN)
    Route::get('/produk/{produk}', [ProdukController::class, 'show'])->name('produk.show');
});

/*
|--------------------------------------------------------------------------
| ROUTES KHUSUS KURIR
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'role:kurir'])->prefix('kurir')->name('kurir.')->group(function () {
    Route::get('/dashboard', [KurirController::class, 'index'])->name('dashboard');
    Route::get('/penugasan/{id}', [KurirController::class, 'show'])->name('show');
    Route::post('/penugasan/{id}/status', [KurirController::class, 'updateStatus'])->name('update-status');
    Route::get('/penugasan/{id}/location', [KurirController::class, 'getLocation'])->name('location');
    Route::get('/history', [KurirController::class, 'history'])->name('history');
});

/*
|--------------------------------------------------------------------------
| ROUTES CHAT (UNTUK SEMUA YANG LOGIN)
|--------------------------------------------------------------------------
*/
Route::middleware(['auth'])->prefix('chat')->name('chat.')->group(function () {
    Route::get('/', [ChatController::class, 'index'])->name('index');
    Route::get('/{id}', [ChatController::class, 'show'])->name('show');
    Route::post('/create-or-get', [ChatController::class, 'createOrGet'])->name('create-or-get');
    Route::post('/{chatId}/send', [ChatController::class, 'send'])->name('send');
    Route::get('/{chatId}/poll', [ChatController::class, 'poll'])->name('poll');
    Route::get('/unread-count', [ChatController::class, 'unreadCount'])->name('unread-count');
});

/*
|--------------------------------------------------------------------------
| AJAX WILAYAH
|--------------------------------------------------------------------------
*/

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

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

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

/*
|--------------------------------------------------------------------------
| UPDATE EMAIL (SEMENTARA)
|--------------------------------------------------------------------------
*/

Route::get('/update-email', function() {
    try {
        $user = User::where('email', 'faozan.maulana118@smk.belajar.id')->first();
        
        if ($user) {
            $oldEmail = $user->email;
            $user->email = 'faozanmaulana2008@gmail.com';
            $user->save();
            
            return response()->json([
                'success' => true,
                'message' => 'Email berhasil diupdate',
                'data' => [
                    'old_email' => $oldEmail,
                    'new_email' => $user->email,
                    'name' => $user->name
                ]
            ]);
        } else {
            $existingUser = User::where('email', 'faozanmaulana2008@gmail.com')->first();
            
            if ($existingUser) {
                return response()->json([
                    'success' => true,
                    'message' => 'Email faozanmaulana2008@gmail.com sudah terdaftar',
                    'data' => $existingUser
                ]);
            }
            
            return response()->json([
                'success' => false,
                'message' => 'User dengan email faozan.maulana118@smk.belajar.id tidak ditemukan'
            ]);
        }
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
})->middleware('auth');

/*
|--------------------------------------------------------------------------
| AUTH DEFAULT
|--------------------------------------------------------------------------
*/

require __DIR__ . '/auth.php';