<?php

class Sendy_Shortcode {
	private static $custom_fields;
	private static $translation;
	private static $sendy_recaptcha;
	private static $style_setting;

	function __construct() {
		add_shortcode( 'swp-forms', array( $this, 'shortcode' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'add_sendy_scripts' ) );

		self::$custom_fields = get_option( 'swp_custom_fields' );
		self::$translation = get_option( 'sendy_translation_settings' );
		self::$sendy_recaptcha = get_option( 'sendy_recaptcha' );

	}


	//Plugin starting point.
	public static function setup() {
		$class = __CLASS__;
		new $class;
	}



	function add_sendy_scripts() {

		wp_enqueue_style( 'swpcss', SENDY_WIDGET_PRO_URL. '/css/sendy.css' );
		wp_enqueue_script( 'swpjs', SENDY_WIDGET_PRO_URL. '/js/sendy.js', array( 'jquery' ) );
		wp_localize_script( 'swpjs', 'swp', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
	}

	public  function shortcode( $atts ) {

		if ( empty( $atts['id'] ) ) {
			return 'Please add a form id to your shortcode';
		}
		$form_id = $atts['id'];
		self::$style_setting = get_post_meta( $form_id, 'swp_styler_settings', true );

		$style_setting = self::$style_setting;


		$form_type = isset( $style_setting['form_type'] )?$style_setting['form_type']:'subscribe';

		$redirect_url = !isset( $style_setting['redirect_url'] ) ? get_option( 'sendy_redirect_url' ):$style_setting['redirect_url'];
		$email_error = !isset( $style_setting['translation']['email_error'] ) ? self::$translation['email_error']:$style_setting['translation']['email_error'];
		$already_subscribed = !isset( $style_setting['translation']['already_subscribed'] ) ?self::$translation['already_subscribed']:$style_setting['translation']['already_subscribed'];
		if ( $form_type == 'subscribe' ) {
			$success_message = !isset( $style_setting['translation']['subscribe_success_message'] ) ? self::$translation['success_message']:$style_setting['translation']['subscribe_success_message'];
		}else {
			$success_message = !isset( $style_setting['translation']['unsubscribe_success_message'] ) ? self::$translation['success_message']:$style_setting['translation']['unsubscribe_success_message'];
		}


		$current_row=1;
		$html ='';
		//debug( !empty(  $style_setting['field_layout']  ) &&  $style_setting['field_layout']!='[]'  );
		if ( !empty(  $style_setting['field_layout']  ) &&  $style_setting['field_layout']!='[]'  ) {
			if ( isset( $style_setting['enabled'] ) ) {
				$html .= self::get_styles( $form_id );
			}

			$html .='<div class="swp-form-cont swp-form-cont-'.$form_id.'">';
			$html .='<form class="swp-form swp-form-'.$form_id.'" action="" method="post">';

			$html .='<div class="swp-row">'; // start the row
			$layout_class = new SWP_Form_layout_Settings();
			$layout = $layout_class->get_styler_field_layout_settings( $form_id );
			$sort=array();
			foreach ( $layout as $key => $field_row ) {
				$sorted_fields[$key]=(array)$field_row;
				$sort['row'][$key]=$field_row->row;
				$sort['col'][$key]=$field_row->col;
			}

			array_multisort( $sort['row'], SORT_ASC, $sort['col'], SORT_ASC, $sorted_fields );

			$current_row =1;
			foreach ( $sorted_fields as $field_row ) {
				$field_id = str_replace( 'swp_styler_field_layout_', '', $field_row['key'] );
				$col = $field_row['col'];
				$row = $field_row['row'];
				$offset = $field_row['size_x'];
				if ( $row > $current_row ) {
					// start new row
					$html .='<div class="swpclear" ></div>';
					$html .='</div><div class="swp-row">';
					$current_row =$row;
				}
				// if submit button then  add lists lists before
				if ( $field_id == '3' ) {
					$lists = $style_setting['list'];
					if ( is_array( $lists ) ) {
						$list_html='';
						foreach ( $lists as $listid ) {
							$list_html.='<input type="hidden" name="listid[]" value="'.$listid.'" >';
						}
					}else {
						$list_html =apply_filters( 'swp_forms_list_display', '<input type="hidden" name="listid" value="'.$listid.'" >', $listid );
					}

					$html .=$list_html;
				}

				$html .='<div class=" swp-col swp-col-'.$col.' swp-colsize-'.$offset.'">
				<div class="swp-field-wrap">';
				$html .=self::get_field( $field_id, $form_id );
				$html .='</div>';

				$html .='</div>';

			}
			$html .='<div class="swpclear" ></div>';
			$html .='</div>'; // ends the last row container
			$html .='<input type="hidden" name="form_id" value="'.$form_id.'" >';
			$html .='<input type="hidden" name="form_type" value="'.$form_type.'" >';
			$html .='<input type="hidden" class="redirect_url" value="'.$redirect_url.'" >';
			$html .='<div class="swp-email-valid-error">'.$email_error.'</div>';
			$html .='<div class="swp-email-duplicate-error">'.$already_subscribed.'</div>';
			$html .='<div class="swp-captcha-error">'.self::$translation['captcha_error'].'</div>';
			$html .='<div class="swp-success">'.$success_message.' </div>';
			$html .='</form>'; // end form
			$html .='</div>'; // end form cont
			return $html;
		}
	}

	public static function get_styles( $form_id ) {
		$style_setting = self::$style_setting ;

		$cont_styles = $label_styles = $field_styles = $button_styles='';

		// FORM Container STYLE
		$cont_styles .= empty( $style_setting['width'] ) ? '': 'width:'.$style_setting['width'].';';
		$cont_styles .= empty( $style_setting['height'] ) ? '': 'height:'.$style_setting['height'].';';
		$cont_styles .= empty( $style_setting['border_color'] ) ? '': 'border:'.$style_setting['border_width'].' '.$style_setting['border_style'].' '.$style_setting['border_color'].';';
		$cont_styles .= empty( $style_setting['background_color'] ) ? '': 'background-color:'.$style_setting['background_color'].';';
		$cont_styles .= empty( $style_setting['padding'] ) ? '': 'padding:'.$style_setting['padding'].';';
		$cont_styles .= empty( $style_setting['margin'] ) ? '': 'margin:'.$style_setting['margin'].';';

		// FORM Field STYLE
		$field_styles .= empty( $style_setting['fields']['font_color'] ) ? '': 'color:'.$style_setting['fields']['font_color'].';';
		$field_styles .= empty( $style_setting['fields']['border_color'] ) ? '': 'border:'.$style_setting['fields']['border_width'].' '.$style_setting['fields']['border_style'].' '.$style_setting['fields']['border_color'].';';
		$field_styles .= empty( $style_setting['fields']['background_color'] ) ? '': 'background-color:'.$style_setting['fields']['background_color'].';';
		$field_styles .= empty( $style_setting['fields']['padding'] ) ? '': 'padding:'.$style_setting['fields']['padding'].';';
		$field_styles .= empty( $style_setting['fields']['margin'] ) ? '': 'margin:'.$style_setting['fields']['margin'].';';
		$field_styles .= empty( $style_setting['fields']['width'] ) ? '': 'width:'.$style_setting['fields']['width'].';';
		// FORM LABEL STYLE
		$label_styles .= empty( $style_setting['label']['min_width'] ) ? '': 'min-width:'.$style_setting['label']['min_width'].';';
		$label_styles .= empty( $style_setting['label']['font_color'] ) ? '': 'color:'.$style_setting['label']['font_color'].';';
		$label_styles .= empty( $style_setting['label']['background_color'] ) ? '': 'background-color:'.$style_setting['label']['background_color'].';';

		// Submit Button
		$button_styles .= empty( $style_setting['submit']['width'] ) ? '': 'width:'.$style_setting['submit']['width'].';';
		$button_styles .= empty( $style_setting['submit']['font_color'] ) ? '': 'color:'.$style_setting['submit']['font_color'].';';
		$button_styles .= empty( $style_setting['submit']['background_color'] ) ? '': 'background-color:'.$style_setting['submit']['background_color'].';background-image:none;';
		$button_styles .= empty( $style_setting['submit']['margin'] ) ? '': 'margin:'.$style_setting['submit']['margin'].';';
		$button_styles .= empty( $style_setting['submit']['padding'] ) ? '': 'padding:'.$style_setting['submit']['padding'].';';



		$css = '<style>';
		// Form cont Styles
		$css .= '.swp-form-cont-'.$form_id.'{';
		$css .= $cont_styles;
		$css .= '}';

		// Form label Styles
		$css .= '.swp-form-cont-'.$form_id.' label {';
		$css .= $label_styles;
		$css .= '}';

		// Form field Styles
		$css .= '.swp-form-cont-'.$form_id.' input[type="text"] {';
		$css .= $field_styles;
		$css .= '}';

		// Submit Button Styles
		$css .= '.swp-form-cont-'.$form_id.' .field-submit {';
		$css .= $button_styles;
		$css .= '}';

		$css .= '</style>';

		return $css;


	}

	public static function get_field( $field_id, $form_id ) {
		$trans = self::$translation;
		$recaptcha = self::$sendy_recaptcha;
		$style_setting = self::$style_setting;

		$form_type = isset( $style_setting['form_type'] )? $style_setting['form_type'] : 'subscribe' ;

		// labels
		$name_label = !isset( $style_setting['translation']['name'] ) ? $trans['name'] : $style_setting['translation']['name'];
		$email = !isset( $style_setting['translation']['email'] ) ? $trans['email'] : $style_setting['translation']['email'];
		$subscriber_count_text = !isset( $style_setting['translation']['subsciber_count'] ) ? $trans['subsciber_count'] : $style_setting['translation']['subsciber_count'];
		$recaptcha_label = !isset( $style_setting['translation']['recaptcha_label'] ) ? $trans['recaptcha_label'] : $style_setting['translation']['recaptcha_label'];
		$optin = !isset( $style_setting['translation']['optin'] ) ? $trans['terms_text'] : $style_setting['translation']['optin'];

		if ( $form_type == 'subscribe' ) {
			$subscribe_button = !isset( $style_setting['translation']['subscribe_button'] ) ? $trans['subscribe_button'] : $style_setting['translation']['subscribe_button'];
		}else {
			$subscribe_button = !isset( $style_setting['translation']['unsubscribe_button'] ) ? $trans['subscribe_button'] : $style_setting['translation']['unsubscribe_button'];
		}

		$type = $field_id;
		// Check if it is a custom field
		if ( $field_id != '1' && $field_id != '2' && $field_id != '3' && $field_id != '4' ) {
			$cus_field = self::$custom_fields;

			if ( !empty( $cus_field[$field_id] ) ) {
				$field_data = $cus_field[$field_id];
				$name = $field_data['name'];
				$label = $field_data['label'];
				$options = $field_data['options'];
				$hidden_field_type = $field_data['hidden_field_value'];
				$type = $field_data['type'];
			}
		}
		switch ( $type ) {
			// email
		case '1':
			$field = '<label for="swp-field-'.$field_id.'" >'.$email.' </label>';
			$field .= '<input type="text" name="swp_email" class="field-email swp-field-'.$field_id.'" >';
			break;
			//name
		case '2':
			$field = '<label for="swp-field-'.$field_id.'" >'.$name_label.' </label>';
			$field .= '<input type="text" name="swp_name"  class="field-name swp-field-'.$field_id.'" >';
			break;
			//submit
		case '3':
			//var_dump($trans);
			//$field = '<label for="swp-field-'.$field_id.'" >'.$trans['name'].' </label>';
			$field = '<input type="submit" value="'.$subscribe_button.'" class="field-submit swp-field-'.$field_id.'" >';
			$field .='<img class="swp-spinner" src="'.SENDY_WIDGET_PRO_URL.'/css/img/spinner.gif">';
			break;

		case '4':
			// reCAPTCHA
			$rand =rand();
			if ( !empty( $recaptcha['site_key'] ) && !empty( $recaptcha['secret_key'] ) ) {
				$lan = !empty( $recaptcha['language'] )?$recaptcha['language']:'en';
				$field = '<script src="https://www.google.com/recaptcha/api.js?hl='.$lan.'" async defer></script>';
				$field .= '<label for="swp-field-'.$field_id.'" >'.$recaptcha_label.' </label>';
				$field .= '<div class="g-recaptcha" data-sitekey="'.$recaptcha['site_key'].'"></div>';

			}
			break;
		case '5':
			$terms_link = get_option( 'sendy_terms_link' );

			$field = '<input type="checkbox" class=" swp-terms swp-field-'.$field_id.'"  >';
			if ( !empty( $terms_link ) ) {
				$field .= '<a target="_blank" href="'.$terms_link.'">'.$optin.'</a>';
			}else {
				$field .= $optin;
			}
			break;
		case '6':

			$lists = $style_setting['list'];
			$count = self::get_list_count( $lists );

			$field = '<p id="swp-field-'.$field_id.'" >'.$count.$subscriber_count_text.'</p>';
			break;

		case 'text':
			$field = '<label for="swp-field-'.$field_id.'" >'.$label.' </label>';
			$field .= '<input type="text" name="swp_custom['.$name.']" class="field-'.$type.' swp-field-'.$field_id.'" >';
			break;
		case 'dropdown':
			$field = '<label for="swp-field-'.$field_id.'" >'.$label.' </label>';
			$field .= '<select class="field-'.$type.' swp-field-'.$field_id.'" name="swp_custom['.$name.']"  >';
			if ( !empty( $options ) ) {
				$choices = explode( ',', $options );
				foreach ( $choices as  $value ) {
					$field .= '<option value="'.$value.'" >'.$value.'</option>';
				}
			}
			$field .= '</select>';
			break;
		case 'checkbox':
			$field = '<label for="swp-field-'.$field_id.'" >'.$label.' </label>';
			if ( !empty( $options ) ) {
				$choices = explode( ',', $options );
				foreach ( $choices as  $value ) {

					$field .= '<input type="checkbox" name="swp_custom['.$name.']" value="'.$value.'"  class="field-'.$type.'"  >'.$value;
				}
			}
			break;
		case 'hidden':
			if ( $hidden_field_type == 'ip_address' ) {
				$val = swp_forms_get_ip();
			}
			elseif ( $hidden_field_type == 'date' ) {
				$val = strftime( '%b %d, %G', time() );

			}
			elseif ( $hidden_field_type == 'page_refer' ) {
				$val = isset( $_SERVER['HTTP_REFERER'] )? $_SERVER['HTTP_REFERER']: '' ;
			}
			$val = apply_filters( 'swp_form_hidden_field_value', $val, $form_id, $hidden_field_type );
			$field = '<input type="hidden" name="swp_custom['.$name.']"  class="field-hidden swp-field-'.$field_id.'" value="'.$val.'"  >';

			break;

		default:
			$field ='';
			break;
		}
		return $field;

	}

	public static function get_list_count( $lists ) {
		$sendy_url=get_option( 'sendy_url' );
		$sendy_api_key=get_option( 'sendy_api_key' );
		$sendy_lists=get_option( 'sendy_lists' );

		$count=0;
		if ( $sendy_lists ) {
			$url=$sendy_url.'/api/subscribers/active-subscriber-count.php';

		}
		if ( !is_array( $lists ) ) {
			$lists[0]=$lists;
		}

		if ( $sendy_lists && !empty( $lists ) ) {

			foreach ( $lists as $key => $list_id ) {

				if ( array_key_exists( $list_id, $sendy_lists ) ) {

					$response= wp_remote_post( $url, array( 'body'=>array( 'api_key'=>$sendy_api_key, 'list_id'=>$list_id ) ) );

					if ( is_wp_error( $response ) ) {

						$error_message = $response->get_error_message();

						$count=0;

					} else {

						$count+=$response['body'];
					}
				}

			}

		}

		return $count;
	}


	function cmp( $a, $b ) {
		if ( $a->value == $b->value ) {
			return 0;
		} else {
			return $a->value < $b->value ? 1 : -1; // reverse order
		}
	}




}
