<?php

/*
 * Ajax calls for common fols.
 */

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

new CyberSoldier_AjaxCalls();

class CyberSoldier_AjaxCalls
{

	public function __construct()
	{
		add_action('wp_ajax_cybersoldier_add_score_to_battle_item', [$this, 'add_score_to_battle_item']);
		add_action('wp_ajax_cybersoldier_add_battle_reply', [$this, 'add_battle_reply']);
	}
	/**
	 * Add battle reply, not for only
	 */

	function add_battle_reply()
	{
		global $wpdb;
		$post_id = isset($_POST['post_id']) && is_numeric($_POST['post_id']) ? intval($_POST['post_id']) : false;
		if (!$post_id || !is_numeric($post_id))
			error_log("Hmm, error: " . print_r($_POST, true));

		$battle = get_post($post_id);
		$reply_text = stripslashes(sanitize_text_field($_POST['reply_text']));

		$current_user = wp_get_current_user();
		$battle_user = CyberSoldier_User::cybersoldier_users_in_battle($post_id, false, $current_user->ID);
		$max_number_of_lines = get_option('number_of_lines', 10);
		$number_of_lines = CyberSoldier_BattlePostType::cybersoldier_battle_lines_number($post_id);
		$who_went_last = CyberSoldier_BattlePostType::cybersoldier_who_went_last($post_id);
		$is_in_battle = CyberSoldier_User::cybersoldier_in_battle($post_id, $current_user->ID);
		$my_turn = $is_in_battle && $current_user->ID != $who_went_last ? true : false;

		if ($my_turn && $number_of_lines < $max_number_of_lines) {
			$insert_array = array(
				"post_id" => $post_id,
				"user_id" => $current_user->ID,
				"line" => $reply_text,
				"date_added" => current_time("Y-m-d H:i:s")
			);
			if ($post_id != 0)
				$insert_array["date_used"] = current_time("Y-m-d H:i:s");

			$table_name = $wpdb->prefix . "cybersoldier_lines";
			$worked = $wpdb->insert($table_name, $insert_array);

			$left_str = $battle_user["user"]->ID == $current_user->ID ? " left" : "";
			$html_str = "";
			$html_str .= "<div class='cybersoldier_line_box $left_str'>";
			$html_str .= "<div class='user_info'>" . esc_attr($current_user->display_name) . " - " . current_time("Y-m-d H:i:s") . "</div>";
			$html_str .= "<div class='badass_line'>" . esc_attr($reply_text) . "</div>";
			$html_str .= "</div>";

			if ($worked) {
				$cybersoldier_send_mail_to_opponent = get_option('cybersoldier_send_mail_to_opponent', true);
				if ($cybersoldier_send_mail_to_opponent) {
					$subject = sprintf(
						__("%s just replyed in %s", "cybersoldier"),
						$current_user->display_name,
						$battle->post_title
					);
					$message = sprintf(
						__("<h4>%s just replyed in %s</h4><p>Your opponent %s just replyed in the battle %s </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');
					$html_str .= "Mail have been sent to " . esc_attr($battle_user["user"]->display_name);
					if (is_email($battle_user["user"]->user_email))
						wp_mail($battle_user["user"]->user_email, $subject, $message, $headers);
				}

				wp_send_json(array(
					"result" => "ok",
					"html_str" => $html_str
				));
			} else
				error_log("error: " . $worked . $wpdb->print_error());
		} else
			die("nah, no cheating, I aint yo girlfriend...");

		wp_die();
	}


	/**
	 * Add battle reply, not for only
	 */
	function add_score_to_battle_item()
	{
		//TODO: set sessions in some fancy way, remove "just voted" functionallity from JS-file
		global $wpdb;
		$line_id = isset($_POST['line_id']) && is_numeric($_POST['line_id']) ? intval($_POST['line_id']) : 0;
		$score = isset($_POST['score']) && is_numeric($_POST['score']) ? intval($_POST['score']) : 0;

		$insert_array = array(
			"line_id" => $line_id,
			"value" => $score
		);

		$table_name = $wpdb->prefix . "cybersoldier_scores";
		$worked = $wpdb->insert($table_name, $insert_array);

		if ($worked) {
			wp_send_json(array(
				"result" => "ok",
				"html_str" => esc_attr__("Thanks for voting!!", "cybersoldier")
			));
		} else {
			error_log(print_r($worked, true));
		}

		wp_die();
	}
}
