<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreOrderRequest;
use App\Models\Category;
use App\Models\Product;
use App\Models\Register;
use App\Services\OrderService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

class PosController extends Controller
{
    public function index(): View
    {
        $user = auth()->user();
        $outletId = (int) $user->outlet_id;

        $catalogCacheKey = "pos.catalog.{$outletId}";
        $catalog = Cache::remember($catalogCacheKey, 300, function () use ($outletId): array {
            return [
                'categories' => Category::query()
                    ->where('outlet_id', $outletId)
                    ->orderBy('sort_order')
                    ->get(),
                'products' => Product::query()
                    ->with(['variants.options', 'addons'])
                    ->where('outlet_id', $outletId)
                    ->where('is_active', true)
                    ->orderBy('name')
                    ->get(),
                'registers' => Register::query()->where('outlet_id', $outletId)->get(),
            ];
        });
        $categories = $catalog['categories'];
        $products = $catalog['products'];
        $registers = $catalog['registers'];
        $defaultRegisterId = $registers->first()?->id;

        return view('pos.index', compact('categories', 'products', 'registers', 'defaultRegisterId'));
    }

    public function store(StoreOrderRequest $request, OrderService $orderService): RedirectResponse|JsonResponse
    {
        $user = $request->user();
        $order = $orderService->createPaidOrder($request->validated(), $user->id, (int) $user->outlet_id);

        if ($request->expectsJson()) {
            return response()->json([
                'order_id' => $order->id,
                'receipt_number' => $order->receipt_number,
                'status' => $order->status,
            ]);
        }

        return redirect()->route('orders.show', $order)->with('success', 'Order dibayar.');
    }
}
