<?php

namespace App\Http\Controllers;

use App\Http\Requests\RefundOrderRequest;
use App\Http\Requests\VoidOrderRequest;
use App\Models\Order;
use App\Services\OrderService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class OrderController extends Controller
{
    public function index(): View
    {
        $user = auth()->user();
        $query = Order::query()
            ->with(['payments'])
            ->where('outlet_id', $user->outlet_id)
            ->latest();

        if ($user->role === 'cashier') {
            $query->where('user_id', $user->id);
        }

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

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

    public function show(Order $order): View
    {
        $this->authorizeOrderAccess($order);

        $order->load(['items', 'payments', 'outlet']);

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

    public function print(Order $order): View
    {
        $this->authorizeOrderAccess($order);
        $order->load(['items', 'payments', 'outlet']);

        return view('orders.print', compact('order'));
    }

    public function void(VoidOrderRequest $request, Order $order, OrderService $service): RedirectResponse
    {
        abort_unless(in_array($request->user()->role, ['owner', 'admin'], true), 403);
        $service->voidOrder($order, $request->user()->id, $request->validated()['reason']);

        return back()->with('success', 'Order di-void.');
    }

    public function refund(RefundOrderRequest $request, Order $order, OrderService $service): RedirectResponse
    {
        abort_unless(in_array($request->user()->role, ['owner', 'admin'], true), 403);
        $this->authorizeOrderAccess($order);
        $service->refundOrder(
            $order,
            $request->user()->id,
            (int) $request->validated('amount'),
            $request->validated('reason'),
            $request->validated('method') ?? 'CASH',
            $request->validated('reference')
        );

        return back()->with('success', 'Refund berhasil dicatat.');
    }

    private function authorizeOrderAccess(Order $order): void
    {
        $user = auth()->user();
        abort_if((int) $order->outlet_id !== (int) $user->outlet_id, 403);

        if ($user->role === 'cashier') {
            abort_if((int) $order->user_id !== (int) $user->id, 403);
        }
    }
}
