<?php

namespace ProudNerds\Plugins;

use GFFormsModel;
use ProudNerds\Helpers\User;
use ProudNerds\Trait\Initializable;
use StoutLogic\AcfBuilder\FieldNameCollisionException;
use StoutLogic\AcfBuilder\FieldsBuilder;

/**
 * Class LocalACF
 */
class LocalACF
{
    use Initializable;

    /**
     * LocalACF constructor.
     * @throws FieldNameCollisionException
     */
    public function __construct()
    {
        if (class_exists('acf')) {
            $this->addFilters();
            $this->optionPages();
            $this->hideACFMenu();
        }
    }

    /**
     * Registers custom fields using FieldsBuilder class.
     *
     * Set ACF fields according to: https://github.com/StoutLogic/acf-builder
     *
     * @param FieldsBuilder $fields
     *
     * @return FieldsBuilder
     * @throws FieldNameCollisionException
     * @see https://github.com/StoutLogic/acf-builder/wiki
     * @see https://github.com/Log1x/acf-builder-cheatsheet
     */
    public function registerSecurityOptions(FieldsBuilder $fields): FieldsBuilder
    {
        $fields->setGroupConfig('title', 'Beveiliging');

        $repeater = $fields->addRepeater('allowed_ips', [
            'label' => 'Toegestane IP-adressen',
            'layout' => 'table',
            'button_label' => 'Voeg IP-adres toe',
            'instructions' => __('Voeg hier IP-adressen toe die de login pagina mogen omzeilen.', 'proudnerds'),
        ]);

        $repeater
            ->addText('description', [
                'label' => __('Beschrijving', 'proudnerds'),
                'instructions' => __('Beschrijf de herkomst van het IP-adres', 'proudnerds'),
            ])
            ->addText('ip', [
                'label' => __('IP-adres', 'proudnerds'),
                'instructions' => __('Vul hier het IP-adres in', 'proudnerds'),
            ]);


        $repeater->endRepeater();

        return $fields;
    }

    /**
     * Registers custom fields using FieldsBuilder class.
     *
     * Set ACF fields according to: https://github.com/StoutLogic/acf-builder
     *
     * @param FieldsBuilder $fields
     *
     * @return FieldsBuilder
     * @throws FieldNameCollisionException
     * @see https://github.com/StoutLogic/acf-builder/wiki
     * @see https://github.com/Log1x/acf-builder-cheatsheet
     */
    public function registerThemeOptions(FieldsBuilder $fields): FieldsBuilder
    {
        // Footer fields
        $contact = new FieldsBuilder('contact');

        $contact->addText('contact_title', [
            'label' => __('Contact tekst', 'proudnerds'),
            'default_value' => __('Contactgegevens', 'proudnerds'),
        ]);

        $contact->addText('phone', [
            'label' =>  __('Telefoonnummer', 'proudnerds'),
            'default_value' => '(070) 376 58 47',
        ]);

        $contact->addText('mail', [
            'label' => __('E-mailadres', 'proudnerds'),
            'default_value' => 'info.sbcm@caop.nl',
        ]);

        // 404 page
        $errorPage = new FieldsBuilder('error_page');

        $errorPage->addText('title', [
            'label' =>  __('Titel', 'proudnerds'),
            'default_value' => '404',
        ]);
        $errorPage->addText('subtitle', [
            'label' => __('Subtitel', 'proudnerds'),
            'default_value' => __('Pagina niet gevonden', 'proudnerds'),
        ]);

        $errorPage->addWysiwyg('content', [
            'label' => __('Content', 'proudnerds'),
            'default_value' => __('Ga terug naar de <a href="/">homepagina</a>', 'proudnerds'),
        ]);

        // Social Media fields
        $social = new FieldsBuilder('social');

        $social->addLink('link_linkedin', [
            'label' => 'LinkedIn',
        ]);

        $social->addLink('link_facebook', [
            'label' => 'Facebook',
        ]);

        $social->addLink('link_twitter', [
            'label' => 'Twitter / X',
        ]);

        $social->addLink('link_instagram', [
            'label' => 'Instagram',
        ]);

        // PasswordPage
        $passwordPage = new FieldsBuilder('password_page');

        $passwordPage->addWysiwyg('content', [
            'label' => __('Informatie tekst', 'proudnerds'),
            'instructions' => __('Tekst die boven het wachtwoord veld voor een beveiligde pagina wordt getoond.', 'proudnerds'),
        ]);

        // Add all above fields as a tab to the theme options
        $placement = ['placement' => 'left'];

        $fields->addTab('Contact', $placement)->addGroup('contact', ['label' => 'Alle velden voor contactgegevens'])->addFields($contact); // NOSONAR
        $fields->addTab('Social Media', $placement)->addGroup('social', ['label' => 'Alle velden voor Social Media'])->addFields($social); // NOSONAR
        $fields->addTab('404 pagina', $placement)->addGroup('error_page', ['label' => 'Alle velden voor de 404 pagina'])->addFields($errorPage); // NOSONAR
        $fields->addTab('Beveiligde pagina\'s', $placement)->addGroup('password_page', ['label' => 'Alle velden voor wachtwoord beveiligde pagina\'s'])->addFields($passwordPage); // NOSONAR

        return $fields;
    }

    /**
     * Fills ACF select field with icons.
     *
     * @param array $field
     *
     * @return array
     */
    public function acfLoadIcons(array $field): array
    {
        $icons = [];
        $files = scandir(get_template_directory() . '/assets/icons/');

        foreach ($files as $file) {
            if (str_contains($file, '.svg')) {
                $icon = str_replace('.svg', '', $file);
                $icons[$icon] = ucfirst(str_replace('-', ' ', $icon));
            }
        }
        $field['choices'] = $icons;

        return $field;
    }

    /**
     * Fills ACF select field with Gravity Forms.
     *
     * @param array $field
     *
     * @return array
     */
    public function acfLoadGravityForms(array $field): array
    {
        if (class_exists('GFFormsModel')) {
            $choices = [];
            foreach (GFFormsModel::get_forms() as $form) {
                $choices[$form->id] = $form->title;
            }
            $field['choices'] = $choices;
        }

        return $field;
    }

    /**
     * Hide ACF menu for all users except the ones in the $allowedUsers array.
     *
     * @return void
     */
    private function hideACFMenu(): void
    {
        add_filter('acf/settings/show_admin', fn () => User::isProudNerdsAdmin());
    }

    /**
     * Filters.
     *
     * @return void
     */
    private function addFilters(): void
    {
        add_filter('acf/load_field/name=icon', [$this, 'acfLoadIcons'], 10, 1);
        add_filter('acf/load_field/name=gravityforms', [$this, 'acfLoadGravityForms'], 10, 1);
    }

    /**
     * Add theme option pages.
     *
     * @return void
     * @throws FieldNameCollisionException
     */
    private function optionPages(): void
    {
        $themeOptions = acf_add_options_page([
            'page_title' => __('Thema opties', 'proudnerds'),
            'menu_title' => __('Thema', 'proudnerds'),
            'menu_slug' => 'theme-options',
            'capability' => 'edit_posts',
            'post_id' => 'theme-options',
            'icon_url' => 'dashicons-admin-settings',
            'position' => 60,
            'redirect'    => !User::isProudNerdsAdmin(),
        ]);

        if (User::isProudNerdsAdmin()) {
            acf_add_options_sub_page([
                'page_title' => __('Beveiliging', 'proudnerds'),
                'menu_title' => __('Beveiliging', 'proudnerds'),
                'parent_slug' => $themeOptions['menu_slug'],
            ]);
        }

        /**
         * Register ACF fields
         */
        $themeOptions = $this->registerThemeOptions(\ProudNerds\Helpers\FieldsBuilder::getInstance(\ProudNerds\Helpers\FieldsBuilder::THEME_OPTIONS));
        $securityOptions = $this->registerSecurityOptions(\ProudNerds\Helpers\FieldsBuilder::getInstance('security'));

        add_action('acf/init', function () use ($themeOptions, $securityOptions) {
            $themeOptions->setLocation('options_page', '==', \ProudNerds\Helpers\FieldsBuilder::THEME_OPTIONS);
            acf_add_local_field_group($themeOptions->build());

            $securityOptions->setLocation('options_page', '==', 'acf-options-beveiliging');
            acf_add_local_field_group($securityOptions->build());
        }, 1000);
    }
}
