<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\TrackingUpdate;
use App\Support\NotificationManager;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class OrderManagementController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->string('status')->toString();

        return view('admin.orders.index', [
            'orders' => Order::query()
                ->with(['user', 'address', 'payments'])
                ->when($status, fn ($query) => $query->where('status', $status))
                ->latest()
                ->get(),
            'statusOptions' => $this->statusOptions(),
            'selectedStatus' => $status,
        ]);
    }

    public function show(Order $order)
    {
        $order->load(['user.role', 'address', 'items.document', 'payments', 'coupon', 'trackingUpdates']);

        return view('admin.orders.show', [
            'order' => $order,
            'statusOptions' => $this->statusOptions(),
            'paymentStatuses' => [
                'pending' => 'Pending',
                'paid' => 'Paid',
                'failed' => 'Failed',
                'refunded' => 'Refunded',
            ],
        ]);
    }

    public function update(Request $request, Order $order)
    {
        $validated = $request->validate([
            'status' => ['required', Rule::in(array_keys($this->statusOptions()))],
            'payment_status' => ['required', Rule::in(['pending', 'paid', 'failed', 'refunded'])],
            'delivery_partner' => ['nullable', 'string', 'max:100'],
            'tracking_number' => ['nullable', 'string', 'max:100'],
            'tracking_url' => ['nullable', 'url', 'max:255'],
            'tracking_location' => ['nullable', 'string', 'max:100'],
            'tracking_note' => ['nullable', 'string', 'max:500'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

        $order->fill($validated);

        if ($validated['status'] === 'approved' && !$order->approved_at) {
            $order->approved_at = now();
        }

        if ($validated['status'] === 'printing' && !$order->printed_at) {
            $order->printed_at = now();
        }

        if ($validated['status'] === 'dispatched' && !$order->dispatched_at) {
            $order->dispatched_at = now();
        }

        if ($validated['status'] === 'dispatched' && !$order->shipped_at) {
            $order->shipped_at = now();
        }

        if ($validated['status'] === 'delivered' && !$order->delivered_at) {
            $order->delivered_at = now();
        }

        $order->save();

        foreach ($order->payments as $payment) {
            $payment->status = $validated['payment_status'];
            if ($validated['payment_status'] === 'paid' && !$payment->paid_at) {
                $payment->paid_at = now();
            }
            $payment->save();
        }

        TrackingUpdate::query()->create([
            'order_id' => $order->id,
            'status' => $validated['status'],
            'title' => $this->statusOptions()[$validated['status']] ?? ucfirst($validated['status']),
            'description' => $validated['tracking_note'] ?? ('Order moved to ' . $validated['status'] . ' stage.'),
            'location' => $validated['tracking_location'] ?? null,
            'created_by' => $request->user()->id,
        ]);

        NotificationManager::statusUpdated($order->fresh('user'));

        return redirect()->route('admin.orders.show', $order)->with('status', 'Order updated successfully.');
    }

    private function statusOptions(): array
    {
        return [
            'pending' => 'Pending',
            'approved' => 'Approved',
            'printing' => 'Printing',
            'dispatched' => 'Dispatched',
            'delivered' => 'Delivered',
            'rejected' => 'Rejected',
        ];
    }
}
