<?php

namespace Modules\Admin\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Admin\Services\OrderService;

class OrderController extends Controller
{
    public function __construct(
        private OrderService $orderService
    ) {}

    public function index(Request $request)
    {
        $filters = $request->only(['status', 'payment_status', 'search', 'date_from', 'date_to']);
        $orders = $this->orderService->getAll(10, array_filter($filters));
        $statusCounts = $this->orderService->getStatusCounts();
        $totalRevenue = $this->orderService->getStatusCounts(); // placeholder, we'll keep passing from repo
        return view('admin::orders.index', compact('orders', 'statusCounts', 'filters'));
    }

    public function show(int $id)
    {
        $order = $this->orderService->findById($id);
        if (!$order) {
            return redirect()->route('admin.orders.index')->with('error', 'Order not found.');
        }
        $statuses = ['pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled'];
        $paymentStatuses = ['pending', 'paid', 'failed', 'refunded'];
        return view('admin::orders.show', compact('order', 'statuses', 'paymentStatuses'));
    }

    public function edit(int $id)
    {
        $order = $this->orderService->findById($id);
        if (!$order) {
            return redirect()->route('admin.orders.index')->with('error', 'Order not found.');
        }
        return view('admin::orders.edit', compact('order'));
    }

    public function update(Request $request, int $id)
    {
        $data = $request->validate([
            'status' => 'required|string|in:pending,confirmed,processing,shipped,delivered,cancelled',
            'payment_status' => 'required|string|in:pending,paid,failed,refunded',
            'notes' => 'nullable|string',
        ]);

        $this->orderService->update($id, $data);

        return redirect()->route('admin.orders.index')
            ->with('success', 'Order updated successfully.');
    }

    public function destroy(int $id)
    {
        $this->orderService->delete($id);
        return redirect()->route('admin.orders.index')
            ->with('success', 'Order deleted successfully.');
    }
}
