<?php
defined( 'ABSPATH' ) || exit;

class Jalpi_Element_Flip_Box extends Jalpi_Element {
    public static function type(): string { return 'flip-box'; }

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id      = sanitize_html_class( $node['id'] ?? '' );
        $content = $node['content'] ?? [];
        $styles  = $node['styles']  ?? [];
        $a       = $renderer->get_css_attrs( $node );

        $height    = Jalpi_Sanitizer::sanitize_dimension( $content['height'] ?? '220px' ) ?: '220px';
        $front_bg  = Jalpi_Sanitizer::sanitize_color( $content['frontBg']          ?? '#6366f1' ) ?: '#6366f1';
        $front_col = Jalpi_Sanitizer::sanitize_color( $content['frontColor']       ?? '#ffffff' ) ?: '#ffffff';
        $back_bg   = Jalpi_Sanitizer::sanitize_color( $content['backBg']           ?? '#111827' ) ?: '#111827';
        $back_col  = Jalpi_Sanitizer::sanitize_color( $content['backColor']        ?? '#ffffff' ) ?: '#ffffff';
        $f_title   = esc_html( $content['frontTitle']       ?? __( 'Front Side', 'jalpi-page-builder' ) );
        $f_desc    = esc_html( $content['frontDescription'] ?? '' );
        $b_title   = esc_html( $content['backTitle']        ?? __( 'Back Side', 'jalpi-page-builder' ) );
        $b_desc    = esc_html( $content['backDescription']  ?? '' );
        $btn_text  = esc_html( $content['btnText'] ?? '' );
        $btn_url   = esc_url(  $content['btnUrl']  ?? '#' );

        $base_css = $renderer->styles_to_css( $styles );
        $renderer->add_css( '.jalpi-el.jalpi-' . $id . '{' . $base_css . ';height:' . esc_attr( $height ) . ';}' );

        $btn_html = $btn_text ? '<a href="' . $btn_url . '" class="jalpi-flipbox__btn">' . $btn_text . '</a>' : '';

        $cls = 'jalpi-el jalpi-flipbox jalpi-' . esc_attr( $id ) . $a['extra_cls'];
        return '<div class="' . $cls . '"' . $a['id_attr'] . '>'
             . '<div class="jalpi-flipbox__inner">'
             .   '<div class="jalpi-flipbox__front" style="background:' . esc_attr( $front_bg ) . ';color:' . esc_attr( $front_col ) . ';">'
             .     '<div class="jalpi-flipbox__title">' . $f_title . '</div>'
             .     ( $f_desc ? '<div class="jalpi-flipbox__desc">' . $f_desc . '</div>' : '' )
             .   '</div>'
             .   '<div class="jalpi-flipbox__back" style="background:' . esc_attr( $back_bg ) . ';color:' . esc_attr( $back_col ) . ';">'
             .     '<div class="jalpi-flipbox__title">' . $b_title . '</div>'
             .     ( $b_desc ? '<div class="jalpi-flipbox__desc">' . $b_desc . '</div>' : '' )
             .     $btn_html
             .   '</div>'
             . '</div>'
             . '</div>';
    }
}
