<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\VehicleRequest;
use App\Models\Vehicle;
use App\Models\AuditLog;
use App\Models\Notification;

class RequestController extends Controller
{
    public function index(Request $request)
    {
        if (auth()->user()->role != 'admin') {
            abort(403);
        }

        $search = $request->search;

        $requests = VehicleRequest::with('user', 'vehicle')

            ->when($search, function ($query) use ($search) {

                $query->whereHas('user', function ($q) use ($search) {
                    $q->where('name', 'like', "%$search%");
                })

                ->orWhereHas('vehicle', function ($q) use ($search) {
                    $q->where('vehicle_name', 'like', "%$search%");
                })

                ->orWhere('status', 'like', "%$search%");
            })

            ->latest()
            ->get();

        return view('admin.requests', compact(
            'requests',
            'search'
        ));
    }

    public function approve($id)
    {
        if (auth()->user()->role != 'admin') {
            abort(403);
        }

        $request = VehicleRequest::findOrFail($id);

        $request->update([
            'status' => 'approved'
        ]);

        \App\Models\Notification::create([
            'user_id' => $request->user_id,
            'message' => 'Your vehicle request has been approved.',
            'is_read' => false
        ]);

        $vehicle = Vehicle::find($request->vehicle_id);

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

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

        Notification::create([
            'user_id' => $request->user_id,
            'message' =>
                'Your request for ' .
                $vehicle->vehicle_name .
                ' was approved.'
        ]);

        return back();
    }

    public function reject($id)
    {
        if (auth()->user()->role != 'admin') {
            abort(403);
        }

        $request = VehicleRequest::findOrFail($id);

        $request->update([
            'status' => 'rejected'
        ]);

        \App\Models\Notification::create([
            'user_id' => $request->user_id,
            'message' => 'Your vehicle request has been rejected.',
            'is_read' => false
        ]);

        $vehicle = Vehicle::find($request->vehicle_id);

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

        Notification::create([
            'user_id' => $request->user_id,
            'message' =>
                'Your request for ' .
                $vehicle->vehicle_name .
                ' was rejected.'
        ]);

        return back();
    }
}