<?php

namespace App\Http\Controllers\Restaurant;

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

class DeliveryController extends Controller
{
    public function store(Request $request)
    {
        $user = $request->user();

        if (!$user || !$user->restaurant_id) {
            abort(403);
        }

        $restaurant = $user->restaurant;

        $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_lat' => 'nullable|numeric',
            'delivery_lng' => 'nullable|numeric',
            'notes' => 'nullable|string',
            'payment_method' => 'required|in:wallet,cash',
        ]);

        $fee = $restaurant?->delivery_fee ?? 0;
        if (($data['payment_method'] ?? 'wallet') === 'wallet' && $fee > 0 && $restaurant && $restaurant->wallet_balance < $fee) {
            return redirect()
                ->back()
                ->withInput()
                ->withErrors(['wallet' => 'Saldo insuficiente para crear la entrega.']);
        }

        $delivery = DB::transaction(function () use ($data, $fee, $restaurant, $user) {
            $data['status'] = 'pending';
            $data['restaurant_id'] = $user->restaurant_id;
            $data['delivery_fee'] = $fee;
            $data['payment_method'] = $data['payment_method'] ?? 'wallet';
            $delivery = Delivery::create($data);

            if ($fee > 0 && $restaurant && $data['payment_method'] === 'wallet') {
                app(WalletService::class)->debitRestaurant(
                    $restaurant,
                    $fee,
                    'Cobro por entrega #' . $delivery->id,
                    $delivery->id,
                    $user->id
                );
            }
            if ($fee > 0 && $restaurant && $data['payment_method'] === 'cash') {
                app(WalletService::class)->recordRestaurantMovement(
                    $restaurant,
                    $fee,
                    'cash_out',
                    'Pago en efectivo entrega #' . $delivery->id,
                    $delivery->id,
                    $user->id
                );
            }

            return $delivery;
        });

        // Optional: notify admin via Telegram if configured.
        app(TelegramNotificationService::class)->sendToAdmin(
            app(TelegramNotificationService::class)->formatAdminNewOrder($delivery)
        );

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

        return redirect()
            ->route('restaurant.dashboard')
            ->with('success', 'Entrega creada correctamente.');
    }

    public function urgent(Request $request)
    {
        $user = $request->user();

        if (!$user || !$user->restaurant_id) {
            abort(403);
        }

        $restaurant = $user->restaurant;
        $data = $request->validate([
            'payment_method' => 'required|in:wallet,cash',
            'notes' => 'nullable|string',
        ]);

        $fee = $restaurant?->delivery_fee ?? 0;
        if (($data['payment_method'] ?? 'wallet') === 'wallet' && $fee > 0 && $restaurant && $restaurant->wallet_balance < $fee) {
            return redirect()
                ->back()
                ->withInput()
                ->withErrors(['wallet' => 'Saldo insuficiente para crear la entrega urgente.']);
        }

        $delivery = DB::transaction(function () use ($data, $fee, $restaurant, $user) {
            $payload = [
                'status' => 'pending',
                'restaurant_id' => $user->restaurant_id,
                'delivery_fee' => $fee,
                'payment_method' => $data['payment_method'] ?? 'wallet',
                'is_urgent' => true,
                'urgent_requested_at' => now(),
                'customer_name' => 'Por definir',
                'customer_phone' => null,
                'delivery_address' => 'Por definir',
                'delivery_address_extra' => null,
                'notes' => $data['notes'] ?? null,
            ];

            $delivery = Delivery::create($payload);

            if ($fee > 0 && $restaurant && $payload['payment_method'] === 'wallet') {
                app(WalletService::class)->debitRestaurant(
                    $restaurant,
                    $fee,
                    'Cobro urgente #' . $delivery->id,
                    $delivery->id,
                    $user->id
                );
            }
            if ($fee > 0 && $restaurant && $payload['payment_method'] === 'cash') {
                app(WalletService::class)->recordRestaurantMovement(
                    $restaurant,
                    $fee,
                    'cash_out',
                    'Pago en efectivo urgente #' . $delivery->id,
                    $delivery->id,
                    $user->id
                );
            }

            return $delivery;
        });

        app(TelegramNotificationService::class)->sendToAdmin(
            app(TelegramNotificationService::class)->formatAdminNewOrder($delivery)
        );

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

        return redirect()
            ->route('restaurant.dashboard')
            ->with('success', 'Repartidor solicitado con urgencia.');
    }

    public function reassign(Delivery $delivery)
    {
        $user = request()->user();

        if (!$user || $user->restaurant_id !== $delivery->restaurant_id) {
            abort(403);
        }

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

        return redirect()
            ->back()
            ->with('success', 'Pedido reasignado al siguiente repartidor.');
    }
}
