<?php

namespace Webien\Elementor\Extensions;

use Elementor\Element_Base;

class ColumnWidth
{
    function __construct()
    {
        $this->register_hooks();
    }


    private function register_hooks()
    {
        if (is_admin()) {
            add_action( 'elementor/element/before_section_end', [ $this, 'register_controls' ], 10, 3 );
        }
        add_action('elementor/frontend/column/before_render', [$this, 'add_column_attributes'], 10, 1);
        add_action('elementor/frontend/container/before_render', [$this, 'add_column_attributes'], 20, 1);
    }


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

        $sections = [
            'layout',
            'layout_container',
            'section_layout_container',
        ];

        $elements = [
            'column',
            'container',
        ];

        $element_name = $element->get_name();

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

        if(in_array( $element_name, $elements )) {
            $element->add_responsive_control(
                'webien_column_width',
                [
                    'label' => __( 'Kolumnbredd', 'webien' ),
                    'type' => \Elementor\Controls_Manager::TEXT,
                    'label_block' => true,
                    'description' => 'Ex: 100px, 20%, calc(100% - 100px)',
                    'selectors' => [
                        '{{WRAPPER}}' => 'width: {{VALUE}}',
                    ],
                ]
            );
        }

    }

    function add_column_attributes(Element_Base $element) {
        $settings = $element->get_settings();
        if (
            !empty($settings['webien_column_width']) ||
            !empty($settings['webien_column_width_tablet']) ||
            !empty($settings['webien_column_width_mobile'])
        ) {
            $breakpoints = \Elementor\Plugin::$instance->breakpoints->get_breakpoints();

            $responsive = [
                'desktop' => $settings['webien_column_width'] ?? false,
                'tablet' => $settings['webien_column_width_tablet'] ?? false,
                'mobile' => $settings['webien_column_width_mobile'] ?? false,
            ];

            $css = '<style>';
            foreach ($responsive as $key => $val){
                if($val){
                    $css .= $key !== 'desktop' ? '@media screen and (max-width: '.$breakpoints[$key]->get_value().'px) {' : '';
                    $css .= '.elementor-element-'.$element->get_id().'{';
                    $css .= 'width: '.$val.' !important;';
                    $css .= 'flex-shrink: 0;';
                    $css .= '}';
                    $css .= $key !== 'desktop' ? '}' : '';
                }
            }
            $css .= '</style>';

            echo $css;
        }
    }
}
