<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Location;
use App\Services\LocationService;
use Illuminate\View\View;

class PosController extends Controller
{
    public function __construct(protected LocationService $locationService)
    {
        $this->middleware('auth');
    }

    public function index(): View
    {
        // Check if user has pos_access permission or is admin/staff
        $user = auth()->user();
        if (!$user->can('pos_access') && !$user->isAdmin() && !$user->isStaff()) {
            abort(403, 'You do not have permission to access POS.');
        }

        $this->locationService->ensureCompanyAndDefaults();
        $locations = $this->locationService->accessibleStores($user);
        $currentLocationId = $this->locationService->resolveLocationIdForUser($user);

        // POS must run at a store — reject warehouse context
        if ($currentLocationId) {
            $current = Location::query()->find($currentLocationId);
            if (!$current || $current->type !== Location::TYPE_STORE) {
                $fallback = $locations->first();
                if (!$fallback) {
                    abort(403, 'POS requires an active store location. Warehouses cannot be used for POS.');
                }
                $currentLocationId = (int) $fallback->id;
            }
            $this->locationService->setCurrentLocation((int) $currentLocationId);
        } elseif ($locations->isNotEmpty()) {
            $currentLocationId = (int) $locations->first()->id;
            $this->locationService->setCurrentLocation($currentLocationId);
        } else {
            abort(403, 'POS requires an active store location. Warehouses cannot be used for POS.');
        }

        return view('admin.pos.index', [
            'posLocations' => $locations,
            'currentLocationId' => $currentLocationId,
        ]);
    }
}
