<?php

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

new CyberSoldier_BattlePostType();
class CyberSoldier_BattlePostType
{

    public function __construct()
    {
        add_action('init', [$this, 'cybersoldier_add_battle']);
        add_action('add_meta_boxes', [$this, 'cybersoldier_metaboxes']);
        add_action('save_post', [$this, 'cybersoldier_save_battle_invite'], 10, 2);
        add_action('edit_post', [$this, 'cybersoldier_save_battle_invite'], 10, 2);
        add_filter('single_template', [$this, 'cybersoldier_battle_template']);
    }
    /**
     * Battle post type
     */
    function cybersoldier_add_battle()
    {
        $battle = register_post_type('battle', [
            'labels' => [
                'name' => __('Battles', "cybersoldier"),
                'singular_name' => __('Battle', "cybersoldier")
            ],
            'public' => true,
            'custom-fields' => true,
            'capability_type' => 'battle',
            'rewrite' => true,
            'capabilities' => array(
                'publish_posts' => 'publish_battles',
                'edit_posts' => 'edit_battles',
                'edit_others_posts' => 'edit_others_battles',
                'read_private_posts' => 'read_private_battles',
                'edit_post' => 'edit_battle',
                'delete_post' => 'delete_battle',
                'delete_others_posts' => 'delete_others__battles',
                'read_post' => 'read_battle'
            ),
            'map_meta_cap' => true
        ]);
    }



    /**
     * Add metabox for battles
     */

    function cybersoldier_metaboxes()
    {
        add_meta_box(
            'battle_invite', 
            __('Invite User', "cybersoldier"), 
            [$this, 'cybersoldier_battle_invite_metabox'], 
            'battle', 
            'side', 
            'default'
        );
    }

    /**
     * Function for adding the invite metabox.
     */
    function cybersoldier_battle_invite_metabox()
    {
        global $post;
        // Noncename needed to verify where the data originated
        wp_nonce_field('battelinvite_nonceaction', 'cybersoldier_battelinvite_noncename');
        // Get the location data if its already been entered

        $battle_invite = get_post_meta($post->ID, 'invited_user', true);

        // Echo out the field
        if ($battle_invite) {
            $battle_user = get_user_by("ID", $battle_invite);
            echo "<h4>" . __("User invited: ", "Cybersoldier") . " " . esc_attr($battle_user->display_name) . "</h4>";
        } else {
            $getid = isset($_GET["csid"]) && is_numeric($_GET["csid"]) ? intval($_GET["csid"]) : '';
            $the_user_id = $battle_invite ? $battle_invite : $getid;
            $battle_user_info = CyberSoldier_User::cybersoldier_user_info($the_user_id);
            $name = $battle_user_info ? $battle_user_info["user"]->display_name : "";
            echo '<input type="text" name="invited_user" id="invited_user" value="' .esc_attr($name) . '" class="widefat" />';
            echo '<input type="hidden" name="invited_user_id" id="invited_user_id" value="' . esc_attr($the_user_id)  . '" />';
            echo "<div id='found_users'></div>";
        }
    }


    /**
     * Handles saving the meta box.
     *
     * @param int     $post_id Post ID.
     * @param WP_Post $post    Post object.
     * @return null
     */

    function cybersoldier_save_battle_invite($post_id, $post)
    {
        // Add nonce for security and authentication.
        $nonce_name   = isset($_POST['cybersoldier_battelinvite_noncename']) ? sanitize_text_field($_POST['cybersoldier_battelinvite_noncename']) : '';
        $nonce_action = 'battelinvite_nonceaction';
        
        // Check if nonce is set.
        if (!isset($nonce_name)) {
            return;
        }

        // Check if nonce is valid.
        if (!wp_verify_nonce($nonce_name, $nonce_action)) {
            return;
        }

        // Check if user has permissions to save data.
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // Check if not an autosave.
        if (wp_is_post_autosave($post_id)) {
            return;
        }

        // Check if not a revision.
        if (wp_is_post_revision($post_id)) {
            return;
        }

        // OK, we're authenticated: we need to find and save the data
        $inv_user = isset($_POST['invited_user_id']) && is_numeric($_POST['invited_user_id']) ? intval($_POST['invited_user_id']) : false;
        // save data in INVISIBLE custom field (note the "_" prefixing the custom fields' name
        //TODO: send email with invite and make a decline page. Or not show anything if not logged in.

        $current_user = wp_get_current_user();
        $battle = $post;
        $battle_invite = $inv_user; // ? get_post_meta($battle->ID, 'invited_user', true);
        // Echo out the field
        if ($battle_invite) {
            $battle_user = get_user_by("ID", $battle_invite);

            $subject = sprintf(__("%s invited you to the battle %s", "cybersoldier"), $current_user->display_name, $battle->post_title);
            $message = sprintf(
                __("<h4>%s have invited you to the battel %s</h4><p>To show %s who is the battle master of all universes, battle this cyber soldier in %s by visiting the link below.</p><p><a href='%s'>%s</a></p>", "cybersoldier"),
                $current_user->display_name,
                $battle->post_title,
                $current_user->display_name,
                $battle->post_title,
                get_permalink($battle->ID),
                get_permalink($battle->ID)
            );
            $headers = array('Content-Type: text/html; charset=UTF-8');
            $mailsent = wp_mail($battle_user->user_email, $subject, $message, $headers);
            
            if ($mailsent)
                update_post_meta($post_id, 'invited_user', $inv_user);
            else {
                update_post_meta($post_id, 'invited_user', $inv_user);
                add_action('admin_notices', [$this, 'cybersoldier_addbattele__error']);
            }
        }
        add_action('admin_notices', [$this, 'cybersoldier_addbattele__error']);
        //echo "This should probably be a nicer warning, but unfortunatly there were no mail sent to battle opponent. $subject $message";
    }

    function cybersoldier_addbattele__error()
    {
        $class = 'notice notice-error';
        $message = __('Irks! An error has occurred.', "cybersoldier");

        printf('<div class="%1$s"><p>%2$s</p></div>', $class, $message);
    }


    /* Filter the single_template with our custom function*/
    function cybersoldier_battle_template($single)
    {
        global $wp_query, $post;
        /* Checks for single template by post type */
        if ($post->post_type == "battle") {
            $template_path = get_template_directory();
            if (file_exists($template_path . '/cybersoldier/battle.php'))
                return $template_path . '/cybersoldier/battle.php';
            else if (file_exists(CYBERSOLDIER_PLUGIN_PATH . 'templates/battle.php'))
                return CYBERSOLDIER_PLUGIN_PATH . 'templates/battle.php';
        }
        return $single;
    }

    /**
     * To check when a battle ends.
     */
    public static function cybersoldier_when_battle_ends($battle_id)
    {
        $time_to_end = get_option('cybersoldier_time_to_end', 24);
        $start_time = get_the_time("Y-m-d H:m:s", $battle_id);
        $end_date = date("Y-m-d H:m:s", strtotime('+' . $time_to_end . ' hours', strtotime($start_time)));
        $battle_over = strtotime($end_date) - time() < 0;
        $start_date = new DateTime();
        $since_start = $start_date->diff(new DateTime($end_date));
        $time_left = !$battle_over ? __("battle ends in ", "cybersoldier") . esc_attr($since_start->days) . __(' days ', "cybersoldier") . date("H:i:s", strtotime($since_start->h . ":" . $since_start->i . ":" . $since_start->s)) : __("battle over", "cybersoldier");
        return $time_left;
    }

    /**
     * Get battle lines
     */
    public static function cybersoldier_battle_lines($battle_id, $battle_user = 0, $battle_over = false)
    {
        global $wpdb;

        if (!is_numeric($battle_id) || !is_numeric($battle_user) || !is_bool($battle_over))
            return "Better check yo self, or at least you values... And maybe life choices.";
        $table1 = $wpdb->prefix . "cybersoldier_lines";

        $sql = "SELECT * FROM $table1 WHERE post_id=$battle_id AND date_used IS NOT NULL";
        $lines = $wpdb->get_results($sql);

        $counter = 1;
        $total_scores = array(0, 0);

        $usernames = array("No score yet", "No score yet");
        $return_text = "<div class='cybersoldier_lines'>";
        foreach ($lines as $line) {

            $table2 = $wpdb->prefix . "cybersoldier_scores";
            $sql2 = "SELECT SUM(value) as score FROM $table2 WHERE line_id=" . $line->id;
            $scores = $wpdb->get_results($sql2);
            $score = $scores[0]->score;

            $left_str = $battle_user == $line->user_id ? " cybersoldier_line_left" : "";
            $user = get_user_by("ID", $line->user_id);

            if ($battle_user == $line->user_id) {
                $total_scores[0] += $score;
                $usernames[0] = $user->display_name;
            } else {
                $total_scores[1] += $score;
                $usernames[1] = $user->display_name;
            }

            $return_text .= "<div class='cybersoldier_line_box $left_str'>";
            $return_text .= "<div class='user_info'>" . esc_attr($user->display_name) . " - " . esc_attr($line->date_added) . __(" Current score: ", "cybersoldier") . number_format($score, 2) . "</div>";
            $return_text .= "<div class='badass_line'>" . esc_attr($line->line) . "</div>";
            if (!$battle_over) {
                $return_text .= "<div class='score_bar' id='battle_" .esc_attr( $line->id) . "'>
					<div class='score_number' id='score_1' style='background: #e0e0e0;'>1</div>
					<div class='score_number' id='score_2' style='background: #d0d0d0;'>2</div>
					<div class='score_number' id='score_3' style='background: #c0c0c0;'>3</div>
					<div class='score_number' id='score_4' style='background: #b0b0b0;'>4</div>
					<div class='score_number' id='score_5' style='background: #a0a0a0;'>5</div>
				</div>";
            }
            $return_text .= "</div>";
            $counter++;
        }
        $return_text .= "</div>";

        $return_top = "<div class='cs-boxes-row scoreboard'>
		<div class='cs-boxes-col'><div class='scoreboard_box'>
            <strong>" . esc_attr($usernames[0]) . ": </strong>" . esc_attr($total_scores[0]) . "
        </div></div>
		<div class='cs-boxes-col'><div class='scoreboard_box'>
            <strong>" . esc_attr($usernames[1]) . ": </strong>" . esc_attr($total_scores[1]) . "
        </div></div>
		</div>";

        return $return_top . $return_text;
    }

    /**
     * Get number of battle lines added
     */
    public static function cybersoldier_battle_lines_number($battle_id, $battle_user = 0)
    {
        //TODO: implement this for a single battel user too
        if (!is_numeric($battle_id) || !is_numeric($battle_user))
            return false;
        global $wpdb;

        $table1 = $wpdb->prefix . "cybersoldier_lines";
        $sql = "SELECT * FROM $table1 WHERE post_id=$battle_id AND date_used IS NOT NULL";
        $lines = $wpdb->get_results($sql);
        return count($lines);
    }

    /**
     * Get battle lines
     * @param int $battle_id Id of battle.
     */
    public static function cybersoldier_who_went_last($battle_id)
    {
        global $wpdb;
        if (!is_numeric($battle_id))
            return false;

        $table1 = $wpdb->prefix . "cybersoldier_lines";
        $sql = "SELECT * FROM $table1 WHERE post_id=$battle_id AND date_used IS NOT NULL ORDER BY date_used DESC LIMIT 1";
        $lines = $wpdb->get_results($sql);
        $last_user = isset($lines[0]->user_id) ? $lines[0]->user_id : false;
        return $last_user;
    }
    /**
     * Get random battle line
     */
    public static function cybersoldier_random_line($number_of_lines = 1, $battle_id = false, $user_id = false)
    {
        global $wpdb;

        if (!is_numeric($number_of_lines))
            return "great number, but hey, it's not really a number is it?";
        if (!(is_numeric($battle_id) || is_bool($battle_id)))
            return "Thats true, false or a number, so are you trying to pull a number on me, true or false!?";
        if (!(is_numeric($battle_id) || is_bool($battle_id)))
            return "Thats true, false or a number, so are you trying to pull a number on me, true or false!?";


        $table1 = $wpdb->prefix . "cybersoldier_lines";
        $battle_id_str = $battle_id ? "post_id=$battle_id AND" : "";
        $user_id_str = isset($battle_user) ? "user_id=$user_id AND" : "";
        $sql = "SELECT * FROM $table1 WHERE $battle_id_str $user_id_str date_used IS NOT NULL ORDER BY RAND() LIMIT $number_of_lines";
        $lines = $wpdb->get_results($sql);

        $counter = 1;
        $total_scores = array(0, 0);
        $usernames = array("", "");
        $return_text = "<div class='cybersoldier_lines'>";
        foreach ($lines as $line) {
            $user = get_user_by("ID", $line->user_id);
            $battle = get_post($line->post_id);

            if ($user && isset($battle->guid)) {
                $return_text .= "<div class='cybersoldier_line_box cybersoldier_line_left'>";
                $return_text .= "<div class='user_info'>" . esc_attr($user->display_name) . " - " . substr($line->date_added, 0, 10) . " <a href='" . esc_attr($battle->guid) . "'>" . esc_attr($battle->post_title) . "</a></div>";
                $return_text .= "<div class='badass_line'>" . esc_attr($line->line) . "</div>";
                $return_text .= "</div>";
                $counter++;
            }
        }
        $return_text .= "</div>";

        return $return_text;
    }
}
