<?php

use App\Http\Controllers\Auth\LoginController;
use App\Modules\TakingOrder\Controllers\OrderController;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

// ============================================
// ROUTES AUTH - TANPA GUEST MIDDLEWARE
// ============================================
Route::get('/login', [LoginController::class, 'showLogin'])->name('login');
Route::post('/login', [LoginController::class, 'login']);
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');

// ============================================
// ROOT
// ============================================
Route::get('/', function () {
    if (Auth::check()) {
        return redirect('/sales/taking-order/dashboard');
    }
    return redirect('/login');
});

// ============================================
// ROUTES SALES - TANPA ROLE MIDDLEWARE DULU
// ============================================
Route::middleware(['auth'])->prefix('sales/taking-order')->name('sales.taking-order.')->group(function () {
    Route::get('/dashboard', [OrderController::class, 'dashboard'])->name('dashboard');
    Route::get('/order/{customer}', [OrderController::class, 'orderForm'])->name('order.form');
    Route::post('/order/store', [OrderController::class, 'storeOrder'])->name('order.store');
    Route::patch('/order/{order}/process', [OrderController::class, 'processOrder'])->name('order.process');
    Route::put('/order/{order}/items/{item}', [OrderController::class, 'updateOrderItem'])->name('order.update-item');
    Route::delete('/order/{order}/items/{item}', [OrderController::class, 'deleteOrderItem'])->name('order.delete-item');
    Route::delete('/order/{order}', [OrderController::class, 'deleteOrder'])->name('order.delete');
    Route::put('/order/{order}/update', [OrderController::class, 'updateOrder'])->name('order.update');
    Route::get('/orders/pending', [OrderController::class, 'pendingOrders'])->name('orders.pending');
    Route::get('/orders/pending/data', [OrderController::class, 'getPendingOrdersData'])->name('orders.pending.data');
    Route::get('/offline', function () { return Inertia::render('Offline'); })->name('offline');
    Route::post('/api/sync-orders', [OrderController::class, 'syncOrders'])->name('api.sync-orders');
});

// Test route
// Route::get('/test', function () {
//     return Inertia::render('Test');
// });

Route::get('/test-auth', function () {
    return response()->json([
        'auth' => auth()->check(),
        'user' => auth()->user(),
        'session' => session()->getId(),
    ]);
})->middleware('auth');
