<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\Api\PenugasanController;
use App\Http\Controllers\Api\NotificationController;
use App\Http\Controllers\UnitKerjaController;
use App\Models\User;
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API ROUTES - BACKEND Laravel_KP
|--------------------------------------------------------------------------
| Backend berjalan di port 8000.
| Frontend KP-ASOY akan mengakses API ini melalui:
| http://127.0.0.1:8000/api
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| PUBLIC ROUTES
|--------------------------------------------------------------------------
| Route yang boleh diakses tanpa login/token.
*/

Route::post('/login', [AuthController::class, 'login']);

/*
|--------------------------------------------------------------------------
| PROTECTED ROUTES
|--------------------------------------------------------------------------
| Semua route di bawah ini wajib menggunakan token Sanctum.
| Token dikirim dari frontend melalui:
| Http::withToken(session('api_token'))
*/
Route::middleware('auth:sanctum')->group(function () {

    /*
    |--------------------------------------------------------------------------
    | AUTH
    |--------------------------------------------------------------------------
    */
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/me', [AuthController::class, 'me']);
    Route::put('/profile/update', [AuthController::class, 'updateProfile']);

    /*
    |--------------------------------------------------------------------------
    | USER MANAGEMENT
    |--------------------------------------------------------------------------
    | Admin/Super Admin membuat akun pegawai/user melalui endpoint ini.
    */
    Route::post('/register', [AuthController::class, 'register'])->middleware('role:admin,superadmin');

    Route::get('/users', function () {
        return response()->json([
            'success' => true,
            'data' => User::select(
                'id',
                'name',
                'username',
                'email',
                'role',
                'jabatan',
                'created_at'
            )->get()
        ]);
    })->middleware('role:admin,superadmin');

    Route::get('/users/{id}', function ($id) {
        try {
            $user = User::findOrFail($id);
            return response()->json(['success' => true, 'data' => $user]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'User tidak ditemukan.'], 404);
        }
    })->middleware('role:admin,superadmin');

    Route::delete('/users/{id}', function ($id) {
        try {
            $user = User::findOrFail($id);
            if ($user->role === 'superadmin') {
                return response()->json(['success' => false, 'message' => 'Superadmin tidak dapat dihapus.'], 403);
            }
            $user->delete();
            return response()->json(['success' => true, 'message' => 'User berhasil dihapus.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal menghapus user: ' . $e->getMessage()], 500);
        }
    })->middleware('role:admin,superadmin');

    Route::put('/users/{id}', function (Request $request, $id) {
        $request->validate([
            'username' => 'nullable|string|unique:users,username,' . $id,
        ]);

        try {
            $user = User::findOrFail($id);
            $data = $request->only(['name', 'username', 'role', 'jabatan']);
            if ($request->filled('password')) {
                $data['password'] = bcrypt($request->password);
            }
            $user->update($data);
            return response()->json(['success' => true, 'message' => 'User berhasil diupdate.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal update user: ' . $e->getMessage()], 500);
        }
    })->middleware('role:admin,superadmin');

    /*
    |--------------------------------------------------------------------------
    | DATA PEGAWAI / USER
    |--------------------------------------------------------------------------
    | Karena role pegawai di sistem kamu memakai nama "user",
    | maka data pegawai diambil dari role user.
    */
    Route::get('/pegawai', function () {
        return response()->json([
            'success' => true,
            'data' => User::where('role', 'user')
                ->select('id', 'name', 'username', 'email', 'role', 'jabatan')
                ->get()
        ]);
    });

    /*
    |--------------------------------------------------------------------------
    | DASHBOARD & PENUGASAN / KEGIATAN
    |--------------------------------------------------------------------------
    */
    Route::get('/dashboard', [PenugasanController::class, 'dashboard']);

    Route::get('/penugasan', [PenugasanController::class, 'index']);
    Route::post('/penugasan', [PenugasanController::class, 'store']);

    Route::get('/penugasan/{id}', [PenugasanController::class, 'show']);
    Route::put('/penugasan/{id}', [PenugasanController::class, 'update']);

    Route::post('/penugasan/{id}/update-status', [PenugasanController::class, 'updateStatus']);
    Route::post('/penugasan/{id}/delete', [PenugasanController::class, 'destroy']);
    Route::post('/penugasan/{id}/archive', [PenugasanController::class, 'toggleArchive']);
    Route::post('/penugasan/{id}/progress', [PenugasanController::class, 'storeProgress']);

    /*
    |--------------------------------------------------------------------------
    | NOTIFIKASI
    |--------------------------------------------------------------------------
    | Nanti dipakai frontend user untuk melihat kegiatan yang sudah ditinjau.
    */
    Route::get('/notifications', [NotificationController::class, 'index']);
    Route::post('/notifications/read', [NotificationController::class, 'markAsRead']);

    /*
    |--------------------------------------------------------------------------
    | UNIT KERJA
    |--------------------------------------------------------------------------
    */
    Route::get('/unit-kerja', [UnitKerjaController::class, 'index']);

    /*
    |--------------------------------------------------------------------------
    | EXPORT EXCEL
    |--------------------------------------------------------------------------
    */
    Route::get('/export-penugasan', [PenugasanController::class, 'export']);
});
