<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderStatusHistory;
use App\Models\AuditLog;
use App\Services\Notification\NotificationDispatcher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderAdminController extends Controller
{
    protected NotificationDispatcher $notifications;

    public function __construct(NotificationDispatcher $notifications)
    {
        $this->notifications = $notifications;
    }

    public function index(Request $request)
    {
        $query = Order::with('user', 'vehicle', 'auctionVehicle');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('order_number', 'like', "%{$search}%")
                  ->orWhere('bl_number', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($uq) use ($search) {
                      $uq->where('name', 'like', "%{$search}%")
                         ->orWhere('phone', 'like', "%{$search}%");
                  });
            });
        }

        $orders = $query->orderBy('created_at', 'desc')->paginate(15)->withQueryString();
        $trackingSteps = Order::trackingSteps();

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

    public function show(string $id)
    {
        $order = Order::with('user.customer', 'vehicle', 'auctionVehicle', 'bid', 'statusHistory.updater', 'invoices.payments')
            ->findOrFail($id);

        $trackingSteps = Order::trackingSteps();

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

    public function updateTracking(Request $request, string $id)
    {
        $order = Order::findOrFail($id);

        $validated = $request->validate([
            'status' => 'required|string',
            'title' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'location' => 'nullable|string|max:255',
        ]);

        $oldStatus = $order->status;
        $order->update(['status' => $validated['status']]);

        OrderStatusHistory::create([
            'order_id' => $order->id,
            'status' => $validated['status'],
            'title' => $validated['title'],
            'description' => $validated['description'] ?? null,
            'location' => $validated['location'] ?? null,
            'updated_by' => Auth::id(),
            'occurred_at' => now(),
        ]);

        AuditLog::record('admin_updated_order_tracking', $order, ['status' => $oldStatus], ['status' => $validated['status']]);

        // Notify customer about milestone progress
        $this->notifications->notifyUser(
            $order->user,
            "Import Update: {$validated['title']}",
            "Your order #{$order->order_number} has advanced to: {$validated['title']}." . ($validated['location'] ? " Location: {$validated['location']}." : ""),
            route('customer.orders.show', $order->id)
        );

        return back()->with('success', "Import tracking status updated to: {$validated['title']}");
    }

    public function updateShipping(Request $request, string $id)
    {
        $order = Order::findOrFail($id);

        $validated = $request->validate([
            'vessel_name' => 'nullable|string|max:255',
            'voyage_number' => 'nullable|string|max:100',
            'bl_number' => 'nullable|string|max:100',
            'container_number' => 'nullable|string|max:100',
            'shipping_line' => 'nullable|string|max:150',
            'eta_chittagong' => 'nullable|date',
            'assigned_reg_number' => 'nullable|string|max:100',
        ]);

        $order->update($validated);

        AuditLog::record('admin_updated_order_shipping_details', $order);

        return back()->with('success', 'Shipping and logistics details saved.');
    }
}
