<?php
/**
 * Front-end countdown rendering and assets.
 *
 * @package TIP_Countdown_Generator
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'tipcg_frontend' ) ) {

	/**
	 * Renders countdown shortcodes and registers front-end assets.
	 */
	class tipcg_frontend extends tipcg_tracking {

/**
		 * Shortcode [tipcg_countdown].
		 *
		 * Main attributes:
		 * - type: "evergreen" (default) or "fixed".
		 * - template: "default" or "flip_clock".
		 * - evergreen duration: "duration" (DD:HH:MM:SS) or evergreen_days/hours/minutes/seconds.
		 * - tracking: "cookie", "ip", or "cookie_ip" (evergreen only).
		 * - target_date: date/time (datetime-local) for a fixed-date countdown.
		 * - style parameters: number_font_size, label_font_size, cell_background_color, cell_text_color, label_text_color, countdown_alignment, show_separators, separator_text_color, cell_border_radius, margin_top, margin_bottom.
		 * - id: countdown identifier.
		 * - countdown_id (optional): saved slot number from the panel; when present, saved options are used as the base.
		 *
		 * @param array $atts Shortcode attributes.
		 */
        public function add_shortcode( $atts ) {

            $raw_atts = is_array( $atts ) ? $atts : array();

            $atts = shortcode_atts( array(
                'countdown_id'        => '',
                'slot'                => '',
                'type'                => 'evergreen',
                'template'            => 'default',
                'duration'            => '00:00:10:00',
                'evergreen_days'      => 0,
                'evergreen_hours'     => 0,
                'evergreen_minutes'   => 10,
                'evergreen_seconds'   => 0,
                'tracking'            => 'cookie',
                'id'                  => 'default',
                'target_date'         => '',
                'number_font_size'    => '',
                'label_font_size'     => '',
                'cell_background_color' => '',
                'cell_text_color'     => '',
                'label_text_color'    => '',
                'countdown_alignment' => 'center',
                'show_separators'     => '1',
                'separator_text_color' => '',
                'cell_border_radius'  => '',
                'margin_top'          => '',
                'margin_bottom'       => '',
            ), $atts, 'tipcg_countdown' );

            // If a saved slot was passed, read values from the database and apply them as the base.
            $slot_requested = '';
            if ( ! empty( $atts['countdown_id'] ) ) {
                $slot_requested = $atts['countdown_id'];
            } elseif ( ! empty( $atts['slot'] ) ) {
                $slot_requested = $atts['slot'];
            }

            if ( '' !== $slot_requested ) {
                $slot_key = $this->resolve_slot_key( $slot_requested );
                if ( $slot_key ) {
                    $saved = $this->get_saved_countdown_config( $slot_key );
                    if ( $saved ) {
                        $flat_saved = $this->flatten_countdown_config( $saved );
                        foreach ( $flat_saved as $key => $value ) {
                            if ( ! array_key_exists( $key, $raw_atts ) || '' === $raw_atts[ $key ] ) {
                                $atts[ $key ] = $value;
                            }
                        }
                        // Keep the slot number as an attribute for debug or front-end use.
                        $atts['countdown_id'] = absint( str_replace( 'slot', '', $slot_key ) );
                    } else {
                        // Requested slot is missing: do not show the countdown.
                        return '';
                    }
                }
            }

            $type          = strtolower( $atts['type'] );
            $allowed_types = array( 'evergreen', 'fixed' );
            if ( ! in_array( $type, $allowed_types, true ) ) {
                $type = 'evergreen';
            }

            $template = sanitize_key( $atts['template'] );
            if ( ! in_array( $template, array( 'default', 'flip_clock' ), true ) ) {
                $template = 'default';
            }

            $atts['id'] = $this->normalize_countdown_id( $atts['id'] );
            $tracking   = sanitize_key( $atts['tracking'] );
            $atts['tracking'] = in_array( $tracking, array( 'cookie', 'ip', 'cookie_ip' ), true ) ? $tracking : 'cookie';

            $style_attr_keys = array(
                'number_font_size',
                'label_font_size',
                'cell_background_color',
                'cell_text_color',
                'label_text_color',
                'separator_text_color',
                'cell_border_radius',
                'margin_top',
                'margin_bottom',
            );
            $use_shortcode_styles = false;
            foreach ( $style_attr_keys as $style_attr_key ) {
                if ( array_key_exists( $style_attr_key, $raw_atts ) && '' !== $raw_atts[ $style_attr_key ] ) {
                    $use_shortcode_styles = true;
                    break;
                }
            }

            $container_attr  = '';
            $time_unit_attr  = '';
            $value_attr      = '';
            $label_attr      = '';
            $clock_card_attr = '';
            $clock_face_attr = '';
            $separator_attr = '';
            $show_separators = ! in_array( strtolower( (string) $atts['show_separators'] ), array( '0', 'false', 'no', 'off' ), true );
            $countdown_alignment = sanitize_key( $atts['countdown_alignment'] );
            $countdown_alignment = in_array( $countdown_alignment, array( 'left', 'center', 'right' ), true ) ? $countdown_alignment : 'center';
            $alignment_class = 'tipcg_countdown_' . $countdown_alignment . '_alignment';

            if ( $use_shortcode_styles ) {
                $defaults = $this->default_countdown_template();

                $number_font_size = ( '' !== $atts['number_font_size'] ) ? absint( $atts['number_font_size'] ) : $defaults['number_font_size'];
                $number_font_size = min( 200, max( 8, $number_font_size ) );

                $label_font_size = ( '' !== $atts['label_font_size'] ) ? absint( $atts['label_font_size'] ) : $defaults['label_font_size'];
                $label_font_size = min( 80, max( 6, $label_font_size ) );

                $cell_background_color = sanitize_hex_color( $atts['cell_background_color'] );
                $cell_background_color = $cell_background_color ? $cell_background_color : $defaults['cell_background_color'];

                $cell_text_color = sanitize_hex_color( $atts['cell_text_color'] );
                $cell_text_color = $cell_text_color ? $cell_text_color : $defaults['cell_text_color'];

                $label_text_color = sanitize_hex_color( $atts['label_text_color'] );
                if ( ! $label_text_color ) {
                    $label_text_color = ( array_key_exists( 'cell_text_color', $raw_atts ) && '' !== $raw_atts['cell_text_color'] ) ? $cell_text_color : $defaults['label_text_color'];
                }

                $separator_text_color = sanitize_hex_color( $atts['separator_text_color'] );
                $separator_text_color = $separator_text_color ? $separator_text_color : $cell_text_color;

                $cell_border_radius = ( '' !== $atts['cell_border_radius'] ) ? absint( $atts['cell_border_radius'] ) : $defaults['cell_border_radius'];
                $cell_border_radius = min( 80, max( 0, $cell_border_radius ) );

                $margin_top = ( '' !== $atts['margin_top'] ) ? absint( $atts['margin_top'] ) : $defaults['margin_top'];
                $margin_top = min( 400, max( 0, $margin_top ) );

                $margin_bottom = ( '' !== $atts['margin_bottom'] ) ? absint( $atts['margin_bottom'] ) : $defaults['margin_bottom'];
                $margin_bottom = min( 400, max( 0, $margin_bottom ) );

                $cell_width   = max( 80, (int) round( $number_font_size * 1.72 ) );
                $clock_width  = max( 48, (int) round( $number_font_size * 1.8 ) );
                $clock_height = max( 58, (int) round( $number_font_size * 2.2 ) );

                $separator_height = $number_font_size;
                $separator_margin_top = 10;
                if ( 'flip_clock' === $template ) {
                    $separator_height = $clock_height;
                    $separator_margin_top = 0;
                }

                $transparent_unit_templates = array( 'flip_clock' );
                $time_unit_css = in_array( $template, $transparent_unit_templates, true )
                    ? 'background-color:transparent;color:' . $cell_text_color . ';border-radius:0;'
                    : 'background-color:' . $cell_background_color . ';color:' . $cell_text_color . ';border-radius:' . $cell_border_radius . 'px;';

                $timer_number_reset_css = 'line-height:1;letter-spacing:0;word-spacing:0;text-indent:0;text-transform:none;text-shadow:none;font-style:normal;font-variant-numeric:tabular-nums;font-feature-settings:"tnum";white-space:nowrap;direction:ltr;unicode-bidi:isolate;';
                $timer_label_reset_css  = 'line-height:1.2;letter-spacing:0;word-spacing:0;text-indent:0;text-shadow:none;font-style:normal;';
                $timer_box_reset_css    = 'line-height:1;letter-spacing:0;word-spacing:0;text-indent:0;text-align:center;';
                $time_unit_css         .= $timer_box_reset_css;

                $container_css   = 'margin-top:' . $margin_top . 'px;margin-bottom:' . $margin_bottom . 'px;--tipcg-cell-width:' . $cell_width . 'px;--tipcg-clock-width:' . $clock_width . 'px;--tipcg-clock-height:' . $clock_height . 'px;';
                $container_attr  = ' style="' . esc_attr( $container_css ) . '"';
                $time_unit_attr  = ' style="' . esc_attr( $time_unit_css ) . '"';
                $value_attr      = ' style="' . esc_attr( 'font-size:' . $number_font_size . 'px;color:' . $cell_text_color . ';' . $timer_number_reset_css ) . '"';
                $label_attr      = ' style="' . esc_attr( 'font-size:' . $label_font_size . 'px;color:' . $label_text_color . ';' . $timer_label_reset_css ) . '"';
                $separator_attr  = ' style="' . esc_attr( 'height:' . $separator_height . 'px;margin-top:' . $separator_margin_top . 'px;font-size:' . $number_font_size . 'px;color:' . $separator_text_color . ';' . $timer_number_reset_css . 'background:transparent;' ) . '"';
                $clock_card_attr = ' style="' . esc_attr( 'min-width:' . $clock_width . 'px;width:max(' . $clock_width . 'px,var(--tipcg-adaptive-card-width,0px));height:' . $clock_height . 'px;' ) . '"';
                $clock_face_attr = ' style="' . esc_attr( 'background-color:' . $cell_background_color . ';color:' . $cell_text_color . ';border-radius:' . $cell_border_radius . 'px;font-size:' . $number_font_size . 'px;padding-inline:.18em;' . $timer_number_reset_css ) . '"';
            }

            $data_attrs = array();

            if ( 'evergreen' === $type ) {
                $ev_parts = array(
                    'days'    => intval( $atts['evergreen_days'] ),
                    'hours'   => intval( $atts['evergreen_hours'] ),
                    'minutes' => intval( $atts['evergreen_minutes'] ),
                    'seconds' => intval( $atts['evergreen_seconds'] ),
                );

                if ( 0 === ( $ev_parts['days'] + $ev_parts['hours'] + $ev_parts['minutes'] + $ev_parts['seconds'] ) ) {
                    $ev_parts = $this->duration_string_to_parts( $atts['duration'] );
                }
                if ( 0 === ( $ev_parts['days'] + $ev_parts['hours'] + $ev_parts['minutes'] + $ev_parts['seconds'] ) ) {
                    $ev_parts['minutes'] = 10;
                }

                $duration_seconds = $this->duration_parts_to_seconds( $ev_parts );
                $start_time       = $this->get_start_time( $atts['tracking'], $atts['id'], $duration_seconds );

                $data_attrs['start-time'] = $start_time;
                $data_attrs['duration']   = $duration_seconds;
                $data_attrs['tracking']   = strtolower( $atts['tracking'] );
            } elseif ( 'fixed' === $type ) {
                $target_time = $this->parse_datetime_to_timestamp( $atts['target_date'] );
                if ( null === $target_time ) {
                    $target_time = current_time( 'timestamp' ) + HOUR_IN_SECONDS;
                }
                $data_attrs['target-time'] = $target_time;
            }

            // Store shortcode data directly as container data attributes instead of using wp_localize_script globals.
            $separator_state_class = $show_separators ? 'tipcg-has-separators' : 'tipcg-no-separators';
            $markup = '<div id="tipcg_countdown-' . esc_attr( $atts['id'] ) . '" class="tipcg_countdown tipcg-is-pending tipcg-template-' . esc_attr( $template ) . ' ' . esc_attr( $separator_state_class ) . ' ' . esc_attr( $alignment_class ) . '"';
            $markup .= ' data-type="' . esc_attr( $type ) . '"';
            $markup .= ' data-template="' . esc_attr( $template ) . '"';
            $markup .= $container_attr;

            foreach ( $data_attrs as $key => $value ) {
                if ( '' === $value || null === $value ) {
                    continue;
                }
                $markup .= ' data-' . esc_attr( $key ) . '="' . esc_attr( $value ) . '"';
            }

            $markup .= '>';

            $units = array(
                'days'    => esc_html__( 'Days', 'tip-countdown-generator' ),
                'hours'   => esc_html__( 'Hours', 'tip-countdown-generator' ),
                'minutes' => esc_html__( 'Minutes', 'tip-countdown-generator' ),
                'seconds' => esc_html__( 'Seconds', 'tip-countdown-generator' ),
            );

            $separator_map = array(
                'hours'   => 'days-hours',
                'minutes' => 'hours-minutes',
                'seconds' => 'minutes-seconds',
            );

            foreach ( $units as $unit_class => $unit_label ) {
                if ( $show_separators && isset( $separator_map[ $unit_class ] ) ) {
                    $separator_class = 'tipcg-separator-' . $separator_map[ $unit_class ];
                    $markup .= '<span class="tipcg-separator ' . esc_attr( $separator_class ) . '" aria-hidden="true"' . $separator_attr . '><span class="tipcg-separator-text">:</span><span class="tipcg-separator-dots"><span></span><span></span></span></span>';
                }

                $markup .= '<div class="time-unit ' . esc_attr( $unit_class ) . '"' . $time_unit_attr . '>';
                    if ( 'flip_clock' === $template ) {
                        $markup .= '<div class="tipcg-clock-card"' . $clock_card_attr . '>';
                            $markup .= '<div class="tipcg-clock-inner">';
                                $markup .= '<span class="tipcg-clock-front value"' . $clock_face_attr . '>00</span>';
                                $markup .= '<span class="tipcg-clock-back value"' . $clock_face_attr . '>00</span>';
                            $markup .= '</div>';
                        $markup .= '</div>';
                    } else {
                        $markup .= '<span class="value"' . $value_attr . '>00</span>';
                    }
                    $markup .= '<span class="label"' . $label_attr . '>' . esc_html( $unit_label ) . '</span>';
                $markup .= '</div>';
            }

            $markup .= '</div>';
            
            return $markup;
        }

/**
		 * Generates inline CSS for saved countdown styles.
		 */
        protected function get_saved_countdowns_inline_css() {
            $settings = maybe_unserialize( get_option( TIPCG_OPTION_KEY ) );
            if ( ! is_array( $settings ) || empty( $settings['tipcg_countdowns'] ) || ! is_array( $settings['tipcg_countdowns'] ) ) {
                return '';
            }

            $css = array();

            foreach ( $settings['tipcg_countdowns'] as $slot => $config ) {
                $slot_key = $this->resolve_slot_key( $slot );
                if ( ! $slot_key || ! is_array( $config ) ) {
                    continue;
                }

                $index    = absint( str_replace( 'slot', '', $slot_key ) );
                $config   = $this->normalize_countdown_config( $config, $index );
                $selector = '#tipcg_countdown-' . $this->normalize_countdown_id( $config['id'] );
                $number_font_size = absint( $config['number_font_size'] );
                $cell_width       = max( 80, (int) round( $number_font_size * 1.72 ) );
                $clock_width      = max( 48, (int) round( $number_font_size * 1.8 ) );
                $clock_height     = max( 58, (int) round( $number_font_size * 2.2 ) );

                $separator_height = $number_font_size;
                $separator_margin_top = 10;
                if ( 'flip_clock' === $config['template'] ) {
                    $separator_height = $clock_height;
                    $separator_margin_top = 0;
                }

                $timer_number_reset_css = 'line-height:1;letter-spacing:0;word-spacing:0;text-indent:0;text-transform:none;text-shadow:none;font-style:normal;font-variant-numeric:tabular-nums;font-feature-settings:"tnum";white-space:nowrap;direction:ltr;unicode-bidi:isolate;';
                $timer_label_reset_css  = 'line-height:1.2;letter-spacing:0;word-spacing:0;text-indent:0;text-shadow:none;font-style:normal;';
                $timer_box_reset_css    = 'line-height:1;letter-spacing:0;word-spacing:0;text-indent:0;text-align:center;';

                $css[] = $selector . '{margin-top:' . absint( $config['margin_top'] ) . 'px;margin-bottom:' . absint( $config['margin_bottom'] ) . 'px;--tipcg-cell-width:' . $cell_width . 'px;--tipcg-clock-width:' . $clock_width . 'px;--tipcg-clock-height:' . $clock_height . 'px;}';
                $css[] = $selector . ' .time-unit{background-color:' . $config['cell_background_color'] . ';color:' . $config['cell_text_color'] . ';border-radius:' . absint( $config['cell_border_radius'] ) . 'px;' . $timer_box_reset_css . '}';
                $css[] = $selector . ' span.value{font-size:' . $number_font_size . 'px;color:' . $config['cell_text_color'] . ';' . $timer_number_reset_css . '}';
                $css[] = $selector . ' span.label{font-size:' . absint( $config['label_font_size'] ) . 'px;color:' . $config['label_text_color'] . ';' . $timer_label_reset_css . '}';
                $css[] = $selector . ' .tipcg-separator{height:' . $separator_height . 'px;margin-top:' . $separator_margin_top . 'px;font-size:' . $number_font_size . 'px;color:' . $config['separator_text_color'] . ';' . $timer_number_reset_css . 'background:transparent;}';

                if ( 'flip_clock' === $config['template'] ) {
                    $css[] = $selector . '.tipcg-template-flip_clock .time-unit{background-color:transparent;border-radius:0;}';
                    $css[] = $selector . ' .tipcg-clock-card{min-width:' . $clock_width . 'px;width:max(' . $clock_width . 'px,var(--tipcg-adaptive-card-width,0px));height:' . $clock_height . 'px;}';
                    $css[] = $selector . '.tipcg-template-flip_clock .time-unit{min-width:' . $clock_width . 'px;}';
                    $css[] = $selector . '.tipcg-template-flip_clock .tipcg-separator{height:' . $clock_height . 'px;margin-top:0;align-self:flex-start;}';
                    $css[] = $selector . ' .tipcg-clock-front,' . $selector . ' .tipcg-clock-back{background-color:' . $config['cell_background_color'] . ';color:' . $config['cell_text_color'] . ';border-radius:' . absint( $config['cell_border_radius'] ) . 'px;padding-inline:.18em;' . $timer_number_reset_css . '}';
                }
            }

            return implode( "\n", $css );
        }

/**
		 * Enqueues front-end styles and scripts.
		 */
			public function site_scripts() {

            wp_enqueue_style (
                'tipcg_countdown_style',
				TIPCG_PLUGIN_FOLDER . '/assets/css/countdown.css',
				array(),
				'3.4'
			);

            $inline_css = $this->get_saved_countdowns_inline_css();
            if ( '' !== $inline_css ) {
                wp_add_inline_style( 'tipcg_countdown_style', wp_kses( $inline_css, array() ) );
            }

            wp_enqueue_script(
                'tipcg_countdown', 
                TIPCG_PLUGIN_FOLDER . '/assets/js/countdown.js',
                array('jquery'),
                '3.2',
                TRUE
            );
        
        }

	}

}
