<?php 

if( class_exists( 'CSF' ) ) {

  CSF::createWidget( 'kanews_widget_survey', array(
    'title'       => KAN_THEME_NAME .' - '."Anket",
    'classname'   => 'kanews_widget_class_survey',
    'fields'      => array(

      array(
        'id'      => 'title',
        'type'    => 'text',
        'title'   => 'Title',
      ),

      array(
        'id'      => 'grid',
        'type'    => 'select',
        'title'   => 'Genişlik',
        'options' => array(
          'col-12' => '12/12',
          'col-12 col-lg-8' => '12/8',
          'col-12 col-lg-6' => '12/6',
          'col-12 col-lg-4' => '12/4'
        ),
        'default' => 'col-12'
      ),

      array(
        'id'     => 'options',
        'type'   => 'group',
        'title'  => 'Seçenekler',
        'button_title'  => 'Yeni Ekle',
        'fields' => array(
          array(
            'id'    => 'title',
            'type'  => 'text',
            'title' => 'Seçenek',
          ),
          array(
            'id'    => 'img',
            'type'  => 'media',
            'title' => 'Görsel',
          ),
          array(
            'id'    => 'color',
            'type'  => 'color',
            'title' => 'Renk',
          ),
        ),
      ),

      array(
        'id'      => 'date',
        'type'    => 'text',
        'title'   => 'Bitiş Tarihi',
        'subtitle' => 'Anketin sona ereceği tarih',
        'desc'    => 'Gün/Ay/Yıl formatında (örn: 29/03/2023) veya Y-m-d formatında (örn: 2023-03-29)',
        'default' => date('d/m/Y', strtotime('+1 day')),
        'attributes' => array(
          'placeholder' => '29/03/2023',
          'pattern'     => '(\d{2}/\d{2}/\d{4}|\d{4}-\d{2}-\d{2})',
        ),
      ),
      array(
        'id'      => 'allow_multiple',
        'type'    => 'switcher',
        'title'   => 'Çoklu Oy',
        'label'   => 'Kullanıcıların birden fazla seçenek seçmesine izin ver',
        'default' => false
      ),
      array(
        'id'          => 'max_choices',
        'type'        => 'text',
        'title'       => 'Maksimum Seçim',
        'subtitle'    => 'Çoklu oy aktifken bir kullanıcının seçebileceği en fazla seçenek sayısı.',
        'default'     => 2,
        'attributes'  => array(
          'type' => 'number',
          'min'  => 2,
          'step' => 1,
        ),
        'dependency'  => array('allow_multiple', '==', 'true'),
      ),

      array(
        'id'      => 'hide_desktop',
        'type'    => 'switcher',
        'title'   => 'Masaüstünde Gizle',
        'default' => false
      ),
      array(
        'id'      => 'hide_mobile',
        'type'    => 'switcher',
        'title'   => 'Mobilde Gizle',
        'default' => false
      ),
    
    )
  ) );
  
  if( ! function_exists( 'kanews_widget_survey' ) ) {
    function kanews_widget_survey( $widgets, $instance ) {
      $hide_mobile = $instance['hide_mobile'] ? 'on' : 'off';
      $hide_desktop = $instance['hide_desktop']? 'on' : 'off';

      if($hide_mobile == 'on') {
        if(kan_is_mobile())
        return;
      }

      if($hide_desktop == 'on') {
        if(!kan_is_mobile())
        return;
      }

      $args_defaults = array( 
        'grid'            => 'col-12',
        'title'           => '',
        'date'            => date('d/m/Y', strtotime('+1 day')),
        'options'         => array(),
        'allow_multiple'  => false,
        'max_choices'     => 2,
      ); 
      $args = wp_parse_args( $instance, $args_defaults );
      $allow_multiple = ! empty( $args['allow_multiple'] );
      $max_choices = $allow_multiple ? max( 2, absint( $args['max_choices'] ) ) : 1;
      
      echo '<div class="'.$args['grid'].'"><div class="kanews-section kanews-survey-widget">';
      
      if ( ! empty($args['title']) ) {
        echo ( $widgets['before_title'] . $args['title'] . $widgets['after_title'] );
      }
	  
	  if( empty($args['date']) ) {
		echo '<div class="kanews-response">Anketiniz için bir bitiş tarihi ayarlayın.</div>';
	  } else {
      
		  $args['date'] = empty($args['date']) ? date('d/m/Y', strtotime('+1 day')) : $args['date'];

		  // Handle different date formats
		  $date_input = trim($args['date']);
		  if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $date_input, $matches)) {
			  // d/m/Y format
			  $date = $matches[3] . '-' . $matches[2] . '-' . $matches[1];
		  } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date_input)) {
			  // Y-m-d format
			  $date = $date_input;
		  } else {
			  // Try to parse with strtotime
			  $date = date('Y-m-d', strtotime($date_input));
		  }
		  
		  // Validate date
		  if (!$date || $date === '1970-01-01') {
			  echo '<div class="kanews-response bg-warning">Geçersiz tarih formatı! Lütfen Gün/Ay/Yıl formatında girin (örn: 29/03/2023).</div>';
			  echo '</div></div>';
			  return;
		  }
		  $widgets['widget_id'] = 'kanews-survey-'.md5( serialize( array( $args['options'], $args['date'], $allow_multiple, $max_choices ) ) );
		  
		  $counter = $total_vote = 0;
		  $option_name = $widgets['widget_id'].'-results';
		  $survey_data = get_option($option_name, array('options' => array(), 'totalUsers' => 0));

		  $cookie_name = $widgets['widget_id'].'-voted';

		  $timediff = strtotime("now") - strtotime($date);
      $widget_payload = array(
        'options'        => $args['options'],
        'allow_multiple' => $allow_multiple,
        'max_choices'    => $max_choices,
      );

      echo kanews_render_survey_form_html( array(
        'options'        => $args['options'],
        'survey_data'    => $survey_data,
        'widget_id'      => $widgets['widget_id'],
        'cookie_name'    => $cookie_name,
        'allow_multiple' => $allow_multiple,
        'max_choices'    => $max_choices,
        'timediff'       => $timediff,
        'widget_payload' => $widget_payload,
        'expires_at'     => $date,
      ) );

		  // Format date for display
		  $display_date = date('d/m/Y', strtotime($date));
		  
		  if( $timediff > 0 ) {
			  echo '<p class="p-1 mb-0">Bu anket sonlanmıştır.</p>';
		  } else {
			  echo '<p class="p-1 mb-0">Bu anket ' . esc_html( $display_date ) . ' tarihinde sonlanacaktır.</p>';
		  }
	  }

      echo '</div></div>';
      
    
    }
  }
}

if ( ! function_exists( 'kanews_get_survey_user_votes' ) ) {
  /**
   * Returns sanitized vote slugs stored in the survey cookie.
   *
   * @param string $cookie_name
   *
   * @return array
   */
  function kanews_get_survey_user_votes( $cookie_name ) {
    if ( empty( $cookie_name ) || ! isset( $_COOKIE[ $cookie_name ] ) ) {
      return array();
    }

    $raw_cookie = wp_unslash( $_COOKIE[ $cookie_name ] );
    $decoded    = json_decode( $raw_cookie, true );
    $votes      = array();

    if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
      $sources = $decoded;
    } else {
      $sources = array( $raw_cookie );
    }

    foreach ( (array) $sources as $vote_slug ) {
      $vote_slug = sanitize_title( $vote_slug );
      if ( '' !== $vote_slug ) {
        $votes[] = $vote_slug;
      }
    }

    return array_values( array_unique( $votes ) );
  }
}

if ( ! function_exists( 'kanews_render_survey_form_html' ) ) {
  /**
   * Renders the survey form HTML for both widget and AJAX responses.
   *
   * @param array $config
   *
   * @return string
   */
  function kanews_render_survey_form_html( $config ) {
    $defaults = array(
      'options'        => array(),
      'survey_data'    => array( 'options' => array(), 'totalUsers' => 0 ),
      'widget_id'      => '',
      'cookie_name'    => '',
      'allow_multiple' => false,
      'max_choices'    => 1,
      'timediff'       => 0,
      'widget_payload' => array(),
      'expires_at'     => '',
    );

    $config         = wp_parse_args( $config, $defaults );
    $options        = is_array( $config['options'] ) ? $config['options'] : array();
    $counts         = isset( $config['survey_data']['options'] ) && is_array( $config['survey_data']['options'] ) ? $config['survey_data']['options'] : array();
    $total_votes    = array_sum( $counts );
    $user_votes     = kanews_get_survey_user_votes( $config['cookie_name'] );
    $form_classes   = array( 'p-1' );
    $allow_multiple = (bool) $config['allow_multiple'];
    $max_choices    = $allow_multiple ? max( 1, absint( $config['max_choices'] ) ) : 1;

    if ( ! empty( $user_votes ) ) {
      $form_classes[] = 'kanews-survey-voted-x';
    }

    if ( $total_votes > 0 ) {
      $form_classes[] = 'kanews-survey-has-votes';
    }

    if ( $allow_multiple ) {
      $form_classes[] = 'kanews-survey-multi';
    }

    $widget_payload = ! empty( $config['widget_payload'] ) ? $config['widget_payload'] : array( 'options' => $options );
    if ( empty( $widget_payload['options'] ) ) {
      $widget_payload['options'] = $options;
    }

    $form  = '<form id="kanews-survey-submit" class="' . esc_attr( implode( ' ', array_filter( array_unique( $form_classes ) ) ) ) . '" method="post" data-expired="' . esc_attr( $config['expires_at'] ) . '" data-widget-name="' . esc_attr( $config['widget_id'] ) . '" data-widget="' . esc_attr( wp_json_encode( $widget_payload ) ) . '" data-multi="' . esc_attr( $allow_multiple ? '1' : '0' ) . '" data-multi-limit="' . esc_attr( $max_choices ) . '">';
    $form .= '<input type="hidden" name="kanews_multi_vote" value="' . esc_attr( $allow_multiple ? '1' : '0' ) . '">';
    $form .= '<input type="hidden" name="kanews_multi_vote_limit" value="' . esc_attr( $max_choices ) . '">';

    if ( $allow_multiple && $config['timediff'] < 0 ) {
      $form .= '<p class="kanews-survey-helper mb-2">' . sprintf( esc_html__( 'En fazla %s seçenek seçebilirsiniz.', 'kanews' ), esc_html( $max_choices ) ) . '</p>';
    }

    if ( is_array( $options ) && ! empty( $options ) ) {
      foreach ( $options as $index => $option ) {
        $title = isset( $option['title'] ) ? trim( wp_strip_all_tags( $option['title'] ) ) : '';

        if ( '' === $title ) {
          continue;
        }

        $option_slug   = sanitize_title( $title );
        $vote_count    = isset( $counts[ $option_slug ] ) ? absint( $counts[ $option_slug ] ) : 0;
        $vote_percent  = ( $total_votes > 0 ) ? round( ( $vote_count / $total_votes ) * 100, 2 ) : 0;
        $vote_color    = ( isset( $option['color'] ) && '' !== $option['color'] ) ? ' style="--kan-theme-color:' . esc_attr( $option['color'] ) . ';"' : '';
        $vote_img      = '';
        $thumb         = isset( $option['img']['thumbnail'] ) ? esc_url( $option['img']['thumbnail'] ) : '';
        $item_selected = in_array( $option_slug, $user_votes, true ) ? ' kanews-survey-selected' : '';
        $input_name    = $allow_multiple ? $config['widget_id'] . '-vote[]' : $config['widget_id'] . '-vote';
        $input_id      = $config['widget_id'] . '-' . $option_slug . '-' . ( $index + 1 );
        $input_type    = $allow_multiple ? 'checkbox' : 'radio';
        $input_attr    = ( $config['timediff'] < 0 ) ? ' required="required"' : '';

        if ( $thumb ) {
          $vote_img = '<span class="kanews-survey-item-thumb"><img loading="lazy" src="' . $thumb . '" width="32" height="32" alt="' . esc_attr( $title ) . '"></span>';
        }

        if ( $allow_multiple ) {
          $input_attr = '';
        }

        $form .= '<div class="kanews-survey-item no-gutters' . $item_selected . '"' . $vote_color . '>';

        $form .= '<div class="kanews-survey-item-top d-flex justify-content-between align-items-center">';
        $form .= '<div class="kanews-survey-item-label">';

        if ( $config['timediff'] < 0 ) {
          $form .= '<input type="' . esc_attr( $input_type ) . '" id="' . esc_attr( $input_id ) . '" name="' . esc_attr( $input_name ) . '" value="' . esc_attr( $option_slug ) . '"' . $input_attr . '>';
        }

        $form .= '<label class="mb-0" for="' . esc_attr( $input_id ) . '">' . $vote_img . '<span>' . esc_html( $title ) . '</span></label>';
        $form .= '</div>';
        $form .= '<div class="kanews-survey-item-result"><span class="kanews-survey-item-per">%' . esc_html( $vote_percent ) . '</span><span class="kanews-survey-item-count">' . sprintf( esc_html__( '%s oy', 'kanews' ), esc_html( $vote_count ) ) . '</span></div>';
        $form .= '</div>';

        $form .= '<div class="kanews-survey-bar"><div class="kanews-survey-bar-current" style="width:' . esc_attr( $vote_percent ) . '%"></div></div>';
        $form .= '</div>';
      }
    } else {
      $form .= '<div class="kanews-response bg-warning">' . esc_html__( 'Henüz anket seçeneği tanımlanmadı.', 'kanews' ) . '</div>';
    }

    if ( $config['timediff'] < 0 ) {
      $form .= '<button type="submit" name="kanews-survey-submit" class="kanews-btn kanews-btn-sm">' . esc_html__( 'Oy Kullan', 'kanews' ) . '<div id="kanews-loader"></div></button>';
    }

    $form .= '</form>';

    return $form;
  }
}

/*-----------------------------------------------------------------------------------*/
add_action( 'wp_ajax_nopriv_kanews_survey_ajax_callback', 'kanews_survey_ajax_callback' );
add_action( 'wp_ajax_kanews_survey_ajax_callback', 'kanews_survey_ajax_callback' );
function kanews_survey_ajax_callback(){
  // Security check
  $nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( $_REQUEST['nonce'] ) : '';
  if ( ! wp_verify_nonce( $nonce, 'kanews-ajax-nonce' ) ) {
    wp_send_json_error( array( 'message' => esc_html__( 'İzin verilmedi!', 'kanews' ) ) );
    exit();
  }
  
  // Validate and sanitize inputs
  $widget_name = isset( $_REQUEST['widget_name'] ) ? sanitize_text_field( $_REQUEST['widget_name'] ) : '';
  if ( empty( $widget_name ) ) {
    wp_send_json_error( array( 'message' => esc_html__( 'Geçersiz anket!', 'kanews' ) ) );
    exit();
  }

  $data_name = $widget_name . '-results';
  $cookie_name = $widget_name . '-voted';
  
  // Get widget configuration
  $widget_data_raw = isset( $_REQUEST['widget_data'] ) ? wp_unslash( $_REQUEST['widget_data'] ) : '';
  $widget_config = json_decode( $widget_data_raw, true );
  
  if ( ! is_array( $widget_config ) || empty( $widget_config['options'] ) ) {
    wp_send_json_error( array( 'message' => esc_html__( 'Anket yapılandırması geçersiz!', 'kanews' ) ) );
    exit();
  }

  $allow_multiple = isset( $widget_config['allow_multiple'] ) && $widget_config['allow_multiple'];
  $max_choices = $allow_multiple ? max( 2, absint( $widget_config['max_choices'] ?? 2 ) ) : 1;

  // Check expiration
  $expired_date = isset( $_REQUEST['expired'] ) ? sanitize_text_field( $_REQUEST['expired'] ) : '';
  if ( empty( $expired_date ) ) {
    wp_send_json_error( array( 'message' => esc_html__( 'Anket tarihi belirtilmemiş!', 'kanews' ) ) );
    exit();
  }

  $timediff = strtotime( 'now' ) - strtotime( $expired_date );
  if ( $timediff > 0 ) {
    wp_send_json_error( array( 'message' => esc_html__( 'Anket tamamlandı, oyun geçersiz!', 'kanews' ) ) );
    exit();
  }

  // Get votes
  $vote_key = $widget_name . '-vote';
  $votes_raw = isset( $_POST[ $vote_key ] ) ? $_POST[ $vote_key ] : array();
  
  // Normalize to array
  if ( ! is_array( $votes_raw ) ) {
    $votes_raw = array( $votes_raw );
  }

  // Sanitize votes
  $votes = array();
  foreach ( $votes_raw as $vote ) {
    $vote = sanitize_title( $vote );
    if ( ! empty( $vote ) ) {
      $votes[] = $vote;
    }
  }

  // Validate votes
  if ( empty( $votes ) ) {
    wp_send_json_error( array( 'message' => esc_html__( 'Lütfen en az bir seçenek seçin!', 'kanews' ) ) );
    exit();
  }

  // Check max choices limit
  if ( count( $votes ) > $max_choices ) {
    wp_send_json_error( array( 'message' => sprintf( esc_html__( 'En fazla %d seçenek seçebilirsiniz!', 'kanews' ), $max_choices ) ) );
    exit();
  }

  // Check if user already voted
  $user_votes = kanews_get_survey_user_votes( $cookie_name );
  if ( ! empty( $user_votes ) ) {
    wp_send_json_error( array( 'message' => esc_html__( 'Zaten oy kullandınız!', 'kanews' ) ) );
    exit();
  }

  // Validate that all votes are valid options
  $valid_options = array();
  foreach ( $widget_config['options'] as $option ) {
    if ( ! empty( $option['title'] ) ) {
      $valid_options[] = sanitize_title( $option['title'] );
    }
  }

  foreach ( $votes as $vote ) {
    if ( ! in_array( $vote, $valid_options, true ) ) {
      wp_send_json_error( array( 'message' => esc_html__( 'Geçersiz seçenek seçildi!', 'kanews' ) ) );
      exit();
    }
  }

  // Save votes to cookie (JSON encoded for multiple votes)
  $cookie_value = $allow_multiple ? wp_json_encode( $votes ) : $votes[0];
  $cookie_expires = strtotime( $expired_date );
  
  // Set cookie with proper domain handling
  $domain = isset( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : '';
  if ( ! empty( $domain ) ) {
    setcookie( $cookie_name, $cookie_value, $cookie_expires, '/', $domain, is_ssl(), true );
  }
  $_COOKIE[ $cookie_name ] = $cookie_value;

  // Update survey data
  $survey_data = get_option( $data_name, array( 'options' => array(), 'totalUsers' => 0 ) );
  
  if ( ! is_array( $survey_data ) ) {
    $survey_data = array( 'options' => array(), 'totalUsers' => 0 );
  }

  if ( ! isset( $survey_data['options'] ) || ! is_array( $survey_data['options'] ) ) {
    $survey_data['options'] = array();
  }

  // Increment vote counts
  foreach ( $votes as $vote ) {
    if ( isset( $survey_data['options'][ $vote ] ) ) {
      $survey_data['options'][ $vote ]++;
    } else {
      $survey_data['options'][ $vote ] = 1;
    }
  }

  // Increment total users (not votes, to avoid double counting in multi-vote)
  $survey_data['totalUsers']++;

  // Save updated data
  update_option( $data_name, $survey_data );

  // Render updated form
  $render_config = array(
    'options'        => $widget_config['options'],
    'survey_data'    => $survey_data,
    'widget_id'      => $widget_name,
    'cookie_name'    => $cookie_name,
    'allow_multiple' => $allow_multiple,
    'max_choices'    => $max_choices,
    'timediff'       => $timediff,
    'widget_payload' => $widget_config,
    'expires_at'     => $expired_date,
  );

  $form = kanews_render_survey_form_html( $render_config );

  wp_send_json_success( array( 
    'message' => esc_html__( 'Oy kullanıldı!', 'kanews' ),
    'content' => $form 
  ) );
  exit();
}