<?php
namespace api\Controllers;

use api\ApiRouter;

class CategoriesApiController
{
    public function list(): void
    {
        if (!ApiRouter::requireMethod('GET')) {
            return;
        }

        $db = $GLOBALS['mdb'] ?? null;
        if (!$db) {
            ApiRouter::sendError('INTERNAL_ERROR', 'Database not available', 500);
            return;
        }

        // Default shop language
        $defaultLang = $db->get('pp_langs', 'id', ['start' => 1]);
        if (!$defaultLang) {
            $defaultLang = 'pl';
        }
        $defaultLang = (string)$defaultLang;

        // All active categories, ordered by display order
        $rows = $db->select(
            'pp_shop_categories',
            ['id', 'parent_id'],
            [
                'status' => 1,
                'ORDER' => ['o' => 'ASC'],
            ]
        );

        if (!is_array($rows) || empty($rows)) {
            ApiRouter::sendSuccess(['categories' => []]);
            return;
        }

        $categoryIds = array_values(array_filter(
            array_map(fn($row) => (int)($row['id'] ?? 0), $rows),
            fn($id) => $id > 0
        ));

        // Bulk fetch titles for default language
        $titlesByCategory = [];
        $titleRows = $db->select('pp_shop_categories_langs', ['category_id', 'title'], [
            'AND' => [
                'category_id' => $categoryIds,
                'lang_id' => $defaultLang,
                'title[!]' => '',
            ],
        ]);
        if (is_array($titleRows)) {
            foreach ($titleRows as $tr) {
                $tid = (int)($tr['category_id'] ?? 0);
                if ($tid > 0 && !isset($titlesByCategory[$tid])) {
                    $titlesByCategory[$tid] = (string)($tr['title'] ?? '');
                }
            }
        }

        // Bulk fetch fallback titles for categories without a title in default language
        $missingIds = array_values(array_filter($categoryIds, fn($id) => !isset($titlesByCategory[$id])));
        if (!empty($missingIds)) {
            $fallbackRows = $db->select('pp_shop_categories_langs', ['category_id', 'title'], [
                'AND' => [
                    'category_id' => $missingIds,
                    'title[!]' => '',
                ],
            ]);
            if (is_array($fallbackRows)) {
                foreach ($fallbackRows as $fr) {
                    $fid = (int)($fr['category_id'] ?? 0);
                    if ($fid > 0 && !isset($titlesByCategory[$fid])) {
                        $titlesByCategory[$fid] = (string)($fr['title'] ?? '');
                    }
                }
            }
        }

        // Build flat category list
        $categories = [];
        foreach ($rows as $row) {
            $categoryId = (int)($row['id'] ?? 0);
            if ($categoryId <= 0) {
                continue;
            }

            $parentId = $row['parent_id'] !== null ? (int)$row['parent_id'] : null;
            $title = $titlesByCategory[$categoryId] ?? ('Kategoria #' . $categoryId);

            $categories[] = [
                'id' => $categoryId,
                'parent_id' => $parentId,
                'title' => $title,
            ];
        }

        ApiRouter::sendSuccess(['categories' => $categories]);
    }
}
