<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ServiceRequest;
use App\Models\User;
use Illuminate\Http\Request;

class RequestController extends Controller
{
    public function index(Request $request)
    {
        $query = ServiceRequest::with(['partner', 'courier']);

        if ($request->filled('type')) {
            $query->where('type', $request->string('type'));
        }

        if ($request->filled('status')) {
            $query->where('status', $request->string('status'));
        }

        if ($request->filled('partner_id')) {
            $query->where('partner_id', $request->integer('partner_id'));
        }

        $requests = $query->latest()->paginate(25)->withQueryString();

        $types = ServiceRequest::types();
        $statuses = ServiceRequest::statuses();
        $couriers = User::where('role', User::ROLE_COURIER)->where('active', true)->get();

        return view('admin.requests.index', compact('requests', 'types', 'statuses', 'couriers'));
    }

    public function show(ServiceRequest $serviceRequest)
    {
        $serviceRequest->load(['partner', 'courier', 'statusHistories.author']);
        $couriers = User::where('role', User::ROLE_COURIER)->where('active', true)->get();

        return view('admin.requests.show', compact('serviceRequest', 'couriers'));
    }

    public function assign(Request $request, ServiceRequest $serviceRequest)
    {
        $data = $request->validate([
            'assigned_courier_id' => ['required', 'exists:users,id'],
        ]);

        $serviceRequest->update(['assigned_courier_id' => $data['assigned_courier_id']]);
        $serviceRequest->changeStatus(
            ServiceRequest::STATUS_ASSIGNE,
            $request->user(),
            'Assigne par admin'
        );

        return back()->with('success', 'Demande assignee au coursier.');
    }
}
