<?php
/**
 * Blended Shortcodes.
 *
 * @class    Blended_Shortcodes
 * @author   Blended
 * @package  Blended/Shortcodes
 * @category Class
 * @version  1.0.0
 */
if (!defined('ABSPATH')) {
    exit;
}

class Blended_Shortcodes {

    public static $style;
    public static $script;

    /**
     * Init shortcodes.
     */
    public static function init() {


        $shortcodes = array(
            'blended_gallery' => __CLASS__ . '::blended_gallery',
            'blended_signup' => __CLASS__ . '::blended_signup',
        );

        foreach ($shortcodes as $shortcode => $function) {
            add_shortcode(apply_filters("{$shortcode}_shortcode_tag", $shortcode), $function);
        }
    }

    public static function blended_gallery($atts) {
        extract(shortcode_atts(array(
            'tag' => '',
            'category' => '',
            'layout' => '',
            'count' => ''
                        ), $atts, 'gallery')
        );

        if (isset($layout) && !$layout)
            return __("Please provide layout slug to gallery", "blended");

        return self::include_layout($layout, $atts);
    }

    public static function include_layout($layout, $args = array()) {

        $context = Timber::get_context();
		
		//Return if no layout
		if(!isset($context['theme']['layouts'][$layout]))
			return __("Please provide correct layout slug", "blended");

        //Set style
        self::set_style($context, $layout);

        //Set script
        self::set_script($context, $layout);

        //Add style to layout
        //add_action("wp_head", array(__CLASS__, "layout_styles"));
        //Add script to layout
        add_action("wp_footer", array(__CLASS__, "layout_scripts"));

        //Include Template

        ob_start();

        if (!isset($_REQUEST['__blended_gallery'])):
            //Load style
            self::layout_styles($context);

            $_REQUEST['__blended_gallery'] = true;
        endif;

        Timber::render_string($context['theme']['layouts'][$layout]['template'], array("content" => self::gallery_data($args), "theme" => $context['theme']));

        return ob_get_clean();
    }

    public static function gallery_data(array $args) {


        $query_args = array("post_type" => "blended_gallery");

        //Image count
        $query_args['posts_per_page'] = isset($args['count']) && !empty($args['count']) ? $args['count'] : -1;

        
        //Tax query
        $query_args['tax_query'] = array('relation' => 'OR');
        
        //Tag
        if (isset($args['tag']) && !empty($args['tag'])) {
                
            $terms = (false !== strpos(",", $args['tag']) ?  array($args['tag']) :  explode(",", $args['tag']));
               $query_args['tax_query'][] = array(
			'taxonomy' => 'blended_gallery_tag',
			'field'    => 'slug',
			'terms'    => $terms 
		);
        }

        //Category
        if (isset($args['category']) && !empty($args['category'])) {
             $terms = (false !== strpos(",", $args['category']) ?  array($args['category']) :  explode(",", $args['category']));
               $query_args['tax_query'][] = array(
			'taxonomy' => 'blended_gallery_cat',
			'field'    => 'slug',
			'terms'    => $terms 
		);
        }


        $wp_query = new WP_Query($query_args);
        $data = array();

        while ($wp_query->have_posts()) : $wp_query->the_post();
            //get post thumbnail id
            $image_id = get_post_thumbnail_id();

            $image_small = blended_attachment_image($image_id, 'gallery-list-thumb');

            $image_big = wp_get_attachment_image_src($image_id, 'full', true);

            $data[] = array("small_image" => $image_small ? $image_small : "", "big_image_src" => isset($image_big[0]) ? $image_big[0] : "", "title" => get_the_title());

        endwhile;
        wp_reset_postdata();
        return $data;
    }

    public static function blended_signup() {
        ob_start();
        ?>
        <div class="wrapper">

            <?php
            $err = '';
            $success = '';

            global $PasswordHash, $current_user, $user_ID;

            if (isset($_POST['task']) && $_POST['task'] == 'register') {


                $pwd1 = sanitize_text_field(trim($_POST['pwd1']));
                $pwd2 = sanitize_text_field(trim($_POST['pwd2']));
                $first_name = sanitize_text_field(trim($_POST['first_name']));
                $last_name = sanitize_text_field(trim($_POST['last_name']));
                $email = sanitize_email(trim($_POST['email']));
                $username = sanitize_user(trim($_POST['username']));

                // Check the nonce
                if (empty($_POST['__nonce_blended_signup']) || !wp_verify_nonce($_POST['__nonce_blended_signup'], 'blended_signup')) {
                    $err = __('Invalid submission.', 'blended');
                } else if ($pwd1 === "" || $pwd2 === "" || $username === "" || $first_name === "" || $last_name === "") {
                    $err = __('Please don\'t leave the required fields.', 'blended');
                } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $err = __('Invalid email address.', 'blended');
                } else if (email_exists($email)) {
                    $err = __('Email already exist.', 'blended');
                } else if ($pwd1 <> $pwd2) {
                    $err = __('Password do not match.', 'blended');
                } else {

                    $user_id = wp_insert_user(array('first_name' => apply_filters('pre_user_first_name', $first_name), 'last_name' => apply_filters('pre_user_last_name', $last_name), 'user_pass' => apply_filters('pre_user_user_pass', $pwd1), 'user_login' => apply_filters('pre_user_user_login', $username), 'user_email' => apply_filters('pre_user_user_email', $email), 'role' => 'subscriber'));
                    if (is_wp_error($user_id)) {
                        $err = 'Error on user creation.';
                    } else {
                        do_action('user_register', $user_id);

                        $success = 'You\'re successfully registered';
                    }
                }
            }
            ?>

            <div class="signup-form row">
				<div class="two_thirds-sm two_twelfths_push-sm">
				<!--display error/success message-->
				<div id="message">
					<?php
					if (!empty($err)) :
						echo '<p class="error">' . $err . '';
					endif;
					?>

					<?php
					if (!empty($success)) :
						echo '<p class="error">' . $success . '';
					endif;
					?>
				</div>
				<form method="post">
					<div class="email-form__group">
						<h3>Sign Up Here</h3>
						
						<div class="row">
							<div class="one_half-sm">
								<!--last name form row ends here...--> 
								<div class="email-form__row form__row--lastname">
									<div class="email-form__field email-form__field-label">
									  <label>Last Name <span class="required">*<span></label>
									</div>
									<div class="email-form__field email-form__field-input">
									  <input type="text" value="" name="last_name" id="last_name" />
									</div>
								</div>
								<!--last name form row ends here...--> 
							</div>
							<div class="one_half-sm">
								<!--first name form row ends here...--> 
								<div class="email-form__row form__row--firstname">
									<div class="email-form__field email-form__field-label">
									  <label>First Name <span class="required">*<span></label>
									</div>
									<div class="email-form__field email-form__field-input">
									  <input type="text" value="" name="first_name" id="first_name" />
									</div>
								</div>
								<!--first name form row ends here...-->
							</div>
							
							<div class="one_half-sm">
								<!--Email form row ends here...--> 
								<div class="email-form__row form__row--email">
									<div class="email-form__field email-form__field-label">
									  <label>Email <span class="required">*<span></label>
									</div>
									<div class="email-form__field email-form__field-input">
									  <input type="text" value="" name="email" id="email" />
									</div>
								</div>
								<!--Email form row ends here...-->
							</div>
							
							<div class="one_half-sm">
								<!--username form row ends here...--> 
								<div class="email-form__row form__row--username">
									<div class="email-form__field email-form__field-label">
									  <label>Username <span class="required">*<span></label>
									</div>
									<div class="email-form__field email-form__field-input">
									  <input type="text" value="" name="username" id="username" />
									</div>
								</div>
								<!--username form row ends here...-->
							</div>
							<div class="one_half-sm">
								<!--password form row ends here...--> 
								<div class="email-form__row form__row--password">
									<div class="email-form__field email-form__field-label">
									  <label>Password <span class="required">*<span></label>
									</div>
									<div class="email-form__field email-form__field-input">
									  <input type="password" value="" name="pwd1" id="pwd1" />
									</div>
								</div>
								<!--password form row ends here...-->
							</div>
							
							<div class="one_half-sm">
								<!--Confirm Password form row ends here...--> 
								<div class="email-form__row form__row--confirm-password">
									<div class="email-form__field email-form__field-label">
									  <label>Confirm Password <span class="required">*<span></label>
									</div>
									<div class="email-form__field email-form__field-input">
									  <input type="password" value="" name="pwd2" id="pwd2" />
									</div>
								</div>
								<!--Confirm Password form row ends here...-->
							</div>
							
						</div>
						<div class="row">
							<div class="whole">
								<!--button row starts here...-->
								<div class="email-form__row form__row--btn">
									<div class="email-form__field email-form__field-btn">
										<button type="submit" name="btnregister" class="button btn btn--transparent btn--radius" >Submit</button>
										<input type="hidden" name="task" value="register" />
										<?php
										// Add an nonce field.
										wp_nonce_field('blended_signup', '__nonce_blended_signup');
										?>
									</div>
								</div>
								<!--button form row ends here...--> 
							</div>
						</div>

					</div>
				</form>
				</div>
			</div>

        </div>
        <?php
        return ob_get_clean();
    }

    public static function layout_styles($context) {
        ?>
        <style type="text/css"><?php Timber::render_string(self::$style, array("theme" => $context['theme'])); //echo self::$style;     ?></style>
        <?php
    }

    public static function layout_scripts() {
        ?>
        <script type="text/javascript"><?php echo self::$script; ?></script>
        <?php
    }

    public static function set_style($context, $layout) {

        self::$style = isset($context['theme']['layouts'][$layout]) && $context['theme']['layouts'][$layout]["style"] ? $context['theme']['layouts'][$layout]["style"] : "";
    }

    public static function set_script($context, $layout) {
        self::$script = isset($context['theme']['layouts'][$layout]) && $context['theme']['layouts'][$layout]["script"] ? $context['theme']['layouts'][$layout]["script"] : "";
    }

}

Blended_Shortcodes::init();
