<?php

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\EcoToursController;
use App\Http\Controllers\LocationController;
use App\Http\Controllers\ProcessTypeController;
use App\Http\Controllers\WasteCatagoriesController;
use App\Http\Controllers\WasteTransactionController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return redirect()->route('login');
});

Route::post('/login', [AuthController::class, 'login'])->name('authenticate');
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
Route::get('/login', [LoginController::class, 'index'])->name('login');

Route::group(['middleware' => 'auth'], function () {
    Route::get('/check-username', function (Request $request) {
        $query = User::where('username', $request->query('username'));

        // Abaikan pengecekan jika sedang edit dan ID dikirim
        if ($request->has('id')) {
            $query->where('id', '!=', $request->query('id'));
        }

        $exists = $query->exists();
        return response()->json(['exists' => $exists]);
    });

    Route::get('/home', [HomeController::class, 'index'])->name('home');
    Route::resource('eco_tours', EcoToursController::class);
    Route::get('eco_tours-data/getData', [EcoToursController::class, 'getData'])->name('eco_tours.getData');
    Route::resource('location', LocationController::class);
    Route::get('location-data/getData', [LocationController::class, 'getData'])->name('location.getData');
    Route::resource('waste_categories', WasteCatagoriesController::class);
    Route::get('waste_categories-data/getData', [WasteCatagoriesController::class, 'getData'])->name('waste_categories.getData');
    Route::resource('process_type', ProcessTypeController::class);
    Route::get('process_type-data/getData', [ProcessTypeController::class, 'getData'])->name('process_type.getData');
    Route::resource('waste_transaction', WasteTransactionController::class);
    Route::get('waste_transaction-data/getData', [WasteTransactionController::class, 'getData'])->name('waste_transaction.getData');
});

Route::get('/eco-tours-api', [EcoToursController::class, 'apiIndex'])->name('api.eco_tours.index');
