<?php

namespace Silvanus\blocks\general\GeneralCTA;

use Silvanus\includes\blocks\BlockModuleInterface;

final class Module implements BlockModuleInterface
{
    public function register(): void
    {
        // Populate CTA select choices for this block
        add_filter('acf/load_field/key=field_general_cta_cta', [$this, 'acfPopulateGeneralCtaChoices'], 20);
    }

    public function acfPopulateGeneralCtaChoices(array $field): array
    {
        $field['choices'] = [];

        $globalCtas = get_field('global_ctas', 'options-theme-settings');

        $rows = is_array($globalCtas) && isset($globalCtas['ctas']) && is_array($globalCtas['ctas'])
            ? $globalCtas['ctas']
            : [];

        foreach ($rows as $i => $row) {
            if (!is_array($row)) {
                continue;
            }

            $label = '';
            if (!empty($row['title']) && is_string($row['title'])) {
                $label = $row['title'];
            } elseif (!empty($row['tagline']) && is_string($row['tagline'])) {
                $label = $row['tagline'];
            } else {
                $label = 'CTA #' . ($i + 1);
            }

            // Store row number (1-based)
            $field['choices'][(string) ($i + 1)] = $label;
        }

        return $field;
    }
}