<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DeliveryAgent;
use App\Models\DeliveryAssignment;
use App\Models\Order;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class DeliveryOrderController extends Controller
{
    public function index(Request $request): View
    {
        $query = Order::whereNotNull('delivery_status')
            ->with(['user', 'deliveryAgent', 'deliveryAssignment']);

        if ($request->has('status')) {
            $query->where('delivery_status', $request->status);
        }

        if ($request->has('agent_id')) {
            $query->where('delivery_agent_id', $request->agent_id);
        }

        $orders = $query->latest()->paginate(20);
        $agents = DeliveryAgent::where('status', 'active')->with('user')->get();

        return view('admin.delivery.orders.index', compact('orders', 'agents'));
    }

    public function assign(Request $request, Order $order): RedirectResponse
    {
        $validated = $request->validate([
            'delivery_agent_id' => 'required|exists:delivery_agents,id',
            'delivery_fee' => 'nullable|numeric|min:0',
        ]);

        $agent = DeliveryAgent::findOrFail($validated['delivery_agent_id']);

        if ($order->delivery_agent_id) {
            return back()->with('error', 'Order is already assigned.');
        }

        DB::transaction(function () use ($order, $agent, $validated) {
            $assignment = DeliveryAssignment::create([
                'order_id' => $order->id,
                'delivery_agent_id' => $agent->id,
                'status' => 'assigned',
                'assigned_at' => now(),
                'delivery_fee' => $validated['delivery_fee'] ?? 50.00,
                'delivery_otp' => str_pad((string) rand(1000, 9999), 4, '0', STR_PAD_LEFT),
            ]);

            $order->update([
                'delivery_status' => 'assigned',
                'delivery_agent_id' => $agent->id,
                'delivery_fee' => $validated['delivery_fee'] ?? 50.00,
                'assigned_at' => now(),
            ]);
        });

        return back()->with('success', 'Order assigned successfully.');
    }

    public function show(Order $order): View
    {
        $order->load(['user', 'items.product', 'deliveryAgent.user', 'deliveryAssignment.tracking']);
        $availableAgents = DeliveryAgent::where('status', 'active')
            ->where('is_online', true)
            ->with('user')
            ->get();

        return view('admin.delivery.orders.show', compact('order', 'availableAgents'));
    }
}
