<?php

/*
Battle post type
 */
if (!defined('ABSPATH')) {
    exit;
}
// Exit if accessed directly

new CyberSoldier_User();
class CyberSoldier_User
{

    public function __construct()
    {
        add_action('show_user_profile', [$this, 'cybersoldier_add_2_user_profile']);
        add_action('edit_user_profile', [$this, 'cybersoldier_add_2_user_profile']);
        add_action('init', [$this, 'cybersoldier_add_player']);
        add_action('admin_init', [$this, 'cybersoldier_add_user_caps']);
    }

    static function get_user_url($scid)
    {
        $cybersoldier_url_to_infopage = get_option('cybersoldier_url_to_infopage', 'cybersoldier/');
        if(is_numeric($cybersoldier_url_to_infopage)){
            $page_from_id = get_post($cybersoldier_url_to_infopage);
            $cybersoldier_url_to_infopage = get_permalink($cybersoldier_url_to_infopage);
        }
        else{
            $cybersoldier_url_to_infopage = site_url(esc_attr($cybersoldier_url_to_infopage));
        }
        $user_url = $cybersoldier_url_to_infopage . '?csid=' . esc_attr($scid);
        return $user_url;
    }

    /**
     * Adding stuff to profile page by shortcode
     */
    function cybersoldier_add_2_user_profile()
    {
        echo do_shortcode("[cybersoldier_user_page]");
    }

    /**
     * Player user type
     */
    function cybersoldier_add_player()
    {
        $result = add_role('player', __('Cybersoldier'));
    }


    /**
     * Add capabilites
     */
    function cybersoldier_add_user_caps()
    {
        $role = get_role('player');
        $role->add_cap('read');
        $role->add_cap('edit_battle');
        $role->add_cap('edit_battles');
        //$role->add_cap ( 'edit_published_battles' );
        $role->add_cap('publish_battles');

        $role = get_role('administrator');
        $role->add_cap('read');
        $role->add_cap('edit_battle');
        $role->add_cap('edit_battles');
        $role->add_cap('edit_published_battles');
        $role->add_cap('publish_battles');

        //For admin to be able to battle too.
        $cs_administrator = get_role('administrator');

        foreach (array('publish', 'delete', 'delete_others', 'delete_private', 'delete_published', 'edit', 'edit_others', 'edit_private', 'edit_published', 'read_private') as $cap) {
            $cs_administrator->add_cap("{$cap}_battles");
        }
    }

    /**
     * Get the info abut a specific user.
     * @param int $user_id
     * @return string[]|WP_User[]|false[]|boolean[]
     */
    public static function cybersoldier_user_info($user_id)
    {
        if (!is_numeric($user_id)){
            //error_log("wat, user id is not numba? wwweii $user_id");
            return false;
        }
        global $wpdb;
        $return_array = array();
        $start_user = get_user_by("ID", $user_id);

        $user_url = CyberSoldier_User::get_user_url($user_id);

        $return_array["user"] = $start_user;
        $return_array["user_url"] = $user_url;
        $return_array["battle_list"] = "";

        $query = "
	SELECT p.* FROM   $wpdb->postmeta m JOIN $wpdb->posts p ON p.id = m.post_id
	WHERE  ( m.meta_key = 'invited_user' AND m.meta_value = '$user_id' ) AND p.post_status = 'publish' AND p.post_type='battle'
	UNION DISTINCT SELECT *	FROM   $wpdb->posts p
	WHERE  post_author = $user_id AND p.post_status = 'publish' AND p.post_type='battle'
	GROUP  BY p.id
	ORDER  BY post_date DESC
	";

        $start_user_battles = $wpdb->get_results($query, OBJECT);
        $upload_path_users = wp_upload_dir();

        $image_path = $upload_path_users["basedir"] . "/cybersoldier/users/" . esc_attr($user_id) . '.png';
        $image_url = $upload_path_users["baseurl"] . "/cybersoldier/users/" . esc_attr($user_id) . '.png';

        $return_array["image"] =  file_exists($image_path) ? $image_url : false;


        if ($start_user_battles) {
            foreach ($start_user_battles as $posten) {
                $guid = esc_url($posten->guid);
                $title = esc_attr($posten->post_title);
                $return_array["battle_list"] .= "<div class='battle_box'><a href='$guid'>$title</a></div>";
            }
        }

        return $return_array;
    }

    /**
     * Checking if user is in battle
     * @param int $battle_id
     * @param int $user_id
     * @return boolean
     */

    public static function cybersoldier_in_battle($battle_id, $user_id)
    {
        if (!is_numeric($battle_id) || !is_numeric($user_id))
            return false;
        global $wpdb;
        $query = "
	SELECT p.* FROM   $wpdb->postmeta m JOIN $wpdb->posts p ON p.id = m.post_id
	WHERE  ( m.meta_key = 'invited_user' AND m.meta_value = '$user_id' ) AND p.post_status = 'publish' AND p.post_type='battle' AND p.ID=$battle_id
	UNION DISTINCT SELECT *	FROM   $wpdb->posts p
	WHERE  post_author = $user_id AND p.post_status = 'publish' AND p.post_type='battle' AND p.ID=$battle_id
	GROUP  BY p.id
	ORDER  BY post_date DESC
	";
        $user_battles = $wpdb->get_results($query, OBJECT);
        return count($user_battles, true) > 0;
    }

    /**
     *
     * @param int $battle_id The id of the battle you want
     * @param string $id_only if you only want the id, ids of the users.
     * @param int $opponent_user_id if you only want the opponent of the user in the current battle.
     * @return different
     */
    public static function cybersoldier_users_in_battle($battle_id, $id_only = true, $opponent_user_id = false)
    {
        global $wpdb;

        if (!is_numeric($battle_id))
            return false;
        if (!(is_numeric($opponent_user_id) || is_bool($opponent_user_id)))
            return false;
        /* 	if(is_bool($opponent_user_id))		
		return false;	 */
        $post = get_post($battle_id);
        $author_id = $post->post_author;
        $battle_user_id = get_post_meta($battle_id, "invited_user", true);

        if ($id_only && $opponent_user_id) {
            return $author_id == $opponent_user_id ? $battle_user_id : $author_id;
        } else if (!$id_only && $opponent_user_id) {
            return $author_id == $opponent_user_id 
            ? CyberSoldier_User::cybersoldier_user_info($battle_user_id) 
            : CyberSoldier_User::cybersoldier_user_info($author_id);
        } else if ($id_only)
            return array(
                "start_user" => $author_id, 
                "invited_user" => $battle_user_id
            );

        return array(
            "start_user" => CyberSoldier_User::cybersoldier_user_info($author_id), 
            "invited_user" => CyberSoldier_User::cybersoldier_user_info($battle_user_id)
        );
    }
    /**
     * Get the battles that a user is in.
     * @param unknown $user_id
     * @return object|NULL
     */
    public static function cybersoldier_users_battles($user_id)
    {
        if (!is_numeric($user_id))
            return false;
        global $wpdb;
        $query = "
	SELECT p.* FROM  $wpdb->postmeta m JOIN $wpdb->posts p ON p.id = m.post_id
	WHERE  ( m.meta_key = 'invited_user' AND m.meta_value = '$user_id' ) AND p.post_status = 'publish' AND p.post_type='battle'
	UNION DISTINCT SELECT *	FROM  $wpdb->posts p
	WHERE  post_author = $user_id AND p.post_status = 'publish' AND p.post_type='battle'
	GROUP  BY p.id
	ORDER  BY post_date DESC
	";
        $user_battles = $wpdb->get_results($query, OBJECT);
        return $user_battles;
    }
    /**
     * Get character items
     * @param string $type 
     */
    public static function cybersoldier_character_items($type = "all")
    {
        global $wpdb;
        if (!is_string($type))
            return false;
        $table1 = $wpdb->prefix . "cybersoldier_character_items";
        if ($type == "all") {
            $items_arr = array();
            $sql = "SELECT * FROM $table1 ORDER BY type, name";
            $items = $wpdb->get_results($sql);
            foreach ($items as $item) {
                $type_name = ucfirst($item->type);
                $items_arr[$type_name][] = $item;
            }
            return $items_arr;
        } else {
            $sql = "SELECT * FROM $table1 WHERE type='$type' ORDER BY name";
            return $wpdb->get_results($sql);
        }
        if (isset($sql))
            $items = $wpdb->get_results($sql);

        wp_die();
    }

    //If the user has no cracter items, give him some.
    public static function cybersoldier_give_character_random_items($user_id)
    {
        if (!is_numeric($user_id))
            return false;
       
        $user_metas = get_user_meta($user_id);

        $metas = [
            "shirt" => 2,
            "top" => 5,
            "eyes" => 6,
            "mouth" => 3,
            "pants" => 2,
            "shoes" => 2,
            "accessories" => 3,
            "body" => 0
        ];

        //foreach radom number and a color for each item.
        foreach ($metas as $key => $value) {
            $meta_key = "cybersoldier" . $key;
            $meta_key_color = $meta_key . "_color";
            $meta_value = get_user_meta($user_id, $meta_key, true);
            $meta_value_color = get_user_meta($user_id, $meta_key_color, true);
            if (!$meta_value) {
                $random_html_color = sprintf('%06X', mt_rand(0, 0xFFFFFF));
                if($value != 0)
                    update_user_meta($user_id, $meta_key, rand(1, $value));
                update_user_meta($user_id, $meta_key_color, $random_html_color);
            }
        }

        //create png
        //CyberSoldier_AdminAjaxCalls::cybersoldier_saveSVGImage($user_id);
    }
}
