<?php

/*
 * Ajax calls for admin page.
 */

if (!defined('ABSPATH')) {
    exit;
}
// Exit if accessed directly

new CyberSoldier_AdminAjaxCalls();

class CyberSoldier_AdminAjaxCalls
{
    public function __construct()
    {
        add_action('wp_ajax_cybersoldier_add_page', [$this, 'cybersoldier_add_page']);
        add_action('wp_ajax_cybersoldier_update_character_info', [$this, 'cybersoldier_update_character_info']);
        add_action('wp_ajax_cybersoldier_find_battle_user', [$this, 'cybersoldier_find_battle_user']);
        add_action('wp_ajax_cybersoldier_set_soldier_item', [$this, 'cybersoldier_set_soldier_item']);
        add_action('wp_ajax_cybersoldier_set_soldier_items', [$this, 'cybersoldier_set_soldier_items']);
        add_action('wp_ajax_cybersoldier_save_cssvg_image', [$this, 'cybersoldier_saveSVGImage']);
    }
    /**
     * Add pages to that are used
     */
    function cybersoldier_add_page()
    {
        $pagetype = isset($_POST["pagetype"]) ? sanitize_text_field($_POST["pagetype"]) : false;
        $current_user_id = get_current_user_id();

        $args = array(
            'post_type' => 'page',
            'post_status' => 'publish',
            'post_author' => $current_user_id,
        );

        switch ($pagetype) {
            case "battleslist":
                $args["post_title"] = "Battles List";
                $args["post_content"] = "[cybersoldier_battles_list]";
                break;
            case "userpage":
                $args["post_title"] = "My Page";
                $args["post_content"] = "[cybersoldier_user_page]";
                break;
            case "playerpage":
                $args["post_title"] = "Cybersoldier";
                $args["post_content"] = "[cybersoldier_player_page]";
                break;
        }

        $postadded = wp_insert_post($args, true);

        wp_send_json([
            "result" => "ok", 
            "html_out" => esc_attr($pagetype) . " " . print_r($postadded, true)]
        );
        wp_die();
    }


    /**
     * Find battle user
     */
    function cybersoldier_find_battle_user()
    {
        $user_search = isset($_POST["find_user"]) ? sanitize_text_field($_POST["find_user"]) : false;
        $user_query = new WP_User_Query(array('search' => '*' . $user_search . '*'));
        $playaz = $user_query->get_results();
        $return_playaz = array();
        foreach ($playaz as $playah) {
            $return_playaz[] = array(
                "id" => esc_attr($playah->ID), 
                "name" => esc_attr($playah->display_name)
            );
        }
        wp_send_json($return_playaz);
        wp_die();
    }

    /**
     * To update user info
     */
    function cybersoldier_update_character_info()
    {
        if (current_user_can('administrator')) {
            global $wpdb;
            include_once CYBERSOLDIER_PLUGIN_PATH.'assets/character_info.php';

            $table_name = $wpdb->prefix . "cybersoldier_character_items";
            $delete = $wpdb->query("TRUNCATE TABLE $table_name");
            $html_out = "";
            
            foreach ($character_items as $chitem) { //From file included
                
                $insert_array = array(
                    "type" => sanitize_text_field($chitem["type"]),
                    "name" => sanitize_text_field($chitem["name"]),
                    "icon" => sanitize_text_field($chitem["icon"]),
                    "svg_info" => $chitem["svg_info"],
                );

                $worked = $wpdb->insert($table_name, $insert_array);

                if ($worked) {
                    $html_out .= "Updated: " . esc_attr($chitem["name"]) . " OK<br />";
                } else {
                    $html_out .= "Updated: " . esc_attr($chitem["name"]) . " " . esc_attr($chitem["type"]) . " error: " . $worked . $wpdb->print_error() . "<br />";
                }
            }
            //echo "done...";
            wp_send_json_success($html_out);
        } else {
            wp_send_json_error("you are not admin, are you?");
        }
    }


    /**
     * Set meta value for user grejs.
     */
    function cybersoldier_set_soldier_item()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . "cybersoldier_character_items";
        $selected_item = isset($_POST['selected_item']) ? sanitize_text_field($_POST['selected_item']) : false;
        $selected_item_color = isset($_POST['selected_item_color']) ? sanitize_text_field($_POST['selected_item_color']) : false;
        $key_value = explode("_", $selected_item);
        $cleankey = str_replace("cybersoldier", "", $key_value[0]);
        $user_id = get_current_user_id();

        if (isset($key_value[0]) && is_string($key_value[0])) {
            if ($selected_item && isset($key_value[1]) && is_numeric($key_value[1])) {
                $worked = update_user_meta($user_id, $key_value[0], $key_value[1]);
                $sql = "SELECT * FROM $table_name WHERE type = '" . $cleankey . "' AND  id = '" . $key_value[1] . "'";
            } else if ($selected_item_color) {
                $worked_too = update_user_meta($user_id, $key_value[0] . "_color", $selected_item_color);
                $sql = "SELECT * FROM $table_name WHERE type = '" . $cleankey . "' LIMIT 1";
            }

            if($cleankey == "body"){
                $item = [];
                $item[0] = new stdClass();
                $item[0]->type = $cleankey;
                $item[0]->color = esc_attr($selected_item_color);
            }
            else{
                $item = $wpdb->get_results($sql);
                $item[0]->type = isset($item[0]) && isset($item[0]->type) ? $item[0]->type : $cleankey;
                $item[0]->color = esc_attr($selected_item_color);
            }

            wp_send_json($item);
        } else {
            echo "Error setting solidier item";
        }

        wp_die();
    }


    /**
     * Set all user meta stuffs..
     */
    function cybersoldier_set_soldier_items()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . "cybersoldier_character_items";
        $user_id = get_current_user_id();
        $return_array = array();
        $user_metas = get_user_meta($user_id);

        foreach ($user_metas as $key => $met) {
            if (strpos($key, "cybersoldier") !== false) {

                $type = str_replace("cybersoldier", "", $key);
                $value = isset($met[0]) ? $met[0] : $met;

                if (strpos($type, "_color") !== false) {
                    $type = str_replace("_color", "", $type);
                    $return_array[$type]["color"] = esc_attr($value);
                } else {
                    $return_array[$type]["itemid"] = esc_attr($value);
                    $itemsvg = CyberSoldier_AdminAjaxCalls::cybersoldier_getCSSVGItem($type, $value);
                    if($itemsvg)
                        $return_array[$type]["svg_info"] = isset($itemsvg->svg_info) ? $itemsvg->svg_info : false;
                }
            }
        }

        wp_send_json($return_array);

        wp_die();
    }

    /**
    * Get SVG item from db.
    */
    static function cybersoldier_getCSSVGItem($type, $id)
    {
        if (is_numeric($id)) {
            global $wpdb;
            $table_name = $wpdb->prefix . "cybersoldier_character_items";
            $sql = "SELECT * FROM $table_name WHERE type = '" . $type . "' AND  id = '" . $id . "'";
            $item = $wpdb->get_results($sql);
            return isset($item[0]) ? $item[0] : false;
        } else {
            return false;
        }
    }

    /**
     * Save svg as png image.
     */
    public static function cybersoldier_saveSVGImage($user_id = false)
    {
        $upload_path_users = wp_upload_dir();
        $image_path = $upload_path_users["basedir"];

        $user_id = $user_id ? $user_id : get_current_user_id();
        $imgData = sanitize_text_field($_POST["imageData"]);

        $imgData = str_replace(" ", "+", $imgData);
        $imgData = substr($imgData, strpos($imgData, ","));
        $file = fopen($image_path . "/cybersoldier/users/" . $user_id . '.png', 'wb');
        $suxess = fwrite($file, base64_decode($imgData));

        if (!$suxess) {
            error_log($image_path . "/cybersoldier/users/" . $user_id . '.png ' . print_r($file, true));
        }

        fclose($file);
    }
}
