<?php

namespace App\Http\Controllers\Courier;

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

class RequestController extends Controller
{
    public function index(Request $request)
    {
        $requests = ServiceRequest::with('partner')
            ->where('assigned_courier_id', $request->user()->id)
            ->orderByRaw("FIELD(status, 'assigne', 'collecte', 'non_disponible', 'livre', 'traite', 'ecart')")
            ->latest()
            ->paginate(20);

        return view('courier.requests.index', compact('requests'));
    }

    public function show(ServiceRequest $serviceRequest)
    {
        abort_unless($serviceRequest->assigned_courier_id === request()->user()->id, 403);

        $serviceRequest->load('partner');

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

    /**
     * Le coursier confirme la collecte physique - seule action qui fait foi.
     * Toute difference avec la quantite demandee declenche automatiquement un statut "ecart".
     */
    public function collect(Request $request, ServiceRequest $serviceRequest)
    {
        abort_unless($serviceRequest->assigned_courier_id === $request->user()->id, 403);

        $data = $request->validate([
            'collected_quantity' => ['required', 'integer', 'min:0'],
            'comment' => ['nullable', 'string', 'max:500'],
            'photo' => ['nullable', 'image', 'max:5120'],
        ]);

        $photoPath = null;
        if ($request->hasFile('photo')) {
            $photoPath = $request->file('photo')->store('collectes', 'public');
        }

        $serviceRequest->update([
            'collected_quantity' => $data['collected_quantity'],
            'photo_path' => $photoPath ?? $serviceRequest->photo_path,
            'collected_at' => now(),
        ]);

        $hasDiscrepancy = $serviceRequest->hasDiscrepancy();

        $serviceRequest->changeStatus(
            $hasDiscrepancy ? ServiceRequest::STATUS_ECART : ServiceRequest::STATUS_COLLECTE,
            $request->user(),
            $data['comment'] ?? ($hasDiscrepancy
                ? "Ecart: demande {$serviceRequest->requested_quantity}, collecte {$data['collected_quantity']}"
                : 'Collecte confirmee par le coursier')
        );

        $message = $hasDiscrepancy
            ? 'Collecte enregistree. Attention : un ecart de quantite a ete detecte et signale a l\'admin.'
            : 'Collecte confirmee avec succes.';

        return redirect()->route('courier.requests.index')->with($hasDiscrepancy ? 'warning' : 'success', $message);
    }

    public function unavailable(Request $request, ServiceRequest $serviceRequest)
    {
        abort_unless($serviceRequest->assigned_courier_id === $request->user()->id, 403);

        $data = $request->validate([
            'unavailable_reason' => ['required', 'string', 'max:255'],
        ]);

        $serviceRequest->update(['unavailable_reason' => $data['unavailable_reason']]);
        $serviceRequest->changeStatus(
            ServiceRequest::STATUS_NON_DISPONIBLE,
            $request->user(),
            $data['unavailable_reason']
        );

        return redirect()->route('courier.requests.index')
            ->with('warning', 'Statut "non disponible" enregistre et remonte a l\'admin.');
    }

    public function deliver(Request $request, ServiceRequest $serviceRequest)
    {
        abort_unless($serviceRequest->assigned_courier_id === $request->user()->id, 403);

        $serviceRequest->update(['delivered_at' => now()]);
        $serviceRequest->changeStatus(
            ServiceRequest::STATUS_LIVRE,
            $request->user(),
            'Livre au laboratoire'
        );

        return redirect()->route('courier.requests.index')->with('success', 'Livraison confirmee.');
    }
}
