<?php

namespace Silvanus\includes\blocks;

use apexl\Utils\Debug\ErrorLog;
use StoutLogic\AcfBuilder\FieldsBuilder;

class AcfBlockFields
{
    protected string $blockKey;
    protected string $blockTitle;
    protected FieldsBuilder $fieldsBuilder;

    public function __construct(string $blockTitle, string $filename, ?FieldsBuilder $fieldsBuilder = null)
    {
        $this->initialise($blockTitle, $filename, $fieldsBuilder);
    }
    public function initialise($blockTitle, $filename, $fields_builder = null): FieldsBuilder
    {
        $this->blockTitle = $blockTitle;
        $this->blockKey = $this->generateKey($this->blockTitle);

        $fields_builder ??= new FieldsBuilder($this->blockTitle);
        $this->fieldsBuilder = $fields_builder;
        $this->fieldsBuilder->setGroupConfig('key', $this->blockKey);

        // add default group fields
        $this->defaultGroupFields();


        // strip any reference to .acf.php from the filename (if that's what's been passed)
        $this->fieldsBuilder->setLocation('block', '==', 'acf/' . str_replace(['.acf.php'], '', basename($filename)));
        return $fields_builder;
    }

    public function defaultGroupFields() {}
    public function addContainerSettings()
    {
        $this->fieldsBuilder->addGroup('block_settings', ["layout" => "row"])
            ->addChoiceField("vheight", "select", [
                "choices" => [
                    "" => "Ignore",
                    "has-vh vh-25" => "25% vh",
                    "has-vh vh-30" => "30% vh",
                    "has-vh vh-35" => "35% vh",
                    "has-vh vh-50" => "50% vh",
                    "has-vh vh-65" => "65% vh",
                    "has-vh vh-75" => "75% vh",
                    "has-vh vh-90" => "90% vh",
                    "has-vh vh-100" => "100% vh",
                ],
                "instructions" => "Select the block Vheight - uses Bootstrap classes",
            ])
            ->addChoiceField("container", 'select', [
                'choices' => [
                    'default' => 'Site Default',
                    'container' => 'Yes',
                    '' => 'No',
                ],
                'default' => ['default'],
                'instructions' => 'Use this to override the global container setting for this block.',
            ])->setDefaultValue('default')
            ->addText("content_classes", [
                'instructions' => 'Add any additional classes to the content wrapper for this block',
            ]);
    }

    public function addGridOptions(): void
    {
        $this->addNumber("row columns", [
            'default_value' => 2,
            'min' => 1,
            'description' => 'Use this to set the number of columns for this grid',
        ]);
        $this->bootstrapColumnSettings();
    }

    public function bootstrapColumnSettings(): void
    {
        $this->addRepeater('column settings', ['layout' => 'inline-block'])
            ->addChoiceField("break selector", "select", [
                "choices" => [
                    "" => "Extra Small (xs)",
                    "sm-" => "Small (sm)",
                    "md-" => "Medium (md)",
                    "lg-" => "Large (lg)",
                    "xl-" => "Extra Large (xl)",
                    "xxl-" => "Extra extra Large (xxl)",
                ],
                'default_value' => ['md-']
            ])
            ->addNumber("column width", [
                'default_value' => 6,
                'description' => 'Col width value for this breakpoint',
            ])
            ->endRepeater();
    }

    public function addDefaultVideoOptions(): void
    {
        $this->addCheckbox('Enable all controls?', [
            'choices' => ['Yes'],
            'layout' => 'horizontal',
        ]);
        $this->addCheckbox('Auto Play?', [
            'choices' => ['Yes'],
            'layout' => 'horizontal',
        ]);
        $this->addFile('Video MP4', [
            'mime_types' => 'mp4',
        ]);
        $this->addFile('Video webm', [
            'mime_types' => 'webm',
        ]);
    }

    public static function Title($blockName, $fields_builder = null) {}
    public function generateKey($key): array|string|null
    {
        // replace spaces with underscores
        $key = str_replace(' ', '_', $key);
        return preg_replace('/[^A-Za-z_]/', '', strtolower(strip_tags($key, '_')));
    }

    /**
     * We need to handle defaults for each field call, so might as well use __call
     * @param string $name
     * @param array $arguments
     * @return void
     */
    public function __call(string $name, array $arguments = [])
    {
        if (method_exists($this->fieldsBuilder, $name)) {
            // check if we have more than 1 arg. if not, set the default blank array so we can merge.
            if (count($arguments) == 1) {
                $arguments[1] = [];
            }
            $argKey = count($arguments) - 1;
            // fix name
            $arguments[$argKey] = array_merge(['name' => $this->generateKey($arguments[0])], ($arguments[$argKey] ?? []));

            return $this->fieldsBuilder->$name(...$arguments)
                ->setCustomKey('field_' . $this->generateKey($this->blockKey . '_' . $arguments[0]));
        } elseif (in_array($name, ['endGroup', 'end', 'endRepeater', 'endFlexibleContent'], true)) {
            // Group terminators are no-ops on the root FieldsBuilder, which has no
            // group-context tracking. Blocks call these to close addGroup()/addRepeater()
            // sections for readability; swallow them silently instead of logging.
            return $this;
        } else {
            ErrorLog::pretty("FieldsBuilder->$name does not exist, called in AcfBlockFields");
        }
    }
    public function build(): array
    {
        return $this->fieldsBuilder->build();
    }
}
