<?php
defined('ABSPATH') or die();
function drk_create_posts_voting_table() {

    global $wpdb;
    if (!current_user_can('activate_plugins')) return;
    $table_name  = $wpdb->prefix .'drk_voting_posts';
    $check_table = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
    if ($check_table !== $table_name) {
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE ". $table_name ." (
            id mediumint(10) UNSIGNED NOT NULL AUTO_INCREMENT,
			post_id mediumint(10) UNSIGNED NOT NULL,
			user_id mediumint(10) UNSIGNED NOT NULL,
			result varchar(10) NOT NULL DEFAULT 'plus',
			vote_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id)
		) ". $charset_collate .";";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
}

function drk_post_voting(WP_REST_Request $request){
    global $wpdb;
    $vote_result_variants = array('plus','minus');
    $table_name  = $wpdb->prefix .'drk_voting_posts';
    $user = wp_get_current_user();
    if(is_wp_error($user)){
        return new WP_Error('not_authorized', 'Not authorized', array('status' => 401));
    }
    $vote_result = $request->get_param('vote');
    if(!in_array($vote_result,$vote_result_variants)){
        return new WP_Error('not_correct_vote', 'Not correct vote result', array('status' => 500));
    }

    $post_id = $request->get_param('post_id');
    $post = get_post($post_id,"OBJECT");
    $user_vote_data = drk_check_post_voted_user($user->ID,$post_id);

    $comment = get_post($post_id);
    if ($post->post_author > 0 ) {
        $author = get_user_by('ID', $post->post_author);
    }
    if ($author->ID) {
        drk_add_rating_to_user($user, $author, $vote_result);
    }

    if($user_vote_data == null){
        $insert_result = $wpdb->insert($table_name,array("post_id"=>$post_id,"user_id"=>$user->ID,"result"=>$vote_result),[ '%d' , '%d' , '%s' ] );
    }else if($user_vote_data[0]['result'] != $vote_result){
        //$update_result = $wpdb->update($table_name, array("result"=> $vote_result),array('id' => $user_vote_data[0]['id']));
        $update_result = $wpdb->delete($table_name, array('id' => $user_vote_data[0]['id']));
    }
    return drk_get_post_votes($user->ID, $post_id);
}

function drk_check_post_voted_user($user_id,$post_id)
{
    global $wpdb;
    $table_name  = $wpdb->prefix .'drk_voting_posts';
    $result = $wpdb->get_results("SELECT * FROM $table_name WHERE user_id = $user_id AND post_id=$post_id",ARRAY_A);
    return $result;
}

function drk_get_post_votes($user_id, $post_id)
{
    global $wpdb;
    $table_name  = $wpdb->prefix .'drk_voting_posts';
    $result = $wpdb->get_results("SELECT * FROM $table_name WHERE post_id=$post_id",ARRAY_A);
    $minus_vote = 0;
    $plus_vote = 0;
    $stars = 5;
    foreach ($result as $key=>$vote){
        if($vote['result'] == 'minus') $minus_vote ++;
        if($vote['result'] == 'plus') $plus_vote ++;
        $user = get_user_by('ID',$vote["user_id"]);
        $result[$key]["avatar"]=drk_get_user_profile((array)$user)["avatar"];
        $result[$key]["nickname"]= $user->nickname;
    }
    $count_vote = count($result);
    $rate = $plus_vote - $minus_vote;
    if($count_vote > 0)
        $stars = round($rate / $count_vote * 10);
    if($stars < 0) $stars = 1;

    $current_user_vote = $wpdb->get_results("SELECT * FROM $table_name WHERE user_id = $user_id AND post_id=$post_id",ARRAY_A);
    return array(
        "post_id"=>$post_id,
        "_vote_results"=> array("minus"=>$minus_vote,"plus"=>$plus_vote),
        "rate"=>$rate,
        "stars"=> $stars,
        "_vote_count" => $count_vote,
        "current_user_vote"=> $current_user_vote[0],
        "all_votes"=>$result
    );
}