<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\BelanjaController;
use App\Http\Controllers\StokAkhirController;
use App\Http\Controllers\KurirController;
use App\Http\Controllers\UserController; // <-- UserController untuk pembeli/pengguna

Route::get('/', function () {
    if (Auth::check()) {
        $role = Auth::user()->role;
        if ($role === 'admin') return redirect()->route('admin.dashboard');
        if ($role === 'kurir') return redirect()->route('kurir.dashboard');
        return redirect()->route('user.dashboard');
    }
    return redirect('/login');
});

// --- Rute untuk Tamu (Belum Login) ---
Route::middleware('guest')->group(function () {
    Route::get('/login', [AuthController::class, 'showLogin'])->name('login');
    Route::post('/login', [AuthController::class, 'login']);

    Route::get('/forgot-password', [AuthController::class, 'showForgotPassword'])->name('password.request');
    Route::post('/forgot-password', [AuthController::class, 'sendResetLinkEmail'])->name('password.email');

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

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

// Rute untuk pengecekan real-time
Route::get('/check-email', [AuthController::class, 'checkEmail']);
Route::get('/check-phone', [AuthController::class, 'checkPhone']);
Route::get('/check-zone',  [AuthController::class, 'checkZone']);
Route::get('/reverse-geocode', [AuthController::class, 'reverseGeocode']);



// Rute Logout
Route::match(['get', 'post'], '/logout', [AuthController::class, 'logout'])->name('logout')->middleware('auth');

// Rute Ping: dipakai JS session watcher untuk cek apakah sesi masih aktif
// Jika user belum/sudah logout → redirect ke /login (JS deteksi via res.redirected)
Route::get('/check-session-alive', function () {
    if (!Auth::check()) {
        return response()->json(['authenticated' => false], 401);
    }
    return response()->json(['authenticated' => true, 'user' => Auth::user()->name]);
})->middleware('auth');

// Rute Pembersih Cache untuk Hosting
Route::get('/clear-all-cache', function() {
    try {
        \Illuminate\Support\Facades\Artisan::call('config:clear');
        \Illuminate\Support\Facades\Artisan::call('cache:clear');
        \Illuminate\Support\Facades\Artisan::call('view:clear');
        \Illuminate\Support\Facades\Artisan::call('route:clear');
        return "Semua cache Laravel berhasil dibersihkan! Silakan coba Chatbot asisten Anda kembali.";
    } catch (\Exception $e) {
        return "Gagal membersihkan cache: " . $e->getMessage();
    }
});

// Rute Migrasi Database untuk Hosting
Route::get('/run-migrations', function() {
    try {
        $manualColumnMsg = "";
        // Cek secara manual apakah kolom 'bukti_bayar' ada di tabel 'transaksi'
        if (!\Illuminate\Support\Facades\Schema::hasColumn('transaksi', 'bukti_bayar')) {
            \Illuminate\Support\Facades\DB::statement("ALTER TABLE transaksi ADD COLUMN bukti_bayar VARCHAR(255) NULL AFTER metode_bayar");
            $manualColumnMsg = "<b>[Perbaikan]</b> Kolom 'bukti_bayar' berhasil ditambahkan secara manual ke tabel 'transaksi'.<br>";
        } else {
            $manualColumnMsg = "<b>[Info]</b> Kolom 'bukti_bayar' sudah ada di tabel 'transaksi'.<br>";
        }

        \Illuminate\Support\Facades\Artisan::call('migrate', ['--force' => true]);
        return $manualColumnMsg . "Migrasi database berhasil dijalankan!<br><pre>" . \Illuminate\Support\Facades\Artisan::output() . "</pre>";
    } catch (\Exception $e) {
        return "Gagal menjalankan migrasi: " . $e->getMessage();
    }
});

// --- Rute yang BUTUH LOGIN ---
Route::middleware('auth')->group(function () {

    // Rute Global secure image server
    Route::get('/bukti-bayar/{filename}', [AdminController::class, 'showBuktiBayar'])->name('bukti-bayar');

    // Rute Global Chatbot AI
    Route::get('/chatbot', [\App\Http\Controllers\ChatbotController::class, 'index'])->name('chatbot.index');
    Route::post('/chatbot/send', [\App\Http\Controllers\ChatbotController::class, 'send'])->name('chatbot.send');

    // --- Rute Khusus Admin ---
    Route::prefix('admin')->name('admin.')->middleware(['role:admin'])->group(function () {

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

        // Master Data Pelanggan
        Route::get('/pelanggan', [AdminController::class, 'pelanggan'])->name('pelanggan');
        Route::post('/pelanggan/store', [AdminController::class, 'storePelanggan'])->name('pelanggan.store');
        Route::put('/pelanggan/{id}', [AdminController::class, 'updatePelanggan'])->name('pelanggan.update');
        Route::delete('/pelanggan/{id}', [AdminController::class, 'destroyPelanggan'])->name('pelanggan.destroy');

        // Master Data Kurir
        Route::get('/kurir', [AdminController::class, 'kurir'])->name('kurir');
        Route::post('/kurir/store', [AdminController::class, 'storeKurir'])->name('kurir.store');
        Route::put('/kurir/{id}', [AdminController::class, 'updateKurir'])->name('kurir.update');
        Route::delete('/kurir/{id}', [AdminController::class, 'destroyKurir'])->name('kurir.destroy');

        // Master Data Harga
        Route::get('/harga', [AdminController::class, 'hargaIndex'])->name('harga');
        Route::post('/harga', [AdminController::class, 'storeHarga'])->name('harga.store');
        Route::put('/harga/{id}', [AdminController::class, 'updatePriceSetting'])->name('harga.update');
        Route::delete('/harga/{id}', [AdminController::class, 'destroyHarga'])->name('harga.destroy');

        // --- FITUR BELANJA (LENGKAP: Index, Store, Update, Destroy) ---
        Route::get('/belanja', [BelanjaController::class, 'index'])->name('belanja');
        Route::post('/belanja/store', [BelanjaController::class, 'store'])->name('belanja.store');
        Route::put('/belanja/{id}', [BelanjaController::class, 'update'])->name('belanja.update');
        Route::delete('/belanja/{id}', [BelanjaController::class, 'destroy'])->name('belanja.destroy');

        // Stok Akhir
        Route::get('/stok', [StokAkhirController::class, 'index'])->name('stok');
        Route::post('/stok', [StokAkhirController::class, 'store'])->name('stok.store');
        Route::put('/stok/{id_stok}', [StokAkhirController::class, 'update'])->name('stok.update');
        Route::delete('/stok/{id_stok}', [StokAkhirController::class, 'destroy'])->name('stok.destroy');

        // Manajemen Pesanan User
        Route::get('/pesanan', [AdminController::class, 'pesanan'])->name('pesanan');
        Route::put('/pesanan/{id}/assign', [AdminController::class, 'assignKurir'])->name('pesanan.assign');
        Route::put('/pesanan/{id}/status', [AdminController::class, 'updateStatusPesanan'])->name('pesanan.status');
        Route::put('/pesanan/{id}/update-qty', [AdminController::class, 'updateQty'])->name('pesanan.updateQty');
        Route::delete('/pesanan/{id}', [AdminController::class, 'destroyPesanan'])->name('pesanan.destroy');

        // Penjualan Langsung oleh Admin
        Route::get('/penjualan', [AdminController::class, 'penjualan'])->name('penjualan');
        Route::post('/penjualan', [AdminController::class, 'storePenjualan'])->name('penjualan.store');

        // Laporan Keuangan
        Route::get('/laba-rugi', [AdminController::class, 'labaRugi'])->name('laba-rugi');
        Route::get('/laporan-penjualan', [AdminController::class, 'laporanPenjualan'])->name('laporan-penjualan');

        // Penggajian Karyawan / Payroll
        Route::get('/payroll', [\App\Http\Controllers\PayrollController::class, 'index'])->name('payroll.index');
        Route::get('/payroll/create', [\App\Http\Controllers\PayrollController::class, 'create'])->name('payroll.create');
        Route::post('/payroll/store', [\App\Http\Controllers\PayrollController::class, 'store'])->name('payroll.store');
        Route::post('/payroll/{id}/pay', [\App\Http\Controllers\PayrollController::class, 'markAsPaid'])->name('payroll.pay');
        Route::get('/payroll/{id}/show', [\App\Http\Controllers\PayrollController::class, 'show'])->name('payroll.show');
        Route::delete('/payroll/{id}', [\App\Http\Controllers\PayrollController::class, 'destroy'])->name('payroll.destroy');

        // Pengumuman / Informasi
        Route::get('/pengumuman', [AdminController::class, 'pengumuman'])->name('pengumuman');
        Route::post('/pengumuman', [AdminController::class, 'storePengumuman'])->name('pengumuman.store');
        Route::put('/pengumuman/{id}', [AdminController::class, 'updatePengumuman'])->name('pengumuman.update');
        Route::delete('/pengumuman/{id}', [AdminController::class, 'destroyPengumuman'])->name('pengumuman.destroy');
    });

// Route untuk kasir (Kurir)
Route::prefix('kurir')->name('kurir.')->middleware(['role:kurir'])->group(function () {
    
    // Halaman Utama / Dashboard Kasir (Tugas Kurir)
    Route::get('/dashboard', [KurirController::class, 'dashboard'])->name('dashboard');
    
    // Halaman Tugas Kurir
    Route::get('/tugas', [KurirController::class, 'tugas'])->name('tugas');
    Route::put('/tugas/{id}/selesai', [KurirController::class, 'selesaikanTugas'])->name('tugas.selesai');

    // Halaman Transaksi Penjualan (Halaman yang kita buat tadi)
    Route::get('/penjualan', [KurirController::class, 'create'])->name('penjualan');
    
    // Proses Simpan Transaksi (Method POST)
    Route::post('/penjualan', [KurirController::class, 'store'])->name('penjualan.store');

    // Halaman Riwayat Transaksi
    Route::get('/riwayat', [KurirController::class, 'riwayat'])->name('riwayat');
    Route::delete('/riwayat/{id}', [KurirController::class, 'destroyTransaksi'])->name('riwayat.destroy');

    // Halaman Laporan
    Route::get('/laporan', [KurirController::class, 'laporan'])->name('laporan');
    Route::post('/laporan/pengeluaran', [KurirController::class, 'storePengeluaran'])->name('laporan.pengeluaran.store');
    Route::delete('/laporan/pengeluaran/{id}', [KurirController::class, 'destroyPengeluaran'])->name('laporan.pengeluaran.destroy');

    // Halaman Data Pelanggan
    Route::get('/pelanggan', [KurirController::class, 'pelanggan'])->name('pelanggan');

    // Halaman Slip Gaji Kurir
    Route::get('/gaji', [KurirController::class, 'gaji'])->name('gaji');
    Route::get('/gaji/{id}', [KurirController::class, 'showGaji'])->name('gaji.show');
});

// Route logout sudah didefinisikan di atas (baris 43)

// Route default / redirect berdasarkan role
Route::get('/home', function () {
    $role = Auth::user()->role ?? '';
    if ($role === 'admin') return redirect()->route('admin.dashboard');
    if ($role === 'kurir') return redirect()->route('kurir.dashboard');
    return redirect()->route('user.dashboard');
})->name('home');

// Route untuk Pengguna (Pembeli)
Route::prefix('user')->name('user.')->middleware(['role:user'])->group(function () {
    // Dashboard Pengguna (Pesan Gas)
    Route::get('/dashboard', [UserController::class, 'dashboard'])->name('dashboard');
    Route::post('/pesan', [UserController::class, 'pesan'])->name('pesan');
    
    // Riwayat / Status Pesanan
    Route::get('/pesanan', [UserController::class, 'pesanan'])->name('pesanan');

    // Notifikasi
    Route::post('/notif/read-all', [UserController::class, 'markNotifRead'])->name('notif.readAll');
    Route::post('/notif/delete-all', [UserController::class, 'deleteAllNotif'])->name('notif.deleteAll');
    Route::delete('/notif/{id}', [UserController::class, 'deleteNotif'])->name('notif.delete');
});
});
