<?php

namespace Webien\Elementor\Extensions\Buttons;

use Elementor\Element_Base;

class Buttons
{
    public function __construct()
    {
        if (is_admin()) {
            // Add ACF on option page
            $this->addOptions();

            add_action('elementor/element/before_section_end', [$this, 'register_controls'], 10, 3);
            // In preview mode the frontend render action wont have any effect, so add classes through this hook instead
            add_filter('elementor/widget/render_content', [$this, 'update_button_markup_for_preview'], 10, 2);
        }

        add_action('wp_head', [$this, 'add_btn_css']);

        // This hook will add classes the proper way in frontend
        add_action('elementor/frontend/widget/before_render', [$this, 'beforeRender'], 10, 1);
        // Update Elementor editor JS content template to reflect editor changes
        add_filter('elementor/widget/print_template', [$this, 'change_button_js_template'], 10, 2);

    }


    public function register_controls($element, $section_id, $args)
    {

        $sections = [
            'section_button'
        ];

        if (!in_array($section_id, $sections)) {
            return;
        }

        // Remove standard dropdowns the interfers with our settings
        $element->remove_control('button_type');
        $element->remove_control('size');
        //$element->remove_control('selected_icon');
        $element->remove_control('icon_indent');

        $element->start_injection([
            'at' => 'before',
            'of' => 'align',
        ]);

        // List buttons created in option page
        $btns = $this->getButtons();

        $element->add_control(
            'webien_button_type',
            [
                'label' => __('Typ', 'webien'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => $btns,
                'default' => 'default',
                'selectors' => [

                ],
                'separator' => 'before',
            ]
        );
        $element->end_injection();


        // Link to parent check
        $element->start_injection([
            'at' => 'before',
            'of' => 'align',
        ]);

        $element->add_control(
            'link_to_parent',
            [
                'label' => esc_html__('Länka till förälder', 'webien'),
                'description' => esc_html__('Om förälder finns slår detta igenom.', 'webien'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'return_value' => 'yes',
                'default' => '',
            ]
        );
        $element->end_injection();

    }


    public function beforeRender(Element_Base $element)
    {


        if ('button' === $element->get_name()) {
            $settings = $element->get_settings();


            // -----------------------------------------//
            // BUTTON STYLES FROM ACF OPTIONS
            // -----------------------------------------//

            if (isset($settings['webien_button_type'])) {


                $render_arr = [
                    'class' => [
                        'webien-' . $this->cleanString($settings['webien_button_type']),
                    ],
                ];
                $element->add_render_attribute('_wrapper', $render_arr);

            }


            // -----------------------------------------//
            // LINK TO PARENT
            // -----------------------------------------//

            if (isset($settings['link_to_parent']) && $settings['link_to_parent'] === 'yes') {

                // First check that we actually have a parent
                global $post;
                $parent = wp_get_post_parent_id($post);
                if ($parent) {
                    $settings['link']['url'] = get_permalink($parent);
                    $element->set_settings('link', $settings['link']);
                }
            }
        }
        return $element;
    }

    function change_button_js_template($template, $widget)
    {
        if ('button' === $widget->get_name()) {
            //Update the default Elementor content template for Button instead of the original in /plugins/elementor/includes/widgets/traits/button-trait.php
            $new_template = file_get_contents(__DIR__ . '/preview-template.html', true);
            return $new_template;

        }
        return $template;
    }


    function update_button_markup_for_preview($widget_content, $widget)
    {

        if ('button' === $widget->get_name()) {
            $settings = $widget->get_settings();

            $widget_content = str_replace('elementor-button-wrapper', 'elementor-button-wrapper' . ' webien-' . $settings['webien_button_type'], $widget_content);
        }
        return $widget_content;
    }


    function getButtons()
    {

        // Load acf the manual way since acf is not loaded yet.
        $repeater = 'options_button_list';
        // init rows
        $btns = array();
        // repeater meta holds number of rows
        $count = intval(get_option($repeater) ?? 0);

        for ($i = 0; $i < $count; $i++) {
            // build row
            $btns[] = ['name' => get_option($repeater . '_' . $i . '_' . 'name')];
        }

        $arr = [];
        $arr['default'] = __('Standard', 'webien');

        if ($btns) {
            foreach ($btns as $btn) {
                $arr[$this->cleanString($btn['name'])] = $btn['name'];
            }
        }

        return $arr;

    }


    function addOptions()
    {
        // We include a exported ACF file, since ACF Builder has some problems with repeaters on option pages
        //include __DIR__ . '/acf/acf-export.php';
    }


    function add_btn_css()
    {

        // ACF Repeaters on option pages wont load as expected
        // Retrieve field from this loop instead until figure whats up..
        // https://support.advancedcustomfields.com/forums/topic/get_field-for-repeater-returning-string-instead-of-array/#post-131707

        // get repeater using get_post_meta()
        $repeater = 'options_button_list'; // name of repeater field
        $sub_fields = array(
            // holds names of all sub fields
            'name',
            'css_normal_mobile',
            'css_normal_desktop',
            'css_hover_mobile',
            'css_hover_desktop',
        );
        // init rows
        $rows = array();
        // repeater meta holds number of rows
        $count = intval(get_option($repeater));

        for ($i = 0; $i < $count; $i++) {
            // build row
            $row = array();
            foreach ($sub_fields as $sub_field) {
                $row[$sub_field] = get_option($repeater . '_' . $i . '_' . $sub_field);
            }
            $rows[] = $row;
        }


        $breakpoint = [
            'desktop' => 768,
        ];


        $style = '<style>';

        // Get general button styling
        $style .= '.elementor-button {' . get_option('options_css_button_general') . '}';
        $style .= '@media screen and (min-width: ' . $breakpoint['desktop'] . 'px) {';
        $style .= '.elementor-button {' . get_option('options_css_button_general_desktop') . '} }';


        // This wont work yet..
        //$rows = get_field('button_list', 'option');

        if ($rows) {

            foreach ($rows as $btn) {
                // Normal
                $style .= '.webien-' . $this->cleanString($btn['name']) . ' .elementor-button {';
                $style .= 'cursor: pointer;';
                $style .= $btn['css_normal_mobile'] ?? '';
                $style .= '}';
                // Normal desktop
                $style .= '@media screen and (min-width: ' . $breakpoint['desktop'] . 'px) {';
                $style .= '.webien-' . $this->cleanString($btn['name']) . ' .elementor-button {';
                $style .= $btn['css_normal_desktop'] ?? '';
                $style .= '}}';

                // Hover
                $style .= '.webien-' . $this->cleanString($btn['name']) . ' .elementor-button:hover,';
                $style .= '.webien-' . $this->cleanString($btn['name']) . ' .elementor-button:active,';
                $style .= '.webien-' . $this->cleanString($btn['name']) . ' .elementor-button:focus {';
                $style .= $btn['css_hover_mobile'] ?? '';
                $style .= '}';
                // Hover desktop
                $style .= '@media screen and (min-width: ' . $breakpoint['desktop'] . 'px) {';
                $style .= '.webien-' . $this->cleanString($btn['name']) . ' .elementor-button:hover,';
                $style .= '.webien-' . $this->cleanString($btn['name']) . ' .elementor-button:active,';
                $style .= '.webien-' . $this->cleanString($btn['name']) . ' .elementor-button:focus {';
                $style .= $btn['css_hover_desktop'] ?? '';
                $style .= '}}';
            }
        }

        $style .= '</style>';

        echo trim($style);

    }


    function cleanString($str)
    {
        $str = preg_replace('/[^A-Za-z0-9\-]/', '', $str);
        return strtolower($str);
    }

}

;