<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Data;

defined('ABSPATH') || exit;

use CliqThemes\StoreLocator\Models\Brand;
use CliqThemes\StoreLocator\Models\Category;

/**
 * Builds the value/label option lists shown in the admin form <select> fields
 * (brand / marker / category pickers). Reads through the ORM models — the same
 * data path the repositories use — so no raw SQL lives in the boot path.
 *
 * Translation overlay is intentionally NOT applied here: these pickers map to
 * canonical row ids.
 */
final class FormSelectOptions
{

    /**
     * Active categories for the store/custom-field category assignment fields.
     *
     * @return array<int, array{value: string, label: string}>
     */
    public function categories(): array
    {
        $options = [];

        foreach (Category::query()->where('is_active', '=', 1)->orderBy('ordering', 'ASC')->orderBy('name', 'ASC')->raw() as $row) {
            $id = isset($row['id']) ? (int) $row['id'] : 0;
            $name = (string) ($row['name'] ?? '');

            if ($id > 0 && $name !== '') {
                $options[] = ['value' => (string) $id, 'label' => $name];
            }
        }

        return $options;
    }

    /**
     * Brands for the store brand picker. Falls back to demo brands when none
     * exist yet.
     *
     * @return array<int, array{value: string, label: string}>
     */
    public function brands(): array
    {
        $options = [];

        foreach (Brand::query()->orderBy('name', 'ASC')->raw() as $row) {
            $id = isset($row['id']) ? (int) $row['id'] : 0;
            $name = (string) ($row['name'] ?? '');

            if ($id > 0 && $name !== '') {
                $options[] = ['value' => (string) $id, 'label' => $name];
            }
        }

        if ($options === []) {
            $options = [
                ['value' => '1', 'label' => __('Cliq Essentials', 'cliq-store-locator')],
                ['value' => '2', 'label' => __('Cliq Luxe', 'cliq-store-locator')],
            ];
        }

        return $options;
    }
}
