<?php

namespace App\Http\Controllers\Courier;

use App\Http\Controllers\Controller;
use App\Models\Delivery;
use App\Models\DeliveryRejection;
use Illuminate\Http\Request;
use App\Services\DeliveryAssigner;
use App\Services\WalletService;
use Illuminate\Support\Facades\DB;

class DeliveryController extends Controller
{
    public function updateStatus(Request $request, Delivery $delivery)
    {
        $courierId = $request->user()->courier_id;

        if (!$courierId || $delivery->courier_id !== $courierId) {
            abort(403);
        }

        $data = $request->validate([
            'status' => 'required|in:pending,confirmed,at_restaurant,en_route,delivered',
        ]);

        if ($data['status'] === 'delivered' && $delivery->is_urgent) {
            $missingDetails = empty($delivery->customer_name)
                || $delivery->customer_name === 'Por definir'
                || empty($delivery->delivery_address)
                || $delivery->delivery_address === 'Por definir'
                || empty($delivery->customer_phone);

            if ($missingDetails) {
                return redirect()
                    ->route('courier.dashboard')
                    ->withErrors(['details' => 'Completa los datos del cliente antes de finalizar la entrega.']);
            }
        }

        DB::transaction(function () use ($delivery, $data, $request) {
            $delivery->update([
                'status' => $data['status'],
                'completed_at' => $data['status'] === 'delivered' ? now() : $delivery->completed_at,
            ]);

            if ($data['status'] === 'delivered' && !$delivery->fee_transferred_at) {
                app(WalletService::class)->transferDeliveryFee($delivery, $request->user()->id);
                $delivery->update([
                    'fee_transferred_at' => now(),
                ]);
            }
        });

        return redirect()
            ->back()
            ->with('success', 'Estado actualizado.');
    }

    public function reject(Request $request, Delivery $delivery)
    {
        $courierId = $request->user()->courier_id;

        if (!$courierId || $delivery->courier_id !== $courierId) {
            abort(403);
        }

        $data = $request->validate([
            'reason' => 'nullable|string|max:255',
        ]);

        DeliveryRejection::create([
            'delivery_id' => $delivery->id,
            'courier_id' => $courierId,
            'reason' => $data['reason'] ?? null,
        ]);

        $delivery->update([
            'courier_id' => null,
            'status' => Delivery::STATUS_PENDING,
        ]);

        $assigner = app(DeliveryAssigner::class);
        $assigner->assignNext($delivery);

        $delivery->refresh();
        if ($delivery->courier_id !== $courierId) {
            $assigner->assignNextForCourier($courierId, $delivery->id);
        }

        return redirect()
            ->route('courier.dashboard')
            ->with('success', 'Pedido rechazado y reasignado.');
    }

    public function updateDetails(Request $request, Delivery $delivery)
    {
        $courierId = $request->user()->courier_id;

        if (!$courierId || $delivery->courier_id !== $courierId) {
            abort(403);
        }

        $data = $request->validate([
            'customer_name' => 'required|string|max:255',
            'customer_phone' => 'nullable|string|max:50',
            'delivery_address' => 'required|string|max:255',
            'delivery_address_extra' => 'nullable|string|max:255',
        ]);

        $delivery->update($data);

        return redirect()
            ->back()
            ->with('success', 'Datos de entrega actualizados.');
    }
}
