<?php
namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderTracking;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    // ── User: My Orders Page ─────────────────────────────────────────────────
    public function index()
    {
        $orders = Order::where('user_id', auth()->id())
            ->with(['items.product.images', 'latestTracking'])
            ->orderByDesc('created_at')
            ->paginate(10);

        $allOrders = Order::where('user_id', auth()->id())->get();

        $pendingCount   = $allOrders->whereIn('status', ['pending', 'payment_submitted'])->count();
        $activeCount    = $allOrders->whereIn('status', ['processing', 'shipped', 'in_transit', 'out_for_delivery'])->count();
        $completedCount = $allOrders->whereIn('status', ['delivered', 'completed', 'cancelled', 'refunded'])->count();

        return view('user-order-page', compact('orders', 'pendingCount', 'activeCount', 'completedCount'));
    }

    // ── User: Get Tracking JSON ──────────────────────────────────────────────
    public function tracking(Order $order)
    {
        if ($order->user_id !== auth()->id()) {
            abort(403);
        }

        $order->load('trackingUpdates');
        $latest = $order->trackingUpdates->last();

        return response()->json([
            'order_id'           => $order->id,
            'status'             => $order->status,
            'estimated_delivery' => $latest?->estimated_delivery?->format('M d, Y'),
            'updates'            => $order->trackingUpdates->map(fn($t) => [
                'status'             => $t->status,
                'location'           => $t->location,
                'note'               => $t->note,
                'estimated_delivery' => $t->estimated_delivery?->format('M d, Y'),
                'created_at'         => $t->created_at->format('M d, Y h:i A'),
            ]),
        ]);
    }

    // ── Admin: All Orders ────────────────────────────────────────────────────
    public function adminIndex(Request $request)
    {
        $query = Order::with(['items', 'user', 'latestTracking'])
            ->orderByDesc('created_at');

        if ($request->filled('search')) {
            $s = $request->search;
            $query->where(function ($q) use ($s) {
                $q->where('id', 'like', "%$s%")
                    ->orWhere('first_name', 'like', "%$s%")
                    ->orWhere('last_name', 'like', "%$s%")
                    ->orWhere('email', 'like', "%$s%");
            });
        }

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

        if ($request->filled('payment_method')) {
            $query->where('payment_method', $request->payment_method);
        }

        $orders = $query->paginate(15);

        $stats = [
            'total'             => Order::count(),
            'pending'           => Order::where('status', 'pending')->count(),
            'payment_submitted' => Order::where('status', 'payment_submitted')->count(),
            'processing'        => Order::where('status', 'processing')->count(),
            'shipped'           => Order::where('status', 'shipped')->count(),
            'completed'         => Order::whereIn('status', ['delivered', 'completed'])->count(),
            'cancelled'         => Order::where('status', 'cancelled')->count(),
        ];

        return view('admin-order', compact('orders', 'stats'));
    }

    // ── Admin: View Single Order JSON ────────────────────────────────────────
    public function adminShow(Order $order)
    {
        $order->load(['items', 'trackingUpdates']);

        return response()->json(array_merge($order->toArray(), [
            'items'    => $order->items->toArray(),
            'tracking' => $order->trackingUpdates->map(fn($t) => [
                'status'             => $t->status,
                'location'           => $t->location,
                'note'               => $t->note,
                'estimated_delivery' => $t->estimated_delivery?->format('M d, Y'),
                'created_at'         => $t->created_at->format('M d, Y h:i A'),
            ]),
        ]));
    }

    // ── Admin: Update Tracking ───────────────────────────────────────────────
    public function adminUpdateTracking(Request $request, Order $order)
    {
        $request->validate([
            'status'             => 'required|in:pending,payment_submitted,processing,shipped,in_transit,out_for_delivery,delivered,completed,cancelled,refunded',
            'location'           => 'nullable|string|max:255',
            'note'               => 'nullable|string|max:1000',
            'estimated_delivery' => 'nullable|date',
        ]);

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

        $existingEstimate = $order->latestTracking?->estimated_delivery;

        OrderTracking::create([
            'order_id'           => $order->id,
            'status'             => $request->status,
            'location'           => $request->location,
            'note'               => $request->note,
            'estimated_delivery' => $request->estimated_delivery ?? $existingEstimate,
            'updated_by'         => auth()->id(),
        ]);

        return redirect()->route('admin.orders')
            ->with('success', "Order #{$order->id} updated to \"" . ucfirst(str_replace('_', ' ', $request->status)) . '".');
    }
}
