<?php
namespace Bricks;
if ( ! defined( 'ABSPATH' ) ) exit;

class Next_Countdown extends \Bricks\Element {
  public $category     = 'Next Bricks - Texts';
  public $name         = 'next-countdown';
  public $icon         = 'ion-ios-timer';
  public $tag      = 'h3';
  public $scripts      = ['next_countdown'];

  public function get_label() {
    return esc_html__( 'Countdown', 'bricks' );
  }

  public function set_controls() {
    $this->controls['tag'] = [
        'tab'         => 'content',
        'label'       => esc_html__( 'HTML tag', 'bricks' ),
        'type'        => 'select',
        'options'     => [
            'h1' => 'h1',
            'h2' => 'h2',
            'h3' => 'h3',
            'h4' => 'h4',
            'h5' => 'h5',
            'h6' => 'h6',
            'p' => 'p',
            'span' => 'span',
            'custom' => 'custom',
        ],
        'clearable'   => false,
        'inline'      => true,
        'placeholder' => 'h3',
        'default'     => 'h3',
    ];
    $this->controls['customTag'] = [
        'tab'         => 'content',
        'label'       => esc_html__( 'Custom tag', 'bricks' ),
        'type'        => 'text',
        'inline'      => true,
        'placeholder' => 'h3',
        'required'    => [ 'tag', '=', 'custom' ],
    ];

    /* Countdown */
    $this->controls['countdownSeparator'] = [
        'label' => esc_html__( 'Countdown Settings', 'bricks' ),
        'type' => 'separator',
    ];
    $this->controls['countdownType'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Countdown Type', 'bricks' ),
        'type' => 'select',
        'options' => [
            'date' => esc_html__( 'End Date', 'bricks' ),
            'session' => esc_html__( 'User Session', 'bricks' ),
        ],
        'default' => 'date',
        'inline' => true,
    ];
    $this->controls['timezone'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Timezone', 'bricks' ),
        'type' => 'select',
        'options' => [
            'America/New_York' => 'New York',
            'America/Los_Angeles' => 'Los Angeles',
            'America/Chicago' => 'Chicago',
            'Europe/London' => 'London',
            'Europe/Paris' => 'Paris',
            'Asia/Tokyo' => 'Tokyo',
            'Asia/Dubai' => 'Dubai',
            'Asia/Shanghai' => 'Shanghai',
            'Australia/Sydney' => 'Sydney',
            'Pacific/Auckland' => 'Auckland'
        ],
        'default' => 'America/New_York',
        'inline' => true,
        'rerender' => true,
        'reloadScripts' => true,
        'required' => [ 'countdownType', '=', 'date' ],
    ];
    $this->controls['endDate'] = [
        'tab' => 'content',
        'label' => esc_html__('Date', 'bricks'),
        'type' => 'datepicker',
        'options' => [
          'enableTime' => true,  // Enables time selection.
          'time_24hr' => true,   // Displays time picker in 24-hour mode.
        ],
        'default' => '2030-12-30 20:37:20',
        'required' => [ 'countdownType', '=', 'date' ],
    ];
    $this->controls['note0'] = [
        'tab' => 'content',
        'description' => sprintf(html_entity_decode(esc_html__( 'Each Session End Date will be stored in the browser\'s user, so it will be persistent across page reloads. The name of the key is the End Date itself.<br>Use the format: DD:HH:MM:SS', 'bricks' )))
    ];
    $this->controls['sessionEndDate'] = [
        'tab' => 'content',
        'label' => esc_html__('Session End Date', 'bricks'),
        'type' => 'text',
        'default' => '02:20:37:20',
        'required' => [ 'countdownType', '=', 'session' ],
    ];
    $this->controls['note'] = [
        'tab' => 'content',
        'description' => sprintf(html_entity_decode(esc_html__( 'If you want to run custom JavaScript when the countdown ends, you can add it here.<br> It is a common practice to hide specific elements.', 'bricks' )))
    ];
    $this->controls['customJs'] = [
        'tab' => 'content',
        'label' => esc_html__('Custom JavaScript', 'bricks'),
        'type' => 'textarea',
        'placeholder' => 'document.querySelector(".nb-countdown").style.display = "none";',
        'rerender' => true,
        'reloadScripts' => true,
    ];

    /*Units Wrapper Style*/
    $this->controls['unitsWrapperStyleSeparator'] = [
        'label'      => esc_html__( 'Units Wrapper Style', 'bricks' ),
        'type'       => 'separator',
    ];
    $this->controls['unitsWrapperPadding'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Padding', 'bricks' ),
        'type' => 'spacing',
        'css' => [
            [
                'property' => 'padding',
                'selector' => '.nb-countdown__unit-container',
            ],
        ],
        'default' => [
            'top' => 0,
            'right' => 20,
            'bottom' => 0,
            'left' => 20,
        ],
    ];
    $this->controls['unitsWrapperGap'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Gap', 'bricks' ),
        'type' => 'number',
        'units' => true,
        'css' => [
            [
                'property' => 'gap',
                'selector' => '.nb-countdown__unit-container',
            ],
        ],
        'default' => 12,
    ];

    /* Units */
    $this->controls['unitsSeparator'] = [
        'label'      => esc_html__( 'Units', 'bricks' ),
        'type'       => 'separator',
    ];
    $this->controls['unitsDimensions'] = [
        'tab' => 'content',
        'label' => esc_html__('Units Width', 'bricks'),
        'type' => 'number',
        'units' => true,
        'css' => [
            [
                'property' => '--unit-dimensions',
                'selector' => '',
            ],
        ],
        'default' => '1em',
    ];
    $this->controls['unitsTypography'] = [
        'tab' => 'content',
        'label' => esc_html__('General Typography', 'bricks'),
        'type' => 'typography',
        'css' => [
            [
                'property' => 'typography',
                'selector' => '.nb-countdown__unit-container',
            ],
        ],
        'inline' => true,
    ];
    $this->controls['showDays'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Show Days', 'bricks' ),
        'type' => 'checkbox',
        'inline' => true,
        'default' => true,
    ];
    $this->controls['daysTitle'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Days Title', 'bricks' ),
        'type' => 'text',
        'inline' => true,
        'default' => 'Days',
        'required' => [ 'showDays', '=', true ],
    ];
    $this->controls['daysTypography'] = [
        'tab' => 'content',
        'label' => esc_html__('Days Typography', 'bricks'),
        'type' => 'typography',
        'css' => [
            [
                'property' => 'typography',
                'selector' => '.nb-countdown__unit-container--days',
            ],
        ],
        'inline' => true,
        'required' => [ 'showDays', '=', true ],
    ];
    $this->controls['showHours'] = [
        'tab' => 'content', 
        'label' => esc_html__( 'Show Hours', 'bricks' ),
        'type' => 'checkbox',
        'inline' => true,
        'default' => true,
    ];
    $this->controls['hoursTitle'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Hours Title', 'bricks' ),
        'type' => 'text',
        'inline' => true,
        'default' => 'Hours',
        'required' => [ 'showHours', '=', true ],
    ];
    $this->controls['hoursTypography'] = [
        'tab' => 'content',
        'label' => esc_html__('Hours Typography', 'bricks'),
        'type' => 'typography',
        'css' => [
            [
                'property' => 'typography',
                'selector' => '.nb-countdown__unit-container--hours',
            ],
        ],
        'inline' => true,
        'required' => [ 'showHours', '=', true ],
    ];
    $this->controls['showMinutes'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Show Minutes', 'bricks' ),
        'type' => 'checkbox', 
        'inline' => true,
        'default' => true,
    ];
    $this->controls['minutesTitle'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Minutes Title', 'bricks' ),
        'type' => 'text',
        'inline' => true,
        'default' => 'Minutes',
        'required' => [ 'showMinutes', '=', true ],
    ];
    $this->controls['minutesTypography'] = [
        'tab' => 'content',
        'label' => esc_html__('Minutes Typography', 'bricks'),
        'type' => 'typography',
        'css' => [
            [
                'property' => 'typography',
                'selector' => '.nb-countdown__unit-container--minutes',
            ],
        ],
        'inline' => true,
        'required' => [ 'showMinutes', '=', true ],
    ];
    $this->controls['showSeconds'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Show Seconds', 'bricks' ),
        'type' => 'checkbox',
        'inline' => true, 
        'default' => true,
    ];
    $this->controls['secondsTitle'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Seconds Title', 'bricks' ),
        'type' => 'text',
        'inline' => true,
        'default' => 'Seconds',
        'required' => [ 'showSeconds', '=', true ],
    ];
    $this->controls['secondsTypography'] = [
        'tab' => 'content',
        'label' => esc_html__('Seconds Typography', 'bricks'),
        'type' => 'typography',
        'css' => [
            [
                'property' => 'typography',
                'selector' => '.nb-countdown__unit-container--seconds',
            ],
        ],
        'inline' => true,
        'required' => [ 'showSeconds', '=', true ],
    ];

    /*Units Animation*/
    $this->controls['unitsAnimationSeparator'] = [
        'label'      => esc_html__( 'Units Animation', 'bricks' ),
        'type'       => 'separator',
    ];
    $this->controls['fadeFrom'] = [
        'tab' => 'content',
        'label' => esc_html__( 'Fade From', 'bricks' ),
        'type' => 'text',
        'inline' => true,
        'default' => '0',
    ];
    $this->controls['unitsAnimationEase'] = [
        'tab' => 'content',
        'label' => esc_html__( 'GSAP Easing', 'bricks' ),
        'type' => 'select',
        'inline' => true,
        'options'     => [
            'none' => 'none',
            'power1' => 'power1',
            'power2' => 'power2',
            'power3' => 'power3',
            'power4' => 'power4',
            'back' => 'back',
            'bounce' => 'bounce',
            'circ' => 'circ',
            'elastic' => 'elastic',
            'expo' => 'expo',
            'sine' => 'sine',
            'steps' => 'steps',
            'custom' => 'custom'
          ],
        'default' => 'back',
    ];
    $this->controls['customUnitsAnimationEase'] = [
      'hasDynamicData' => false,
      'tab' => 'content',
      'label' => esc_html__( 'Custom easing', 'bricks' ),
      'type' => 'text',
      'inline' => true,
      'placeholder' => 'back.out(1.7)',
      'default' => 'back.out(1.7)',
      'required' => [ 'unitsAnimationEase', '=', 'custom' ],
    ];



  }

  public function enqueue_scripts() {
    wp_enqueue_script( 'next-countdown', NEXTBRICKS_PLUGIN_URL . 'elements/js/next_countdown.min.js', array('bricks-scripts'), NEXTBRICKS_VERSION, false);
  }

  public function render() {
    $settings = $this->settings;
    $is_builder = bricks_is_builder();
    $countdownType = ! empty( $settings['countdownType'] ) ? $settings['countdownType'] : 'date';
    $endDate = ! empty( $settings['endDate'] ) ? $settings['endDate'] : '2030-12-30 20:37:20';
    $sessionEndDate = ! empty( $settings['sessionEndDate'] ) ? $settings['sessionEndDate'] : '02:20:37:20';
    $timezone = ! empty( $settings['timezone'] ) ? $settings['timezone'] : 'Europe/Paris';
    $customJs = ! empty( $settings['customJs'] ) ? $settings['customJs'] : '';
    $daysTitle = ! empty( $settings['daysTitle'] ) ? $settings['daysTitle'] : 'Days';
    $showDays = ! empty( $settings['showDays'] ) ? $settings['showDays'] : false;
    $hoursTitle = ! empty( $settings['hoursTitle'] ) ? $settings['hoursTitle'] : 'Hours';
    $showHours = ! empty( $settings['showHours'] ) ? $settings['showHours'] : false;
    $minutesTitle = ! empty( $settings['minutesTitle'] ) ? $settings['minutesTitle'] : 'Minutes';
    $showMinutes = ! empty( $settings['showMinutes'] ) ? $settings['showMinutes'] : false;
    $secondsTitle = ! empty( $settings['secondsTitle'] ) ? $settings['secondsTitle'] : 'Seconds';
    $showSeconds = ! empty( $settings['showSeconds'] ) ? $settings['showSeconds'] : false;
    $fadeFrom = ! empty( $settings['fadeFrom'] ) ? $settings['fadeFrom'] : 0;
    $unitsDuration = ! empty( $settings['unitsDuration'] ) ? $settings['unitsDuration'] : '0.4s';
    $unitsDelay = ! empty( $settings['unitsDelay'] ) ? $settings['unitsDelay'] : '-=0.2s';
    $unitsAnimationEase = ! empty( $settings['unitsAnimationEase'] ) ? $settings['unitsAnimationEase'] : 'back';
    if ($unitsAnimationEase === 'custom') {
      $unitsAnimationEase = ! empty( $settings['customUnitsAnimationEase'] ) ? $settings['customUnitsAnimationEase'] : 'back';
    }

    $this->set_attribute( '_root', 'class', 'nb-countdown' );

    $flickering_attribute = $is_builder ? '' : "\n    data-flickering='1'";

    $output = "<{$this->tag} {$this->render_attributes( '_root' )}" . $flickering_attribute . "
    data-countdown-type='{$countdownType}'
    data-end-date='{$endDate}'
    data-session-end-date='{$sessionEndDate}'
    data-timezone='{$timezone}'
    data-custom-js='{$customJs}'
    data-units-duration='{$unitsDuration}'
    data-units-delay='{$unitsDelay}'
    data-units-animation-ease='{$unitsAnimationEase}'
    data-fade-from='{$fadeFrom}'>";
    if($showDays) {
      // Determine number of digit containers for days
      if ($countdownType === 'date') {
        // In date mode, match the number of digits to the actual days left
        $endDateTime = new \DateTime($endDate, new \DateTimeZone($timezone));
        $now = new \DateTime('now', new \DateTimeZone($timezone));
        $interval = $now->diff($endDateTime);
        $daysLeft = $interval->days;
        $numDigits = strlen((string)$daysLeft);
        $numDigits = max(2, min(4, $numDigits));
      } else {
        // In session mode we always render exactly two digits to align with JS
        $numDigits = 2;
      }

      $output .= "<div class='nb-countdown__unit-container nb-countdown__unit-container--days'>";
      $output .= "<span>{$daysTitle}</span>";
      $output .= "<div class='nb-countdown__unit'>";
      
      // Add digit containers based on calculated number needed
      for($i = 0; $i < $numDigits; $i++) {
        $output .= "<div class='nb-countdown__digit-container'>";
        $output .= "<div class='nb-countdown__current-value'></div>";
        $output .= "<div class='nb-countdown__next-value'></div>";
        $output .= "</div>";
      }

      $output .= "</div>";
      $output .= "</div>";
    }
    if($showHours) {
        $output .= "<div class='nb-countdown__unit-container nb-countdown__unit-container--hours'>";
          $output .= "<span>{$hoursTitle}</span>";
          $output .= "<div class='nb-countdown__unit'>";
              $output .= "<div class='nb-countdown__digit-container'>";
                  $output .= "<div class='nb-countdown__current-value'></div>";
                  $output .= "<div class='nb-countdown__next-value'></div>";
              $output .= "</div>";
              $output .= "<div class='nb-countdown__digit-container'>";
                  $output .= "<div class='nb-countdown__current-value'></div>";
                  $output .= "<div class='nb-countdown__next-value'></div>";
              $output .= "</div>";
          $output .= "</div>";
        $output .= "</div>";
    }
    if($showMinutes) {
        $output .= "<div class='nb-countdown__unit-container nb-countdown__unit-container--minutes'>";
          $output .= "<span>{$minutesTitle}</span>";
          $output .= "<div class='nb-countdown__unit'>";
              $output .= "<div class='nb-countdown__digit-container'>";
                  $output .= "<div class='nb-countdown__current-value'></div>";
                  $output .= "<div class='nb-countdown__next-value'></div>";
              $output .= "</div>";
              $output .= "<div class='nb-countdown__digit-container'>";
                  $output .= "<div class='nb-countdown__current-value'></div>";
                  $output .= "<div class='nb-countdown__next-value'></div>";
              $output .= "</div>";
          $output .= "</div>";
        $output .= "</div>";
    }
    if($showSeconds) {
        $output .= "<div class='nb-countdown__unit-container nb-countdown__unit-container--seconds'>";
          $output .= "<span>{$secondsTitle}</span>";
          $output .= "<div class='nb-countdown__unit'>";
              $output .= "<div class='nb-countdown__digit-container'>";
                  $output .= "<div class='nb-countdown__current-value'></div>";
                  $output .= "<div class='nb-countdown__next-value'></div>";
              $output .= "</div>";
              $output .= "<div class='nb-countdown__digit-container'>";
                  $output .= "<div class='nb-countdown__current-value'></div>";
                  $output .= "<div class='nb-countdown__next-value'></div>";
              $output .= "</div>";
          $output .= "</div>";
        $output .= "</div>";
    }
    $output .= "</{$this->tag}>";

    echo $output;
  }
}
