<?php

declare(strict_types=1);

namespace App\Modules\Sales\Application\Services;

final class PosPageService
{
    public function handleIndex(): void
    {
        require_login();

        $pdo = db();
        \App\Core\AppBootstrap::bootPos($pdo);
        require_permission('sales.pos');

        $cartService = new PosCartService();
        $suspendedCartService = new PosSuspendedCartService();
        $formService = new PosFormService();
        $cartService->ensureSessionState();
        $suspendedCartService->ensureSessionState();

        (new PosActionService($formService, $cartService, $suspendedCartService))->handle($pdo);

        $pageData = $formService->loadIndexData($pdo, $cartService, $suspendedCartService);
        $this->renderIndex($pageData);
    }

    public function handleSuspended(): void
    {
        $suspendedService = new PosSuspendedCartService();
        $cartService = new PosCartService();
        $suspendedService->ensureSessionState();
        $cartService->ensureSessionState();

        $this->renderSuspended([
            'suspended_carts' => $suspendedService->allForDisplay(db(), $cartService),
        ]);
    }

    public function pageData(): array
    {
        return [
            'dashboard' => PosRouteContext::dashboard(),
            'sales_home' => PosRouteContext::salesHome(),
            'pos' => PosRouteContext::pos(),
            'suspended' => PosRouteContext::suspended(),
            'invoice_view' => static fn (int $id): string => PosRouteContext::invoiceView($id),
        ];
    }

    public function renderIndex(array $data): void
    {
        $routeContext = $this->pageData();
        view('pages/pos/index', array_merge($data, [
            'routeContext' => $routeContext,
            'page_title' => 'نقطة البيع',
            'breadcrumbs' => [
                ['label' => 'لوحة التحكم', 'url' => $routeContext['dashboard']],
                ['label' => 'المبيعات', 'url' => $routeContext['sales_home']],
                ['label' => 'نقطة البيع'],
            ],
        ]));
    }

    public function renderSuspended(array $data): void
    {
        $routeContext = $this->pageData();
        view('pages/pos/suspended', array_merge($data, [
            'routeContext' => $routeContext,
            'page_title' => 'السلال المعلقة',
            'breadcrumbs' => [
                ['label' => 'لوحة التحكم', 'url' => $routeContext['dashboard']],
                ['label' => 'المبيعات', 'url' => $routeContext['sales_home']],
                ['label' => 'نقطة البيع', 'url' => $routeContext['pos']],
                ['label' => 'السلال المعلقة'],
            ],
        ]));
    }
}
