<?php

namespace Simple_Giveaways;

class SG_Customizer {

	protected $defaults = array();

	public function __construct() {
		if ( defined( 'DOING_AJAX' ) || $this->is_customizer() ) {
			$this->defaults = array(
				'sender_name'         => get_bloginfo( 'name' ),
				'sender_email'      => get_bloginfo( 'admin_email' ),
				'template'          => 'boxed',
				'body_bg'           => '#e3e3e3',
				'body_size'         => '680',
				'footer_text'       => '&copy;' . date( 'Y' ) . ' ' . get_bloginfo( 'name' ),
				'footer_aligment'   => 'center',
				'footer_bg'         => '#eee',
				'footer_text_size'  => '12',
				'footer_text_color' => '#777',
				'footer_powered_by' => 'off',
				'header_aligment'   => 'center',
				'header_bg'         => '#454545',
				'header_text_size'  => '30',
				'header_text_color' => '#f1f1f1',
				'email_body_bg'     => '#fafafa',
				'body_text_size'    => '14',
				'body_text_color'   => '#888',
				'body_href_color'   => '#4ca6cf',
				'custom_css'        => '',
			);
		}

		add_action( 'customize_register', array( $this, 'register_customize_sections' ) );
		add_filter( 'customize_section_active', array( $this, 'remove_other_sections' ), 999, 2 );
		add_filter( 'customize_panel_active', array( $this, 'remove_other_panels' ), 999, 2 );
		add_action( 'template_include', array( $this, 'capture_customizer_page' ), 30000 );
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'customize_preview_init', array( $this, 'enqueue_template_scripts' ), 99 );
		add_action( 'init', array( $this, 'remove_all_actions' ), 999 );

	}

	public function is_customizer() {
		return isset( $_GET['sg_customizer'] ) && Helpers::unslash_and_clean( $_GET['sg_customizer'] );
	}

	/**
	 * Add all panels to customizer
	 *
	 * @param $wp_customize
	 */
	public function register_customize_sections( $wp_customize ) {
		if ( ! defined( 'DOING_AJAX' ) && ! $this->is_customizer() ) {
			return;
		}

		include_once 'customizer/class-sg-customizer-tinymce-control.php';

		$wp_customize->add_panel(
			'sg_mailtpl',
			array(
				'title'       => __( 'Giveaway Emails', 'email-templates' ),
				'description' => __( 'Within the Email Templates customizer you can change how your WordPress Emails looks. It\'s fully compatible with WooCommerce and Easy Digital Downloads html emails', 'email-templates' ),
			)
		);

		do_action( 'sg_customizer_sections_before', $wp_customize );

		// Add sections
		$wp_customize->add_section(
			'section_sg_mailtpl_settings',
			array(
				'title' => __( 'Global Settings', 'email-templates' ),
				'panel' => 'sg_mailtpl',
			)
		);

		$wp_customize->add_section(
			'section_sg_mailtpl_subscriber',
			array(
				'title' => __( 'Subscriber Email Settings', 'email-templates' ),
				'panel' => 'sg_mailtpl',
			)
		);

		$wp_customize->add_section(
			'section_sg_mailtpl_layout',
			array(
				'title' => __( 'Layout', 'email-templates' ),
				'panel' => 'sg_mailtpl',
			)
		);

		$wp_customize->add_section(
			'section_sg_mailtpl_test',
			array(
				'title' => __( 'Send test email', 'email-templates' ),
				'panel' => 'sg_mailtpl',
			)
		);
		// Populate sections
		$this->settings_section( $wp_customize );
		$this->subscriber_section( $wp_customize );
		$this->layout_section( $wp_customize );
		/*
		$this->test_section( $wp_customize );*/

		do_action( 'sg_customizer_sections_after', $wp_customize );

	}

	/**
	 * Remover other sections
	 *
	 * @param $active
	 * @param $section
	 *
	 * @return bool
	 */
	public function remove_other_sections( $active, $section ) {
		if ( ! defined( 'DOING_AJAX' ) && ! $this->is_customizer() ) {
			return $active;
		}

		return in_array(
			$section->id,
			apply_filters(
				'sg_customizer_sections',
				array(
					'section_sg_mailtpl_footer',
					'section_sg_mailtpl_layout',
					'section_sg_mailtpl_header',
					'section_sg_mailtpl_body',
					'section_sg_mailtpl_test',
					'section_sg_mailtpl_settings',
					'section_sg_mailtpl_subscriber',
				)
			)
		);
	}

	/**
	 * Remover other panels
	 *
	 * @param $active
	 * @param $panel
	 *
	 * @return bool
	 */
	public function remove_other_panels( $active, $panel ) {
		if ( ! $this->is_customizer() ) {
			return $active;
		}

		return $panel->id === 'sg_mailtpl';
	}
	/**
	 * Here we capture the page and show template acordingly
	 *
	 * @param $template
	 *
	 * @return string
	 */
	public function capture_customizer_page( $template ) {

		if ( is_customize_preview() && $this->is_customizer() ) {
			return apply_filters( 'sg_customizer_template', untrailingslashit( GASAP_ROOT ) . '/admin/views/customizer/email.php' );
		}

		return $template;
	}


	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {
		if ( ! $this->is_customizer() ) {
			return;
		}

		wp_enqueue_script( 'sg-customizer-js', trailingslashit( GASAP_URI ) . 'assets/js/admin/customizer-admin.js', array( 'jquery' ), gasap()->version(), true );

		wp_enqueue_editor();

	}

	/**
	 * Enqueue scripts for preview area
	 *
	 * @since 1.0.0
	 */
	public function enqueue_template_scripts() {
		if ( ! $this->is_customizer() ) {
			return;
		}

		// wp_enqueue_script( 'mailtpl-front-js', GASAP_URI . '/admin/js/mailtpl-public.js', array(  'jquery', 'customize-preview' ), $this->version, true );
		// wp_enqueue_style( 'mailtpl-css', GASAP_URI . '/admin/css/mailtpl-admin.css', '', $this->version, false );
	}

	/**
	 * Template Section
	 *
	 * @param $wp_customize \WP_Customize_Manager
	 */
	private function settings_section( $wp_customize ) {

		do_action( 'sg_sections_settings_before_content', $wp_customize );

		$wp_customize->add_setting(
			'giveasap_settings[sender_email]',
			array(
				'type'                 => 'option',
				'default'              => $this->defaults['sender_email'],
				'transport'            => 'postMessage',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_text_field',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Control(
				$wp_customize,
				'sg_mailtpl_from_name',
				array(
					'label'       => __( 'From Email', 'email-templates' ),
					'type'        => 'text',
					'section'     => 'section_sg_mailtpl_settings',
					'settings'    => 'giveasap_settings[sender_email]',
					'description' => __( 'Default: ', 'email-templates' ) . get_bloginfo( 'name' ),
				)
			)
		);

		$wp_customize->add_setting(
			'giveasap_settings[sender_name]',
			array(
				'type'                 => 'option',
				'default'              => $this->defaults['sender_name'],
				'transport'            => 'postMessage',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_text_field',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Control(
				$wp_customize,
				'sg_mailtpl_from_email',
				array(
					'label'       => __( 'From Name', 'email-templates' ),
					'type'        => 'text',
					'section'     => 'section_sg_mailtpl_settings',
					'settings'    => 'giveasap_settings[sender_name]',
					'description' => __( 'Default: ', 'email-templates' ) . get_bloginfo( 'admin_email' ),
				)
			)
		);

		do_action( 'sg_sections_settings_after_content', $wp_customize );
	}

	/**
	 * Template Section
	 *
	 * @param $wp_customize \WP_Customize_Manager
	 */
	private function subscriber_section( $wp_customize ) {

		do_action( 'sg_sections_settings_before_content', $wp_customize );

		$wp_customize->add_setting(
			'giveasap_settings[subscriber_email_subject]',
			array(
				'type'                 => 'option',
				'default'              => '',
				'transport'            => 'postMessage',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_text_field',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Control(
				$wp_customize,
				'sg_mailtpl_subject',
				array(
					'label'    => __( 'Subscriber Subject', 'giveasap' ),
					'type'     => 'text',
					'section'  => 'section_sg_mailtpl_subscriber',
					'settings' => 'giveasap_settings[subscriber_email_subject]',
				)
			)
		);

		$wp_customize->add_setting(
			'giveasap_settings[subscriber_email]',
			array(
				'type'                 => 'option',
				'default'              => $this->defaults['sender_email'],
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'wp_kses_post',
				'sanitize_js_callback' => '',

			)
		);

		$wp_customize->add_control(
			new SG_Customizer_TinyMCE_Control(
				$wp_customize,
				'sg_mailtpl_email',
				array(
					'label'       => __( 'Subscriber Subject', 'giveasap' ),
					'section'     => 'section_sg_mailtpl_subscriber',
					'settings'    => 'giveasap_settings[subscriber_email]',
					'input_attrs' => [
						'toolbar1'     => 'formatselect bold italic link bullist',
						'mediaButtons' => true,
						'height'       => 200,
					],
				)
			)
		);

		do_action( 'sg_sections_settings_after_content', $wp_customize );
	}


	/**
	 * Template Section
	 *
	 * @param $wp_customize \WP_Customize_Manager
	 */
	private function layout_section( $wp_customize ) {
		do_action( 'sg_sections_layout_before_content', $wp_customize );

		$wp_customize->add_setting(
			'giveasap_settings[email_hide_links]',
			array(
				'type'                 => 'option',
				'default'              => '0',
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Control(
				$wp_customize,
				'mailtpl_hide_links',
				array(
					'label'       => __( 'Hide links', 'giveasap' ),
					'type'        => 'select',
					'choices'     => array(
						'0' => 'No',
						'1' => 'Yes',
					),
					'section'     => 'section_sg_mailtpl_layout',
					'settings'    => 'giveasap_settings[email_hide_links]',
					'description' => __( 'This will hide the links in the emails that are automatically generated: Entry, Activation and Share link. You will have to enter them manually in the email content.', 'giveasap' ),
				)
			)
		);

		// body size
		$wp_customize->add_setting(
			'giveasap_settings[email_logo]',
			array(
				'type'                 => 'option',
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Media_Control(
				$wp_customize,
				'mailtpl_image',
				array(
					'label'                => __( 'Email Logo', 'giveasap' ),
					'description'          => __( 'Logo used in the email template', 'giveasap' ),
					'section'              => 'section_sg_mailtpl_layout',
					'settings'             => 'giveasap_settings[email_logo]',
					'sanitize_js_callback' => '',
					'mime_type'            => 'image',
				)
			)
		);

		// body bg
		$wp_customize->add_setting(
			'giveasap_settings[email_background]',
			array(
				'type'                 => 'option',
				'default'              => '#a46497',
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_hex_color',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Color_Control(
				$wp_customize,
				'sg_mailtpl_background_color',
				array(
					'label'    => __( 'Background Color', 'giveasap' ),
					'section'  => 'section_sg_mailtpl_layout',
					'settings' => 'giveasap_settings[email_background]',
				)
			)
		);

		$wp_customize->add_setting(
			'giveasap_settings[email_body_bg]',
			array(
				'type'                 => 'option',
				'default'              => '#fff',
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_hex_color',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Color_Control(
				$wp_customize,
				'sg_mailtpl_body_background_color',
				array(
					'label'       => __( 'Body Background', 'giveasap' ),
					'description' => __( 'Body of the Email where the content will be.', 'giveasap' ),
					'section'     => 'section_sg_mailtpl_layout',
					'settings'    => 'giveasap_settings[email_body_bg]',
				)
			)
		);

		$wp_customize->add_setting(
			'giveasap_settings[email_text_color]',
			array(
				'type'                 => 'option',
				'default'              => '#000000',
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_hex_color',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Color_Control(
				$wp_customize,
				'sg_mailtpl_email_text_color',
				array(
					'label'    => __( 'Text Color', 'giveasap' ),
					'section'  => 'section_sg_mailtpl_layout',
					'settings' => 'giveasap_settings[email_text_color]',
				)
			)
		);

		$wp_customize->add_setting(
			'giveasap_settings[email_link_color]',
			array(
				'type'                 => 'option',
				'default'              => '#61ce70',
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_hex_color',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Color_Control(
				$wp_customize,
				'sg_mailtpl_email_link_color',
				array(
					'label'    => __( 'Link Color', 'giveasap' ),
					'section'  => 'section_sg_mailtpl_layout',
					'settings' => 'giveasap_settings[email_link_color]',
				)
			)
		);

		$wp_customize->add_setting(
			'giveasap_settings[email_button_color]',
			array(
				'type'                 => 'option',
				'default'              => '#ffffff',
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_hex_color',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Color_Control(
				$wp_customize,
				'sg_mailtpl_email_button_color',
				array(
					'label'    => __( 'Button Text Color', 'giveasap' ),
					'section'  => 'section_sg_mailtpl_layout',
					'settings' => 'giveasap_settings[email_button_color]',
				)
			)
		);

		$wp_customize->add_setting(
			'giveasap_settings[email_button_bg_color]',
			array(
				'type'                 => 'option',
				'default'              => '#61ce70',
				'transport'            => 'refresh',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => 'sanitize_hex_color',
				'sanitize_js_callback' => '',
			)
		);

		$wp_customize->add_control(
			new \WP_Customize_Color_Control(
				$wp_customize,
				'sg_mailtpl_email_button_bg_color',
				array(
					'label'    => __( 'Button Background Color', 'giveasap' ),
					'section'  => 'section_sg_mailtpl_layout',
					'settings' => 'giveasap_settings[email_button_bg_color]',
				)
			)
		);

		do_action( 'sg_sections_layout_after_content', $wp_customize );
	}

	/**
	 * Send test email section
	 *
	 * @param $wp_customize \Wp_Customize_Manager
	 */
	private function test_section( $wp_customize ) {

		do_action( 'sg_sections_test_before_content', $wp_customize );

		// image logo
		$wp_customize->add_setting(
			'mailtpl_opts[send_mail]',
			array(
				'type'                 => 'option',
				'default'              => '',
				'transport'            => 'postMessage',
				'capability'           => 'edit_theme_options',
				'sanitize_callback'    => '',
				'sanitize_js_callback' => '',
			)
		);

		do_action( 'sg_sections_test_after_content', $wp_customize );
	}

	/**
	 * We let them use some safe html
	 *
	 * @param $input string to sanitize
	 *
	 * @return string
	 */
	public function sanitize_text( $input ) {
		return wp_kses_post( force_balance_tags( $input ) );
	}


	/**
	 * Sanitize aligment selects
	 *
	 * @param $input string to sanitize
	 *
	 * @return string
	 */
	public function sanitize_alignment( $input ) {
		$valid = array(
			'left',
			'right',
			'center',
		);

		if ( in_array( $input, $valid ) ) {
			return $input;
		} else {
			return '';
		}
	}
	/**
	 * Sanitize template select
	 *
	 * @param $input string to sanitize
	 *
	 * @return string
	 */
	public function sanitize_templates( $input ) {
		$valid = apply_filters(
			'sg_customizer_template_choices',
			array(
				'boxed'     => 'Simple Theme',
				'fullwidth' => 'Fullwidth',
			)
		);

		if ( array_key_exists( $input, $valid ) ) {
			return $input;
		} else {
			return '';
		}
	}

	/**
	 * If we are in our template strip everything out and leave it clean
	 *
	 * @since 1.0.0
	 */
	public function remove_all_actions() {
		global $wp_scripts, $wp_styles;

		if ( ! $this->is_customizer() ) {
			return;
		}

		$exceptions = array(
			'mailtpl-js',
			'jquery',
			'query-monitor',
			'mailtpl-front-js',
			'customize-preview',
			'customize-controls',
		);

		if ( is_object( $wp_scripts ) && isset( $wp_scripts->queue ) && is_array( $wp_scripts->queue ) ) {
			foreach ( $wp_scripts->queue as $handle ) {
				if ( in_array( $handle, $exceptions ) ) {
					continue;
				}
				wp_dequeue_script( $handle );
			}
		}

		if ( is_object( $wp_styles ) && isset( $wp_styles->queue ) && is_array( $wp_styles->queue ) ) {
			foreach ( $wp_styles->queue as $handle ) {
				if ( in_array( $handle, $exceptions ) ) {
					continue;
				}
				wp_dequeue_style( $handle );
			}
		}

		// Now remove actions
		$action_exceptions = array(
			'wp_print_footer_scripts',
			'wp_admin_bar_render',
		);

		// No core action in header
		remove_all_actions( 'wp_header' );

		global $wp_filter;
		foreach ( $wp_filter['wp_footer'] as $priority => $handle ) {
			if ( in_array( key( $handle ), $action_exceptions ) ) {
				continue;
			}
			unset( $wp_filter['wp_footer'][ $priority ] );
		}
	}
}
