<?php

namespace Sibs\Stargate\Admin;

use Sibs\Stargate\Config\SibsConfig;

defined('ABSPATH') || exit;

class SibsStyleSettings
{
    /**
     * Page Hook.
     */
    private string $page_hook;

    /**
     * Constructor.
     */
    public function __construct()
    {
        add_action('admin_menu', [$this, 'registerMenu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
    }

    /**
     * To Array.
     */
    public static function __toArray(): array
    {
        $layout = SibsConfig::getStyleOption('layout') ?? 'default';
        $theme = SibsConfig::getStyleOption('theme') ?? 'default';
        $layout_primary = SibsConfig::getStyleOption('layout_primary') ?? '';
        $layout_surface = SibsConfig::getStyleOption('layout_surface') ?? '';
        $layout_text_color = SibsConfig::getStyleOption('layout_text_color') ?? '';
        $layout_header_color = SibsConfig::getStyleOption('layout_header_color') ?? '';

        $theme_secondary = SibsConfig::getStyleOption('theme_secondary_color') ?? '';
        $theme_background = SibsConfig::getStyleOption('theme_background_color') ?? '';
        $theme_border = SibsConfig::getStyleOption('theme_border_color') ?? '';
        $theme_header = SibsConfig::getStyleOption('theme_header_text') ?? '';

        $font = SibsConfig::getStyleOption('font') ?? '';

        return [
            'layout' => $layout,
            'theme' => $theme,
            'color' => [
                'primary' => $layout_primary,
                'secondary' => $theme_secondary,
                'border' => $theme_border,
                'surface' => $layout_surface,
                'header' => [
                    'text' => $theme_header,
                    'background' => $layout_header_color,
                ],
                'body' => [
                    'text' => $layout_text_color,
                    'background' => $theme_background,
                ],
                'font' => $font,
            ],
        ];
    }

    /**
     * Register Menu.
     */
    public function registerMenu()
    {
        $this->page_hook = add_submenu_page(
            'woocommerce',
            __('SIBS Style', 'sibs-woo-stg'),
            __('SIBS Style', 'sibs-woo-stg'),
            'manage_woocommerce',
            'sibs_style',
            [$this, 'renderPage'],
            4
        );
    }

    /**
     * Enqueue Assets.
     *
     * @param mixed $hook
     */
    public function enqueueAssets($hook)
    {
        if ($hook !== $this->page_hook) {
            return;
        }

        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');

        wp_add_inline_script('wp-color-picker', '
            jQuery(document).ready(function($){
                $(".colorpick").wpColorPicker();
            });
        ');

        wp_enqueue_style('sibs_admin_form_payment_style', constant('SIBS_PLUGIN_URL').'assets/css/sibs-form-payment-style.css', []);
    }

    /**
     * Save Data Style Settings.
     *
     * @param mixed $post
     */
    public function saveDataStyleSettings($post)
    {
        SibsConfig::setStyleOption('layout', $post[SibsConfig::SIBS_STYLE_CONFIG.'_layout']);
        SibsConfig::setStyleOption('layout_primary', $post[SibsConfig::SIBS_STYLE_CONFIG.'_layout_primary']);
        SibsConfig::setStyleOption('layout_surface', $post[SibsConfig::SIBS_STYLE_CONFIG.'_layout_surface']);
        SibsConfig::setStyleOption('layout_text_color', $post[SibsConfig::SIBS_STYLE_CONFIG.'_layout_text_color']);
        SibsConfig::setStyleOption('layout_header_color', $post[SibsConfig::SIBS_STYLE_CONFIG.'_layout_header_color']);
        SibsConfig::setStyleOption('theme', $post[SibsConfig::SIBS_STYLE_CONFIG.'_theme']);
        SibsConfig::setStyleOption('theme_secondary_color', $post[SibsConfig::SIBS_STYLE_CONFIG.'_theme_secondary_color']);
        SibsConfig::setStyleOption('theme_background_color', $post[SibsConfig::SIBS_STYLE_CONFIG.'_theme_background_color']);
        SibsConfig::setStyleOption('theme_border_color', $post[SibsConfig::SIBS_STYLE_CONFIG.'_theme_border_color']);
        SibsConfig::setStyleOption('theme_header_text', $post[SibsConfig::SIBS_STYLE_CONFIG.'_theme_header_text']);
        SibsConfig::setStyleOption('font', $post[SibsConfig::SIBS_STYLE_CONFIG.'_font']);

        return true;
    }

    /**
     * Render Page.
     */
    public function renderPage()
    {
        if (!current_user_can('manage_woocommerce')) {
            return;
        }

        $saved = $this->handleFormSubmit();

        ?>
        <div class="wrap">
            <?php $this->renderHeader(); ?>
            <?php $this->renderSuccessMessage($saved); ?>

            <form method="POST">
                <?php wp_nonce_field('sibs_style_save', 'sibs_style_nonce'); ?>

                <table class="form-table">
                    <tbody>

                    <?php $this->renderSelect('layout', __('Layout', 'sibs-woo-stg'), $this->getLayouts()); ?>

                    <?php $this->renderColorField('layout_primary', __('Button Color', 'sibs-woo-stg')); ?>
                    <?php $this->renderColorField('layout_surface', __('Surface Color', 'sibs-woo-stg')); ?>
                    <?php $this->renderColorField('layout_text_color', __('Text Color', 'sibs-woo-stg')); ?>
                    <?php $this->renderColorField('layout_header_color', __('Header Color', 'sibs-woo-stg')); ?>

                    <?php $this->renderSelect('theme', __('Theme', 'sibs-woo-stg'), $this->getThemes()); ?>

                    <?php $this->renderColorField('theme_secondary_color', __('Secondary', 'sibs-woo-stg')); ?>
                    <?php $this->renderColorField('theme_background_color', __('Background', 'sibs-woo-stg')); ?>
                    <?php $this->renderColorField('theme_border_color', __('Border', 'sibs-woo-stg')); ?>
                    <?php $this->renderColorField('theme_header_text', __('Header Text', 'sibs-woo-stg')); ?>

                    <?php $this->renderTextField('font', __('Font Family', 'sibs-woo-stg')); ?>

                    </tbody>
                </table>

                <p>
                    <button class="button button-primary" type="submit" name="sibs_save_style_settings">
                        <?php echo __('Save Changes', 'sibs-woo-stg'); ?>
                    </button>
                </p>
            </form>
        </div>
        <?php
    }

    /**
     * Render Header.
     */
    private function renderHeader()
    {
        ?>
        <div class="row align-items-center mb-4">
            <div class="col-md-2 col-12 text-center text-md-start">
                <img src="<?php echo esc_attr(plugins_url('sibs-woo-stg/assets/images/logo.png')); ?>" class="img-fluid" style="max-height:60px;">
            </div>
            <div class="col-md-10 col-12 text-center text-md-start">
                <h2><?php echo __('Style Settings', 'sibs-woo-stg'); ?></h2>
            </div>
        </div>
        <?php
    }

    /**
     * Render Success Message.
     *
     * @param mixed $saved
     */
    private function renderSuccessMessage($saved)
    {
        if (isset($_POST['sibs_save']) && $saved) {
            ?>
            <div class="notice notice-success">
                <p><strong><?php echo __('Settings saved', 'sibs-woo-stg'); ?></strong></p>
            </div>
            <?php
        }
    }

    /**
     * Handle Form Submit.
     */
    private function handleFormSubmit()
    {
        if (
            !isset($_POST['sibs_save_style_settings'])
            || !isset($_POST['sibs_style_nonce'])
            || !wp_verify_nonce($_POST['sibs_style_nonce'], 'sibs_style_save')
        ) {
            return false;
        }

        $sanitized = [];

        foreach ($_POST as $key => $value) {
            if (0 === strpos($key, SibsConfig::SIBS_STYLE_CONFIG)) {
                $sanitized[$key] = sanitize_text_field($value);
            }
        }

        return $this->saveDataStyleSettings($sanitized);
    }

    /**
     * Get Layouts.
     */
    private function getLayouts()
    {
        return [
            'default' => __('Default', 'sibs-woo-stg'),
            'list' => __('List', 'sibs-woo-stg'),
            'accordion' => __('Accordion', 'sibs-woo-stg'),
        ];
    }

    /**
     * Get Themes.
     */
    private function getThemes()
    {
        return [
            'default' => __('Default', 'sibs-woo-stg'),
            'light' => __('Light', 'sibs-woo-stg'),
            'gray' => __('Gray', 'sibs-woo-stg'),
            'dark' => __('Dark', 'sibs-woo-stg'),
        ];
    }

    /**
     * Render Select.
     *
     * @param mixed $key
     * @param mixed $label
     * @param mixed $options
     */
    private function renderSelect($key, $label, $options)
    {
        $name = SibsConfig::SIBS_STYLE_CONFIG.'_'.$key;
        $current = SibsConfig::getStyleOption($key);
        ?>
        <tr>
            <th><label for="<?php echo esc_attr($name); ?>"><?php echo esc_html($label); ?></label></th>
            <td>
                <select name="<?php echo esc_attr($name); ?>" class="regular-text">
                    <?php foreach ($options as $value => $text) { ?>
                        <option value="<?php echo esc_attr($value); ?>" <?php selected($current, $value); ?>>
                            <?php echo esc_html($text); ?>
                        </option>
                    <?php } ?>
                </select>
            </td>
        </tr>
        <?php
    }

    /**
     * Render Color Field.
     *
     * @param mixed $key
     * @param mixed $label
     */
    private function renderColorField($key, $label)
    {
        $name = SibsConfig::SIBS_STYLE_CONFIG.'_'.$key;
        ?>
        <tr>
            <th><label for="<?php echo esc_attr($name); ?>"><?php echo esc_html($label); ?></label></th>
            <td>
                <input class="regular-text colorpick"
                       type="text"
                       name="<?php echo esc_attr($name); ?>"
                       value="<?php echo esc_attr(SibsConfig::getStyleOption($key)); ?>" />
            </td>
        </tr>
        <?php
    }

    /**
     * Render Text Field.
     *
     * @param mixed $key
     * @param mixed $label
     */
    private function renderTextField($key, $label)
    {
        $name = SibsConfig::SIBS_STYLE_CONFIG.'_'.$key;
        ?>
        <tr>
            <th><label for="<?php echo esc_attr($name); ?>"><?php echo esc_html($label); ?></label></th>
            <td>
                <input class="regular-text"
                       type="text"
                       name="<?php echo esc_attr($name); ?>"
                       value="<?php echo esc_attr(SibsConfig::getStyleOption($key)); ?>" />
            </td>
        </tr>
        <?php
    }
}
