<?php

declare(strict_types=1);

namespace App\Modules\Parties\Presentation\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Modules\Parties\Application\Services\PartyLookupService;
use Throwable;

final class PartyAjaxController
{
    public function customers(): void
    {
        $_GET['type'] = 'customer';
        $this->search();
    }

    public function suppliers(): void
    {
        $_GET['type'] = 'supplier';
        $this->search();
    }

    public function __construct(private ?PartyLookupService $service = null)
    {
        $this->service ??= new PartyLookupService(db());
    }

    public function search(): void
    {
        Auth::requireLogin();
        header('Content-Type: application/json; charset=utf-8');
        $this->service->ensureSchema();

        try {
            if (rbac_enabled(db())) {
                $ok = can('parties.view') || can('customers.view') || can('suppliers.view') || can('sales.invoices.create') || can('sales.receipts.create') || can('cash.payments.create');
                if (!$ok) {
                    http_response_code(403);
                    echo '[]';
                    return;
                }
            }
        } catch (Throwable) {
        }

        echo json_encode(
            $this->service->search(
                trim((string) Request::get('type', 'all')),
                trim((string) Request::get('q', '')),
            ),
            JSON_UNESCAPED_UNICODE
        );
    }
}
