<?php

/**
 * The functionality of the module.
 *
 * @package    Exercise
 * @author     Tim Mallwitz <tim.mallwitz@th-luebeck.de>
 */

 class Trainingssystem_Plugin_Module_Avatar {

    /**
    * BACKEND
    * Adding the meta boxes to the edit page
    */
    public function add_avatar_meta_box(){
        add_meta_box("avatar-option-meta-box", "Avatar-Optionen", array($this, "custom_avatar_options_meta_box_markup"), "avatare", "normal", "high", null);
    }

    /**
    * BACKEND 
    * Add the avatar options box
    */

    public function custom_avatar_options_meta_box_markup(){

        global $post;
        $avatarImage = get_post_meta($post->ID, 'tspv2_avatar_image', true);
        $avatarimageDec = json_decode($avatarImage);
        $avatarGif = get_post_meta($post->ID, 'tspv2_avatar_gif', true);
        $avatarGifDec = json_decode($avatarGif);
        $isDefaultAvatar = get_post_meta($post->ID, 'tspv2_default_avatar', true);

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        
        echo $twig->render('avatar/backend-avatar-options.html', [
            "postid" => $post->ID,
            "avatarImage" => $avatarimageDec,
            "avatarGif" => $avatarGifDec,
            "is_default_avatar" => $isDefaultAvatar
        ]);
    }

    /**
    * BACKEND
    * Function to save the options for an avatar
    */

    public function saveAvatarOptions(){

        if(isset($_POST['postid']) && is_numeric($_POST['postid']) && 
            isset($_POST['avatarImage']) && strlen(trim($_POST['avatarImage'])) > 1 &&
            isset($_POST['avatarGif']) && strlen(trim($_POST['avatarGif'])) > 1 &&
            isset($_POST['isDefaultAvatar']) && ($_POST['isDefaultAvatar'] == "false" || $_POST['isDefaultAvatar'] == "true")){

            $postid = $_POST['postid'];
            $avatarImageStr = $_POST['avatarImage'];
            $avatarGifStr = $_POST['avatarGif'];
            $isDefaultAvatar = $_POST['isDefaultAvatar'] == "false" ? false : true;

            $avatarImage = json_decode(stripslashes($avatarImageStr), true);
            $avatarGif = json_decode(stripslashes($avatarGifStr), true);

            if(is_string(get_post_status($postid)) && json_last_error() === JSON_ERROR_NONE){
                update_post_meta($postid, 'tspv2_avatar_image', json_encode($avatarImage));
                update_post_meta($postid, 'tspv2_avatar_gif', json_encode($avatarGif));
                // Check for old default avatar
                $args = array(
                    'post_type' => 'avatare',
                    'post_status' => 'publish',
                    'numberposts' => 1,
                    'meta_query' => array(
                        array(
                            'key' => 'tspv2_default_avatar'
                        )
                    )
                );

                $query = new WP_Query($args);
                $oldDefaultAvatarPost = $query->posts;

                $oldDefaultAvatarId = "";

                if(!empty($oldDefaultAvatarPost)){
                    foreach($oldDefaultAvatarPost as $defaultAvatar){
                        $oldDefaultAvatarId = $defaultAvatar->ID;
                    }
                }
                if($isDefaultAvatar){

                    if($oldDefaultAvatarId == ""){
                        update_post_meta($postid, 'tspv2_default_avatar', $isDefaultAvatar);
                    }
                    else{
                        // delete the old default avatar entry, write an entry for the current avatar
                        if($oldDefaultAvatarId != $postid){
                            delete_post_meta($oldDefaultAvatarId, 'tspv2_default_avatar');
                            update_post_meta($postid, 'tspv2_default_avatar', $isDefaultAvatar);
                        }
                    }
                }
                else{
                    // delete default avatar entry for current avatar
                    if($oldDefaultAvatarId == $postid){
                        delete_post_meta($oldDefaultAvatarId, 'tspv2_default_avatar');
                    }
                }
            }
        }
        wp_die();
    }

    /**
    * FRONTEND
    * Displays all available avatars
    */
       
    public function showAvatarOverview($atts){

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        $uid = get_current_user_id();

        if(0 !== $uid){

            $mode = "table";
            if(isset($atts['mode']) && trim($atts['mode']) != ""){
                $mode = trim($atts['mode']);
            }

            $showBorder = true;
            if(isset($atts['show_border']) && trim($atts['show_border']) != ""){
                if(trim($atts['show_border']) == "0" || trim($atts['show_border']) == "false"){
                    $showBorder = false;
                }
            }

            $showAvatarTitle = true;
            if(isset($atts['show_avatar_title']) && trim($atts['show_avatar_title']) != ""){
                if(trim($atts['show_avatar_title']) == "0" || trim($atts['show_avatar_title']) == "false"){
                    $showAvatarTitle = false;
                }
            }

            $posts = get_posts([
                'post_type' => 'avatare',
                'post_status' => 'publish',
                'numberposts' => -1
            ]);

            $avatare = array();
            foreach($posts as $post){
                $avatar = array();
                $avatar['title'] = $post->post_title;
                $avatar['id'] = $post->ID;
                $avatar['image_url'] = "";
                $avatar['gif_url'] = "";
                $avatar['selected'] = false;

                $avatarImage = get_post_meta($post->ID, 'tspv2_avatar_image', true);
                if(isset($avatarImage)){
                    $avatarImageDec = json_decode($avatarImage);
                    if(isset($avatarImageDec->url)){
                        if($avatarImageDec->url != ""){
                            $avatar['image_url'] = $avatarImageDec->url;
                        }
                    }

                }
                    
                $avatarGif = get_post_meta($post->ID, 'tspv2_avatar_gif', true);
                if(isset($avatarGif)){
                    $avatarGifDec = json_decode($avatarGif);
                    if(isset($avatarGifDec->url)){
                        if($avatarGifDec->url != ""){
                            $avatar['gif_url'] = $avatarGifDec->url;
                        }
                    }
                }

                $selectedAvatarId = get_user_meta($uid, 'tspv2_my_avatar', true);
                if(isset($selectedAvatarId)){
                    if(trim($selectedAvatarId) != ""){
                        if(trim($selectedAvatarId == $post->ID)){
                            $avatar['selected'] = true;
                        }
                    }
                }
                $avatare[] = $avatar;
            }
            $defaultimglink = get_header_image();

            return $twig->render('avatar/avatar-overview.html', [
                "mode" => $mode,
                "avatare" => $avatare,
                "defaultimglink" => $defaultimglink,
                "showBorder" => $showBorder,
                "showAvatarTitle" => $showAvatarTitle
            ]);
        }
        else{
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }
    /**
    * AJAX/FRONTEND
    * Called when a user clicks the select button on the frontend
    */
    public function selectAvatar(){

        if(isset($_POST['avatarid']) && is_numeric($_POST['avatarid']) && get_post_type($_POST['avatarid']) == "avatare"){

            $userid = get_current_user_id();
            $avatarid = $_POST['avatarid'];
            update_user_meta($userid, 'tspv2_my_avatar', $avatarid);
        }
        wp_die();
    }

    /**
    * FRONTEND
    * Displays the user's avatar/default avatar
    */
    public function showMyAvatar($atts){

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        $uid = get_current_user_id();

        $defaultimglink = get_header_image();

        $showBorder = true;
        if(isset($atts['show_border']) && trim($atts['show_border']) != ""){
            if(trim($atts['show_border']) == "0" || trim($atts['show_border']) == "false"){
                $showBorder = false;
            }
        }

        $showAvatarTitle = true;
        if(isset($atts['show_avatar_title']) && trim($atts['show_avatar_title']) != ""){
            if(trim($atts['show_avatar_title']) == "0" || trim($atts['show_avatar_title']) == "false"){
                $showAvatarTitle = false;
            }
        }

        $editAvatarURL = "";
        if(isset($atts['edit_avatar_url']) && trim($atts['edit_avatar_url']) != ""){
            $editAvatarURL = $atts['edit_avatar_url'];
        }
            
        $avatarMode = "image";
        if(isset($atts['avatar_mode']) && trim($atts['avatar_mode']) != ""){
            $avatarMode = trim($atts['avatar_mode']);
        }
        
        if(0 !== $uid){

            // Check for selected avatar
            $selectedAvatarId = get_user_meta($uid, 'tspv2_my_avatar', true);
            if(isset($selectedAvatarId) && trim($selectedAvatarId) != ""){
                $post = get_post(trim($selectedAvatarId));
                
                //Check if selected avatar exists
                if(!is_null($post) && $post->post_status == 'publish'){
                    $avatar = array();
                    $avatar['title'] = $post->post_title;
                    $avatar['id'] = $post->ID;
                    $avatar['image_url'] = "";
                    $avatar['gif_url'] = "";

                    $avatarImage = get_post_meta($post->ID, 'tspv2_avatar_image', true);
                    if(isset($avatarImage)){
                        $avatarImageDec = json_decode($avatarImage);
                        if(isset($avatarImageDec->url)){
                            if($avatarImageDec->url != ""){
                                $avatar['image_url'] = $avatarImageDec->url;
                            }
                        }

                    }
                    
                    $avatarGif = get_post_meta($post->ID, 'tspv2_avatar_gif', true);
                    if(isset($avatarGif)){
                        $avatarGifDec = json_decode($avatarGif);
                        if(isset($avatarGifDec->url)){
                            if($avatarGifDec->url != ""){
                                $avatar['gif_url'] = $avatarGifDec->url;
                            }
                        }
                    }


                    return $twig->render('avatar/avatar-selected.html', [
                        "avatar" => $avatar,
                        "defaultimglink" => $defaultimglink,
                        "showBorder" => $showBorder,
                        "showAvatarTitle" => $showAvatarTitle,
                        "editAvatarURL" => $editAvatarURL,
                        "avatarMode" => $avatarMode
                    ]);
                }
                else{
                    // Check for default avatar
                    $args = array(
                        'post_type' => 'avatare',
                        'post_status' => 'publish',
                        'numberposts' => 1,
                        'meta_query' => array(
                            array(
                                'key' => 'tspv2_default_avatar'
                            )
                        )
                    );

                    $query = new WP_Query($args);
                    $defaultAvatarPost = $query->posts;

                    if(!empty($defaultAvatarPost)){
                        $avatar = array();
                        $avatar['title'] = "";
                        $avatar['id'] = "";
                        $avatar['image_url'] = "";
                        $avatar['gif_url'] = "";
                        foreach($defaultAvatarPost as $defaultAvatar){
                            $avatar['title'] = $defaultAvatar->post_title;
                            $avatar['id'] = $defaultAvatar->ID;

                            $avatarImage = get_post_meta($defaultAvatar->ID, 'tspv2_avatar_image', true);
                            if(isset($avatarImage)){
                                $avatarImageDec = json_decode($avatarImage);
                                if(isset($avatarImageDec->url)){
                                    if($avatarImageDec->url != ""){
                                        $avatar['image_url'] = $avatarImageDec->url;
                                    }
                                }
        
                            }
                            
                            $avatarGif = get_post_meta($defaultAvatar->ID, 'tspv2_avatar_gif', true);
                            if(isset($avatarGif)){
                                $avatarGifDec = json_decode($avatarGif);
                                if(isset($avatarGifDec->url)){
                                    if($avatarGifDec->url != ""){
                                        $avatar['gif_url'] = $avatarGifDec->url;
                                    }
                                }
                            }
                        }

                        return $twig->render('avatar/avatar-selected.html', [
                            "avatar" => $avatar,
                            "defaultimglink" => $defaultimglink,
                            "showBorder" => $showBorder,
                            "showAvatarTitle" => $showAvatarTitle,
                            "editAvatarURL" => $editAvatarURL,
                            "avatarMode" => $avatarMode
                        ]);

                    }
                }
                
            }
            else{
                // Check for default avatar
                $args = array(
                    'post_type' => 'avatare',
                    'post_status' => 'publish',
                    'numberposts' => 1,
                    'meta_query' => array(
                        array(
                            'key' => 'tspv2_default_avatar'
                        )
                    )
                );

                $query = new WP_Query($args);
                $defaultAvatarPost = $query->posts;

                if(!empty($defaultAvatarPost)){
                    $avatar = array();
                    $avatar['title'] = "";
                    $avatar['id'] = "";
                    $avatar['image_url'] = "";
                    $avatar['gif_url'] = "";
                    foreach($defaultAvatarPost as $defaultAvatar){
                        $avatar['title'] = $defaultAvatar->post_title;
                        $avatar['id'] = $defaultAvatar->ID;

                        $avatarImage = get_post_meta($defaultAvatar->ID, 'tspv2_avatar_image', true);
                        if(isset($avatarImage)){
                            $avatarImageDec = json_decode($avatarImage);
                            if(isset($avatarImageDec->url)){
                                if($avatarImageDec->url != ""){
                                    $avatar['image_url'] = $avatarImageDec->url;
                                }
                            }
        
                        }
                            
                        $avatarGif = get_post_meta($defaultAvatar->ID, 'tspv2_avatar_gif', true);
                        if(isset($avatarGif)){
                            $avatarGifDec = json_decode($avatarGif);
                            if(isset($avatarGifDec->url)){
                                if($avatarGifDec->url != ""){
                                    $avatar['gif_url'] = $avatarGifDec->url;
                                }
                            }
                        }
                    }

                    return $twig->render('avatar/avatar-selected.html', [
                        "avatar" => $avatar,
                        "defaultimglink" => $defaultimglink,
                        "showBorder" => $showBorder,
                        "showAvatarTitle" => $showAvatarTitle,
                        "editAvatarURL" => $editAvatarURL,
                        "avatarMode" => $avatarMode
                    ]);

                }
            }
        }
        else{
            // Check for default avatar
            $args = array(
                'post_type' => 'avatare',
                'post_status' => 'publish',
                'numberposts' => 1,
                'meta_query' => array(
                    array(
                        'key' => 'tspv2_default_avatar'
                    )
                )
            );

            $query = new WP_Query($args);
            $defaultAvatarPost = $query->posts;

            if(!empty($defaultAvatarPost)){
                $avatar = array();
                $avatar['title'] = "";
                $avatar['id'] = "";
                $avatar['image_url'] = "";
                $avatar['gif_url'] = "";
                foreach($defaultAvatarPost as $defaultAvatar){
                    $avatar['title'] = $defaultAvatar->post_title;
                    $avatar['id'] = $defaultAvatar->ID;

                    $avatarImage = get_post_meta($defaultAvatar->ID, 'tspv2_avatar_image', true);
                    if(isset($avatarImage)){
                        $avatarImageDec = json_decode($avatarImage);
                        if(isset($avatarImageDec->url)){
                            if($avatarImageDec->url != ""){
                                $avatar['image_url'] = $avatarImageDec->url;
                            }
                        }
    
                    }
                        
                    $avatarGif = get_post_meta($defaultAvatar->ID, 'tspv2_avatar_gif', true);
                    if(isset($avatarGif)){
                        $avatarGifDec = json_decode($avatarGif);
                        if(isset($avatarGifDec->url)){
                            if($avatarGifDec->url != ""){
                                $avatar['gif_url'] = $avatarGifDec->url;
                            }
                        }
                    }
                }

                return $twig->render('avatar/avatar-selected.html', [
                    "avatar" => $avatar,
                    "defaultimglink" => $defaultimglink,
                    "showBorder" => $showBorder,
                    "showAvatarTitle" => $showAvatarTitle,
                    "editAvatarURL" => $editAvatarURL,
                    "avatarMode" => $avatarMode
                ]);

            }
        }
    }
 }