<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class ElementSell_Course_Image_Widget extends \Elementor\Widget_Base {

    public function get_name() {
        return 'elementsell_course_image';
    }

    public function get_title() {
        return __( 'Obrázek kurzu', 'platebni-formular' );
    }

    public function get_icon() {
        return function_exists( 'elementsell_get_course_image_widget_icon' )
            ? elementsell_get_course_image_widget_icon()
            : 'eicon-eye';
    }

    public function get_categories() {
        return [ 'basic' ];
    }

    public function get_keywords() {
        return [ 'kurz', 'role', 'obrázek', 'elementsell', 'přístup' ];
    }

    protected function register_controls() {
        $this->start_controls_section(
            'content_section',
            [
                'label' => __( 'Kurz', 'platebni-formular' ),
                'tab'   => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'image',
            [
                'label'   => __( 'Obrázek kurzu', 'platebni-formular' ),
                'type'    => \Elementor\Controls_Manager::MEDIA,
                'default' => [
                    'url' => \Elementor\Utils::get_placeholder_image_src(),
                ],
            ]
        );

        $this->add_control(
            'image_width',
            [
                'label'      => __( 'Šířka obrázku', 'platebni-formular' ),
                'type'       => \Elementor\Controls_Manager::SLIDER,
                'size_units' => [ 'px', '%' ],
                'range'      => [
                    'px' => [
                        'min'  => 120,
                        'max'  => 800,
                        'step' => 10,
                    ],
                    '%'  => [
                        'min'  => 20,
                        'max'  => 100,
                        'step' => 1,
                    ],
                ],
                'default'    => [
                    'unit' => 'px',
                    'size' => 560,
                ],
            ]
        );

        $this->add_control(
            'link',
            [
                'label'       => __( 'Odkaz, kam obrázek povede', 'platebni-formular' ),
                'type'        => \Elementor\Controls_Manager::URL,
                'description' => __( 'Při uložení stránky se cílové WP stránce automaticky nastaví viditelnost podle vybraných rolí.', 'platebni-formular' ),
                'default'     => [
                    'url' => '',
                ],
            ]
        );

        $this->add_control(
            'course_role',
            [
                'label'       => __( 'Viditelné pro role', 'platebni-formular' ),
                'type'        => \Elementor\Controls_Manager::SELECT2,
                'label_block' => true,
                'options'     => elementsell_get_role_select2_options(),
                'multiple'    => true,
                'tags'        => true,
            ]
        );

        $this->end_controls_section();
    }

    protected function render() {
        $settings        = $this->get_settings_for_display();
        $roles           = elementsell_get_course_roles_from_widget_settings( $settings );
        $is_admin_viewer = current_user_can( 'manage_options' );
        $is_editor       = elementsell_is_elementor_editor_render();
        $image           = $settings['image'] ?? [];
        $url             = isset( $image['url'] ) ? (string) $image['url'] : '';

        if ( $url === '' ) {
            if ( $is_editor || $is_admin_viewer ) {
                echo '<div class="elementsell-course-image elementsell-course-image--notice">Vyberte obrázek kurzu.</div>';
            }
            return;
        }

        if ( ! $is_editor && ! $is_admin_viewer ) {
            if ( empty( $roles ) || ! elementsell_current_user_has_any_role( $roles ) ) {
                return;
            }
        }

        $link        = $settings['link'] ?? [];
        $link_url    = isset( $link['url'] ) ? (string) $link['url'] : '';
        $is_external = ! empty( $link['is_external'] );
        $nofollow    = ! empty( $link['nofollow'] );

        $this->render_styles_once();

        $attrs = '';

        if ( $link_url !== '' ) {
            $attrs .= ' href="' . esc_url( $link_url ) . '"';

            if ( $is_external ) {
                $attrs .= ' target="_blank"';
            }

            if ( $nofollow ) {
                $attrs .= ' rel="nofollow"';
            }
        }

        $wrapper_class = 'elementsell-course-image';

        if ( $is_admin_viewer || $is_editor ) {
            $wrapper_class .= ' elementsell-course-image--admin';
        }

        $width_style = $this->get_image_width_style( $settings );

        $tag_open  = $link_url !== '' ? '<a class="elementsell-course-image__link"' . $attrs . '>' : '<div class="elementsell-course-image__link">';
        $tag_close = $link_url !== '' ? '</a>' : '</div>';
        $img_class = 'elementsell-course-image__img';

        if ( $is_admin_viewer || $is_editor ) {
            $img_class .= ' elementsell-course-image__img--admin';
        }
        ?>
        <div class="<?php echo esc_attr( $wrapper_class ); ?>"<?php echo $width_style !== '' ? ' style="' . esc_attr( $width_style ) . '"' : ''; ?>>
            <?php echo $tag_open; ?>
                <span class="elementsell-course-image__visual">
                    <img
                        class="<?php echo esc_attr( $img_class ); ?>"
                        src="<?php echo esc_url( $url ); ?>"
                        alt=""
                        loading="lazy"
                    >
                    <?php if ( ( $is_admin_viewer || $is_editor ) && ! empty( $roles ) ) : ?>
                        <span class="elementsell-course-image__admin-note">
                            <?php
                            printf(
                                /* translators: %s: comma-separated role slugs */
                                esc_html__( 'Viditelné pro: %s (náhled v editoru)', 'platebni-formular' ),
                                esc_html( implode( ', ', $roles ) )
                            );
                            ?>
                        </span>
                    <?php elseif ( ( $is_admin_viewer || $is_editor ) && empty( $roles ) ) : ?>
                        <span class="elementsell-course-image__admin-note">
                            <?php esc_html_e( 'Vyplňte alespoň jednu roli pro zobrazení na webu.', 'platebni-formular' ); ?>
                        </span>
                    <?php endif; ?>
                </span>
            <?php echo $tag_close; ?>
        </div>
        <?php
    }

    protected function content_template() {
        $placeholder = esc_url( \Elementor\Utils::get_placeholder_image_src() );
        ?>
        <#
        var image = settings.image || {};
        var imageUrl = image.url ? image.url : <?php echo wp_json_encode( $placeholder ); ?>;
        var link = settings.link || {};
        var linkUrl = link.url ? link.url : '';
        var roles = settings.course_role || [];
        if ( ! Array.isArray( roles ) ) {
            roles = roles ? [ roles ] : [];
        }
        var rolesLabel = roles.length ? roles.join( ', ' ) : '';
        var imageWidth = settings.image_width || {};
        var imageWidthUnit = imageWidth.unit ? imageWidth.unit : 'px';
        var imageWidthSize = imageWidth.size ? imageWidth.size : 560;
        var imageWidthValue = imageWidthUnit === '%'
            ? Math.min(100, Math.max(20, imageWidthSize)) + '%'
            : Math.min(800, Math.max(120, imageWidthSize)) + 'px';
        var imageWidthStyle = '--elementsell-course-image-width:' + imageWidthValue;
        #>
        <div class="elementsell-course-image elementsell-course-image--admin" style="{{{ imageWidthStyle }}}">
            <# if ( linkUrl ) { #>
                <a class="elementsell-course-image__link" href="{{{ linkUrl }}}"<# if ( link.is_external ) { #> target="_blank"<# } #><# if ( link.nofollow ) { #> rel="nofollow"<# } #>>
            <# } else { #>
                <div class="elementsell-course-image__link">
            <# } #>
                <span class="elementsell-course-image__visual">
                    <img class="elementsell-course-image__img elementsell-course-image__img--admin" src="{{{ imageUrl }}}" alt="" loading="lazy">
                    <# if ( rolesLabel ) { #>
                        <span class="elementsell-course-image__admin-note">Viditelné pro: {{{ rolesLabel }}} (náhled v editoru)</span>
                    <# } else { #>
                        <span class="elementsell-course-image__admin-note">Vyplňte alespoň jednu roli pro zobrazení na webu.</span>
                    <# } #>
                </span>
            <# if ( linkUrl ) { #>
                </a>
            <# } else { #>
                </div>
            <# } #>
        </div>
        <style><?php echo $this->get_course_image_styles(); ?></style>
        <?php
    }

    /**
     * @param array<string, mixed> $settings
     * @return string
     */
    private function get_image_width_css_var( $settings ) {
        $width = $settings['image_width'] ?? [];

        if ( ! is_array( $width ) || ! isset( $width['size'] ) || $width['size'] === '' ) {
            return '560px';
        }

        $size = (float) $width['size'];
        $unit = ! empty( $width['unit'] ) ? (string) $width['unit'] : 'px';

        if ( $unit === '%' ) {
            $size = min( 100, max( 20, $size ) );

            return $size . '%';
        }

        $size = (int) min( 800, max( 120, $size ) );

        return $size . 'px';
    }

    /**
     * @param array<string, mixed> $settings
     * @return string
     */
    private function get_image_width_style( $settings ) {
        return '--elementsell-course-image-width:' . $this->get_image_width_css_var( $settings );
    }

    /**
     * @return string
     */
    private function get_course_image_styles() {
        return '
            .elementsell-course-image {
                position: relative;
                width: 100%;
                max-width: var(--elementsell-course-image-width, 560px);
                margin: 0 auto 24px;
                text-align: center;
            }
            @media (max-width: 767px) {
                .elementsell-course-image {
                    max-width: min(var(--elementsell-course-image-width, 560px), 85vw);
                }
            }
            .elementsell-course-image__link {
                display: block;
                text-decoration: none;
            }
            .elementsell-course-image__visual {
                position: relative;
                display: block;
            }
            .elementsell-course-image__img {
                display: block;
                width: 100%;
                height: auto;
                border-radius: 8px;
            }
            .elementsell-course-image__img--admin {
                opacity: 0.4;
            }
            .elementsell-course-image__admin-note {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: calc(100% - 24px);
                margin: 0;
                padding: 10px 14px;
                border-radius: 8px;
                background: rgba(255, 255, 255, 0.92);
                color: #646970;
                font-size: 13px;
                line-height: 1.4;
                text-align: center;
                pointer-events: none;
            }
        ';
    }

    /**
     * @return void
     */
    private function render_styles_once() {
        static $done = false;

        if ( $done ) {
            return;
        }

        $done = true;
        ?>
        <style><?php echo $this->get_course_image_styles(); ?>
            .elementsell-course-image__link {
                transition: transform 0.2s ease;
            }
            .elementsell-course-image__link:hover {
                transform: translateY(-2px);
            }
            .elementsell-course-image--notice {
                padding: 16px;
                border: 1px dashed #c3c4c7;
                border-radius: 8px;
                color: #646970;
                text-align: center;
            }
        </style>
        <?php
    }
}
