<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

use Soft_Tehnica\Freya_Sync_Service\STUtils\STView;

class SettingsPage
{
    public const PAGE = 'fs-setting-admin';

    /**
     * Holds the values to be used in the fields callbacks
     */
    private array $options;

    /**
     * Start up
     */
    public function __construct()
    {
        $this->init();
    }

    /**
     * Add options page
     */
    public function add_plugin_page(): void
    {
        wp_enqueue_style('fss_settings', fsPluginUrl . 'assets/css/settings.css', 'fsStyle');
        add_menu_page(
            'Freya Sync',
            'Freya Sync',
            'manage_options',
            self::PAGE,
            array($this, 'create_admin_page'),
            'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgdmlld0JveD0iMCAwIDc5LjMzIDkxLjYiCiAgIHZlcnNpb249IjEuMSIKICAgaWQ9InN2ZzM2IgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxkZWZzCiAgICAgaWQ9ImRlZnMzMCI+CiAgICA8c3R5bGUKICAgICAgIGlkPSJzdHlsZTIxIj4uY2xzLTF7ZmlsbDp1cmwoI2xpbmVhci1ncmFkaWVudCk7fTwvc3R5bGU+CiAgICA8bGluZWFyR3JhZGllbnQKICAgICAgIGlkPSJsaW5lYXItZ3JhZGllbnQiCiAgICAgICB4MT0iMzkuNjciCiAgICAgICB5MT0iLTEuNCIKICAgICAgIHgyPSIzOS42NyIKICAgICAgIHkyPSI5Ni4yNiIKICAgICAgIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KICAgICAgPHN0b3AKICAgICAgICAgb2Zmc2V0PSIwLjAxIgogICAgICAgICBzdG9wLWNvbG9yPSIjNGFhZmFjIgogICAgICAgICBpZD0ic3RvcDIzIiAvPgogICAgICA8c3RvcAogICAgICAgICBvZmZzZXQ9IjAuNSIKICAgICAgICAgc3RvcC1jb2xvcj0iIzAwOThhYyIKICAgICAgICAgaWQ9InN0b3AyNSIgLz4KICAgICAgPHN0b3AKICAgICAgICAgb2Zmc2V0PSIwLjk5IgogICAgICAgICBzdG9wLWNvbG9yPSIjMDA2YTkwIgogICAgICAgICBpZD0ic3RvcDI3IiAvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICA8L2RlZnM+CiAgPGcKICAgICBpZD0iTGF5ZXJfMiIKICAgICBkYXRhLW5hbWU9IkxheWVyIDIiPgogICAgPGcKICAgICAgIGlkPSJMYXllcl8xLTIiCiAgICAgICBkYXRhLW5hbWU9IkxheWVyIDEiPgogICAgICA8cG9seWdvbgogICAgICAgICBjbGFzcz0iY2xzLTEiCiAgICAgICAgIHBvaW50cz0iMzkuNjYgMCAwIDIyLjkgMCA2OC43IDExLjQ2IDYyLjA4IDExLjQ2IDI5LjUyIDExLjQ3IDI5LjUxIDM5Ljc1IDQ1LjggNDkuMjEgNDAuMzMgMjEgMjQuMDEgMzkuNjYgMTMuMjMgNjcuODcgMjkuNTIgNjcuODcgNjIuMDggMzkuNjYgNzguMzcgMjEuODkgNjguMTEgMTAuNDQgNzQuNzMgMzkuNjYgOTEuNiA3OS4zMyA2OC43IDc5LjMzIDIyLjkgMzkuNjYgMCIKICAgICAgICAgaWQ9InBvbHlnb24zMiIKICAgICAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZiIgLz4KICAgIDwvZz4KICA8L2c+Cjwvc3ZnPgo=', // don't even ask :)
        );
    }

    /**
     * Options page callback
     */
    public function create_admin_page(): void
    {
        if (!get_option('fs_option_settings')) {
            $this->options = [];
        } else {
            $this->options = get_option('fs_option_settings');
        }
        echo STView::render('settings-form');
    }

    /**
     * Register and add settings
     */
    public function page_init(): void
    {
        register_setting(
            'fs_option_group', // Option group
            'fs_option_settings', // Option name
            array($this, 'sanitize') // Sanitize
        );

        add_settings_section(
            'fs_setting_section_id', // ID
            'Setări sincronizare', // Title
            array($this, 'print_section_info'), // Callback
            self::PAGE // Page
        );

        // Fields list
        add_settings_field(
            'fsCompanyUid', // ID
            'UID Companie', // Title
            array($this, 'companyUidFieldCb'), // Callback
            'fs-setting-admin', // Page
            'fs_setting_section_id' // Section
        );

        add_settings_field(
            'fsDefaultLocationUid', // ID
            'UID Locație Default', // Title
            array($this, 'fsDefaultLocationUidFieldCb'), // Callback
            'fs-setting-admin', // Page
            'fs_setting_section_id' // Section
        );

        add_settings_field(
            'fsServiceUrl',
            'URL API',
            array($this, 'serviceUrlFieldCb'),
            'fs-setting-admin',
            'fs_setting_section_id'
        );

        add_settings_field(
            'fsNoPolygons',
            'Compania nu are poligoane',
            array($this, 'fsNoPolygonsCb'),
            'fs-setting-admin',
            'fs_setting_section_id'
        );

        add_settings_field(
            'fsCountyRestriction',
            'Restricționați adresele la un singur județ',
            array($this, 'fsCountyRestrictionCb'),
            'fs-setting-admin',
            'fs_setting_section_id'
        );

        add_settings_field(
            'fsNoAddressFoundMessage',
            'Mesaj în cazul în care adresa nu a putut fi identificată',
            array($this, 'fsNoAddressFoundMessageCb'),
            'fs-setting-admin',
            'fs_setting_section_id'
        );

        add_settings_field(
            'fsIsRunningOnLandingPageInstance',
            'Există instanță de landing page',
            array($this, 'fsIsRunningOnLandingPageInstanceFieldCb'),
            'fs-setting-admin',
            'fs_setting_section_id'
        );

        add_settings_field(
            'fsEnableMultiSubdomain',
            'Activează redirecționarea către alte subdomenii',
            array($this, 'fsEnableMultiSubdomainFieldCb'),
            'fs-setting-admin',
            'fs_setting_section_id'
        );

        add_settings_field(
            'fsShowAllProductsNoLocation',
            'Afișează toate produsele din magazin dacă utilizatorul nu a selectat o locație',
            function () {
                $checked = isset($this->options['fsShowAllProductsNoLocation'])
                    && (int)$this->options['fsShowAllProductsNoLocation'] === 1
                    ? 'checked'
                    : '';
?>
            <input id="fsShowAllProductsNoLocation"
                name="fs_option_settings[fsShowAllProductsNoLocation]"
                class="fs-setting"
                <?php echo $checked ?>
                value="1"
                type="checkbox" />
        <?php
            },
            'fs-setting-admin',
            'fs_setting_section_id'
        );

        add_settings_field(
            'fsHideModalDismiss',
            'Dezactivează butonul de ascundere modală',
            function () {
                $checked = isset($this->options['fsHideModalDismiss'])
                    && (int)$this->options['fsHideModalDismiss'] === 1
                    ? 'checked'
                    : '';
        ?>
            <input id="fsHideModalDismiss"
                name="fs_option_settings[fsHideModalDismiss]"
                class="fs-setting"
                <?php echo $checked ?>
                value="1"
                type="checkbox" />
<?php
            },
            self::PAGE,
            'fs_setting_section_id'
        );

        add_settings_field(
            'fsAddressRequestOnPages',
            'Paginile pe care se va cere adresa',
            array($this, 'fsAddressRequestOnPagesFieldCb'),
            'fs-setting-admin',
            'fs_setting_section_id'
        );
    }

    /**
     * Sanitize each setting field as needed
     *
     * @param array $input Contains all settings fields as array keys
     */
    public function sanitize(array $input): array
    {
        $new_input = [];

        if (isset($input['fsDefaultLocationUid'])) {
            $new_input['fsDefaultLocationUid'] = sanitize_text_field($input['fsDefaultLocationUid']);
        }
        if (isset($input['fsCompanyUid'])) {
            $new_input['fsCompanyUid'] = sanitize_text_field($input['fsCompanyUid']);
        }
        if (isset($input['fsServiceUrl'])) {
            $new_input['fsServiceUrl'] = sanitize_text_field($input['fsServiceUrl']);
        }
        if (isset($input['fsCountyRestriction'])) {
            $new_input['fsCountyRestriction'] = sanitize_text_field($input['fsCountyRestriction']);
        }
        if (isset($input['fsNoAddressFoundMessage'])) {
            $new_input['fsNoAddressFoundMessage'] = sanitize_text_field($input['fsNoAddressFoundMessage']);
        }
        if (isset($input['fsAddressRequestOnPages'])) {
            $new_input['fsAddressRequestOnPages'] = $input['fsAddressRequestOnPages'];
        }
        if (isset($input['fsIsRunningOnLandingPageInstance'])) {
            $new_input['fsIsRunningOnLandingPageInstance'] = ((int)$input['fsIsRunningOnLandingPageInstance'] === 1) ? 1 : 0;
        }
        if (isset($input['fsEnableMultiSubdomain'])) {
            $new_input['fsEnableMultiSubdomain'] = ((int)$input['fsEnableMultiSubdomain'] === 1) ? 1 : 0;
        }
        if (isset($input['fsNoPolygons'])) {
            $new_input['fsNoPolygons'] = ((int)$input['fsNoPolygons'] === 1) ? 1 : 0;
        }
        if (isset($input['fsHideModalDismiss'])) {
            $new_input['fsHideModalDismiss'] = ((int)$input['fsHideModalDismiss'] === 1) ? 1 : 0;
        }
        if (isset($input['fsShowAllProductsNoLocation'])) {
            $new_input['fsShowAllProductsNoLocation'] = ($input['fsShowAllProductsNoLocation']) === "1" ? 1 : 0;
        }

        return $new_input;
    }

    /**
     * Print the Section text
     */
    public function print_section_info(): void
    {
        echo '<h4>Completați informațiile de mai jos:</h4>';
    }

    /**
     * Get the settings option array and print one of its values
     */
    public function fsNoAddressFoundMessageCb(): void
    {
        printf(
            '<textarea class="fs-setting" id="fsNoAddressFoundMessage" name="fs_option_settings[fsNoAddressFoundMessage]">%s</textarea>',
            isset($this->options['fsNoAddressFoundMessage']) ? esc_attr($this->options['fsNoAddressFoundMessage']) : ''
        );
    }

    public function companyUidFieldCb(): void
    {
        printf(
            '<input type="text" class="fs-setting" id="fsCompanyUid" name="fs_option_settings[fsCompanyUid]" value="%s" />',
            isset($this->options['fsCompanyUid']) ? esc_attr($this->options['fsCompanyUid']) : ''
        );
    }

    public function fsDefaultLocationUidFieldCb(): void
    {
        printf(
            '<input type="text" class="fs-setting" id="fsDefaultLocationUid" name="fs_option_settings[fsDefaultLocationUid]" value="%s" />',
            isset($this->options['fsDefaultLocationUid']) ? esc_attr($this->options['fsDefaultLocationUid']) : ''
        );
    }

    public function serviceUrlFieldCb(): void
    {
        printf(
            '<input type="text" class="fs-setting code" id="fsServiceUrl" name="fs_option_settings[fsServiceUrl]" value="%s"/>',
            isset($this->options['fsServiceUrl']) ? esc_attr($this->options['fsServiceUrl']) : ''
        );
    }

    public function fsCountyRestrictionCb(): void
    {
        printf(
            '<input type="text" class="fs-setting" id="fsCountyRestriction" name="fs_option_settings[fsCountyRestriction]" value="%s"/>',
            isset($this->options['fsCountyRestriction']) ? esc_attr($this->options['fsCountyRestriction']) : ''
        );
    }

    public function fsIsRunningOnLandingPageInstanceFieldCb(): void
    {
        $checked = (isset($this->options['fsIsRunningOnLandingPageInstance'])
            && (int)$this->options['fsIsRunningOnLandingPageInstance'] === 1) ? 'checked' : '';
        echo '<input type="checkbox" class="fs-setting" id="fsIsRunningOnLandingPageInstance" name="fs_option_settings[fsIsRunningOnLandingPageInstance]" value="1" ' . $checked . ' />';
    }

    public function fsEnableMultiSubdomainFieldCb(): void
    {
        $checked = (isset($this->options['fsEnableMultiSubdomain']) && (int)$this->options['fsEnableMultiSubdomain'] === 1) ? 'checked' : '';
        echo '<input type="checkbox" class="fs-setting" id="fsEnableMultiSubdomain" name="fs_option_settings[fsEnableMultiSubdomain]" value="1" ' . $checked . ' />';
    }

    public function fsAddressRequestOnPagesFieldCb(): void
    {
        // Add your filter input here. Make sure the input name matches the $_GET value you are checking above.
        echo '<select multiple="multiple" class="fs-setting" name="fs_option_settings[fsAddressRequestOnPages][]" style="min-height: 10rem">';

        $values = get_pages();

        foreach ($values as $page) {
            if (!isset($this->options['fsAddressRequestOnPages'])) {
                $checked = false;
            } else {
                $checked = in_array(
                    $page->ID,
                    $this->options['fsAddressRequestOnPages']
                ) ? ' selected="selected" ' : '';
            }
            echo '<option value="' . $page->ID . '" ' . $checked . '>' . $page->post_title . '</option>';
        }
        echo '</select>';
    }

    public function fsNoPolygonsCb(): void
    {
        $checked = (isset($this->options['fsNoPolygons']) && (int)$this->options['fsNoPolygons'] === 1) ? 'checked' : '';
        echo '<input type="checkbox" class="fs-setting" id="fsNoPolygons" name="fs_option_settings[fsNoPolygons][]" value="0" ' . $checked . ' />';
    }

    public function get_settings(): void
    {
        check_ajax_referer('wp_rest', 'nonce');
        $options = get_option('fs_option_settings');
        $options['fsServiceUrl'] = fsServiceUrl(true);
        wp_send_json_success($options, 200);
    }

    public function init(): void
    {
        add_action('admin_menu', array($this, 'add_plugin_page'));
        add_action('admin_init', array($this, 'page_init'));
        add_action('wp_ajax_freya_sync_service_get_settings', array($this, 'get_settings'));
        add_action('wp_ajax_nopriv_freya_sync_service_get_settings', array($this, 'get_settings'));
    }
}
