<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;

use App\Models\Vehicle;
use App\Models\VehicleRequest;
use App\Models\Announcement;
use App\Models\AuditLog;
use App\Models\Notification;
use App\Models\User;

use Barryvdh\DomPDF\Facade\Pdf;

use App\Http\Controllers\UserController;
use App\Http\Controllers\ReturnController;
use App\Http\Controllers\ProfileController;

use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\VehicleController;
use App\Http\Controllers\Admin\MaintenanceController;
use App\Http\Controllers\Admin\RequestController;
use App\Http\Controllers\Admin\UserManagementController;

use App\Http\Controllers\Security\SecurityController;

use App\Http\Controllers\Employee\EmployeeController;
use App\Http\Controllers\Employee\ReportController;



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

Route::get('/', fn() => redirect('/login'));

Route::get('/login', function () {
    return view('auth.login');
})->name('login');

Route::post('/login', function (Request $request) {

    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required'
    ]);

    if (Auth::attempt($credentials)) {

        $request->session()->regenerate();

        $user = Auth::user();

        if ($user->role == 'admin') {
            return redirect('/admin/dashboard');
        }

        if ($user->role == 'security') {
            return redirect('/security/dashboard');
        }

        return redirect('/employee/dashboard');
    }

    return back()->with(
        'error',
        'Invalid email or password.'
    );

});

Route::post('/logout', function () {

    Auth::logout();

    return redirect('/login');

})->middleware('auth');

Route::get('/register', function () {

    return view('auth.register');

});

Route::post('/register', function (Request $request) {

    User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password),
        'role' => 'employee'
    ]);

    return redirect('/login')
        ->with('success', 'Account created.');

});



/*
|--------------------------------------------------------------------------
| ADMIN
|--------------------------------------------------------------------------
*/

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

    Route::get('/admin/dashboard',
        [DashboardController::class, 'index']);

    Route::get('/admin/vehicles',
        [VehicleController::class, 'index']);

    Route::get('/admin/vehicles/create',
        [VehicleController::class, 'create']);

    Route::post('/admin/vehicles/store',
        [VehicleController::class, 'store']);

    Route::get('/admin/vehicles/{id}/edit',
        [VehicleController::class, 'edit']);

    Route::put('/admin/vehicles/{id}',
        [VehicleController::class, 'update']);

    Route::post('/admin/vehicles/{id}/delete',
        [VehicleController::class, 'destroy']);

    Route::get('/admin/vehicles/{id}/maintenance',
        [VehicleController::class, 'maintenance']);

    Route::get('/admin/fleet-status',
    [DashboardController::class, 'fleetStatus']);

    Route::get('/admin/maintenance',
        [MaintenanceController::class, 'index']);

    Route::get('/admin/maintenance/create',
        [MaintenanceController::class, 'create']);

    Route::post('/admin/maintenance/store',
        [MaintenanceController::class, 'store']);



    Route::get('/admin/requests',
        [RequestController::class, 'index']);

    Route::get('/admin/request/{id}/approve',
        [RequestController::class, 'approve']);

    Route::get('/admin/request/{id}/reject',
        [RequestController::class, 'reject']);



    Route::get('/admin/reports',
        [ReportController::class, 'adminInbox']);



    Route::get('/admin/calendar', function () {

        $bookings = VehicleRequest::with('vehicle')
            ->where('status', 'approved')
            ->orderBy('start_date')
            ->get();

        return view(
            'admin.calendar',
            compact('bookings')
        );

    });

    Route::get(
    '/admin/users',
    [UserManagementController::class, 'index']
);

Route::get(
    '/admin/users/create',
    [UserManagementController::class, 'create']
);

Route::post(
    '/admin/users/store',
    [UserManagementController::class, 'store']
);

Route::get(
    '/admin/users/{id}/edit',
    [UserManagementController::class, 'edit']
);

Route::put(
    '/admin/users/{id}',
    [UserManagementController::class, 'update']
);

Route::post(
    '/admin/users/{id}/delete',
    [UserManagementController::class, 'destroy']
);



    Route::get('/admin/employees', function () {

        $employees = User::where(
            'role',
            'employee'
        )->get();

        return view(
            'admin.employees',
            compact('employees')
        );

    });



    Route::get('/admin/logs', function () {

        $logs = AuditLog::latest()->get();

        return view(
            'admin.logs',
            compact('logs')
        );

    });



    Route::get('/admin/export-pdf', function () {

        $requests = VehicleRequest::with(
            'user',
            'vehicle'
        )->get();

        $pdf = Pdf::loadView(
            'admin.pdf_report',
            compact('requests')
        );

        return $pdf->download(
            'vehicle_requests_report.pdf'
        );

    });



    Route::get('/admin/vehicle/{id}/return',
        function ($id) {

        $vehicle = Vehicle::findOrFail($id);

        $vehicle->update([
            'status' => 'available'
        ]);

        return redirect('/admin/vehicles');

    });



    Route::get('/admin/announcements', function () {

        $announcements = Announcement::latest()
            ->get();

        return view(
            'admin.announcements',
            compact('announcements')
        );

    });



    Route::post('/admin/announcements/store',
        function (Request $request) {

        Announcement::create([
            'title' => $request->title,
            'message' => $request->message
        ]);

        AuditLog::create([
            'user_id' => auth()->id(),
            'action' =>
                'Posted announcement: '
                . $request->title
        ]);

        return redirect('/admin/announcements');

    });



    Route::get('/admin/announcement/{id}/edit',
        function ($id) {

        $announcement = Announcement::findOrFail($id);

        return view(
            'admin.edit-announcement',
            compact('announcement')
        );

    });



    Route::post('/admin/announcement/{id}/update',
        function (Request $request, $id) {

        $announcement = Announcement::findOrFail($id);

        $announcement->update([
            'title' => $request->title,
            'message' => $request->message
        ]);

        return redirect('/admin/announcements');

    });



    Route::get('/admin/announcement/{id}/delete',
        function ($id) {

        Announcement::findOrFail($id)->delete();

        return back();

    });

});



/*
|--------------------------------------------------------------------------
| SECURITY
|--------------------------------------------------------------------------
*/

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

    Route::get('/security/dashboard', function () {

        $activeTripCount = \App\Models\TripLog
            ::whereNull('return_time')
            ->count();

        $tripsToday = \App\Models\TripLog
            ::whereDate(
                'departure_time',
                today()
            )->count();

        $returnedToday = \App\Models\TripLog
            ::whereDate(
                'return_time',
                today()
            )->count();

        $activeTrips = \App\Models\TripLog::with([
            'user',
            'vehicle'
        ])
        ->whereNull('return_time')
        ->latest()
        ->get();

        $lateTrips = \App\Models\TripLog::with([
            'user',
            'vehicle'
        ])
        ->whereNull('return_time')
        ->where(
            'departure_time',
            '<',
            now()->subHours(5)
        )
        ->latest()
        ->get();

        return view('security.dashboard', compact(
            'activeTripCount',
            'tripsToday',
            'returnedToday',
            'activeTrips',
            'lateTrips'
        ));

    });



    Route::post('/security/start-trip/{id}',
        [SecurityController::class, 'startTrip']);

    Route::match(['get', 'post'], '/security/end-trip/{id}',
        [SecurityController::class, 'endTrip']);

    Route::post('/security/end-trip-submit/{id}',
        [SecurityController::class, 'submitEndTrip']);

    Route::get('/security/pending-returns',
        [SecurityController::class, 'pendingReturns']);

    Route::post('/security/approve-return/{id}',
        [SecurityController::class, 'approveReturn']);

    Route::post('/security/send-maintenance/{id}',
        [SecurityController::class, 'sendMaintenance']);

    Route::get('/security/trip-log',
        [SecurityController::class, 'tripLog']);



    Route::get('/security/report', function () {

        $activeTripCount = \App\Models\TripLog
            ::whereNull('return_time')
            ->count();

        $activeTrips = \App\Models\TripLog::with(
            'vehicle',
            'user'
        )
        ->whereNull('return_time')
        ->latest()
        ->get();

        return view(
            'security.report',
            compact(
                'activeTripCount',
                'activeTrips'
            )
        );

    });



    Route::get('/security/vehicle/{id}/return',
        function ($id) {

        $vehicle = Vehicle::findOrFail($id);

        $vehicle->update([
            'status' => 'available'
        ]);

        AuditLog::create([
            'user_id' => auth()->id(),
            'action' =>
                'Returned vehicle: '
                . $vehicle->vehicle_name
        ]);

        return redirect('/security/dashboard');

    });



    Route::get('/security/announcements',
        function () {

        $announcements = Announcement::latest()
            ->get();

        return view(
            'security.announcements',
            compact('announcements')
        );

    });

});



/*
|--------------------------------------------------------------------------
| EMPLOYEE
|--------------------------------------------------------------------------
*/

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

    Route::get('/employee/dashboard',
        [EmployeeController::class, 'dashboard']);

    Route::get('/employee/request/{id}',
        [EmployeeController::class, 'requestForm']);

    Route::post('/employee/request/{id}/store',
        [EmployeeController::class, 'storeRequest']);

    Route::get('/employee/requests',
        [EmployeeController::class, 'myRequests']);



    Route::get('/employee/reports',
        [ReportController::class, 'index']);

    Route::post('/employee/reports/store',
        [ReportController::class, 'store'])
            ->name('reports.store');



    Route::get('/employee/notifications',
        function () {

        $notifications = VehicleRequest::where(
            'user_id',
            auth()->id()
        )
        ->whereIn('status', [
            'approved',
            'rejected',
            'returned'
        ])
        ->latest()
        ->get();

        return view(
            'employee.notifications',
            compact('notifications')
        );

    });



    Route::get('/employee/announcements',
        function () {

        $announcements = Announcement::latest()
            ->get();

        return view(
            'employee.announcements',
            compact('announcements')
        );

    });



    Route::delete('/employee/reports/delete/{id}',
        function ($id) {

        $report = \App\Models\Report::where(
            'user_id',
            auth()->id()
        )->findOrFail($id);

        $report->delete();

        return back();

    });



    Route::get('/employee/reports/edit/{id}',
        function ($id) {

        $report = \App\Models\Report::where(
            'user_id',
            auth()->id()
        )->findOrFail($id);

        return view(
            'employee.edit-report',
            compact('report')
        );

    });



    Route::put('/employee/reports/update/{id}',
        function ($id) {

        $report = \App\Models\Report::where(
            'user_id',
            auth()->id()
        )->findOrFail($id);

        $report->update([
            'description' => request('description'),
            'severity' => request('severity'),
        ]);

        return redirect('/employee/reports');

    });

        Route::get('/returns/{id}/create',
            [ReturnController::class, 'create'])
                ->name('returns.create');

        Route::post('/returns/{id}',
            [ReturnController::class, 'store'])
                ->name('returns.store');

});



/*
|--------------------------------------------------------------------------
| PROFILE
|--------------------------------------------------------------------------
*/

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

    Route::get('/profile', function () {

        return view('profile.profile');

    });

    Route::get('/change-password', function () {

        return view('profile.change-password');

    });

    Route::post('/change-password',
        function (Request $request) {

        $user = auth()->user();

        if (!Hash::check(
            $request->current_password,
            $user->password
        )) {

            return back()->with(
                'error',
                'Current password incorrect.'
            );
        }

        if (
            $request->new_password !=
            $request->new_password_confirmation
        ) {

            return back()->with(
                'error',
                'Passwords do not match.'
            );
        }

        $user->password = Hash::make(
            $request->new_password
        );

        $user->save();

        return back()->with(
            'success',
            'Password updated.'
        );

    });

Route::post('/profile/upload-photo', [App\Http\Controllers\ProfileController::class, 'uploadPhoto']);


Route::get('/employee/notifications', function () {

    $notifications = \App\Models\Notification::where(
        'user_id',
        auth()->id()
    )
    ->latest()
    ->get();

    return view(
        'employee.notifications',
        compact('notifications')
    );

})->middleware(['auth', 'employee']);



Route::post('/settings/update',
    [UserController::class, 'updateSettings']);

});

Route::post(
    '/admin/maintenance/{id}/complete',
    [MaintenanceController::class, 'complete']
);
