<?php


declare(strict_types=1);

require_once __DIR__ . '/BaseHandler.php';

final class CategoriesHandler extends BaseHandler
{
    public function handle(): void
    {
        $this->requireMethod('GET');

        if (($this->setting['statuscategorygenral'] ?? '') === 'offcategorys') {
            AYCoreResponse::ok([]);
        }

        $codePanel = $this->resolveCountryId();
        if ($codePanel === '') {
            AYCoreResponse::badRequest('انتخاب موقعیت/کشور الزامی است.');
        }
        $panel = $this->loadPanelByCode($codePanel);

        $allCategories = AYCoreDb::fetchAll('SELECT * FROM category');

        $userAgent = $this->user['agent'] ?? 'f';
        $list = [];
        foreach ($allCategories as $cat) {
            $count = (int) AYCoreDb::fetchScalar(
                "SELECT COUNT(*) FROM product
                  WHERE (Location = :location OR Location = '/all')
                    AND category = :category
                    AND (agent = :agent OR agent = 'all')",
                [
                    ':location' => $panel['name_panel'],
                    ':category' => $cat['remark'],
                    ':agent'    => $userAgent,
                ]
            );
            if ($count === 0) continue;

            $list[] = [
                'id' => $cat['id'],
                'name' => $cat['remark'],
            ];
        }

        AYCoreResponse::ok($list);
    }
}

