<?php
function drk_create_users_voting_table() {

    global $wpdb;
    if (!current_user_can('activate_plugins')) return;
    $table_name  = $wpdb->prefix .'drk_voting_users';
    $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,
			v_user_id mediumint(10) UNSIGNED NOT NULL,
			user_id mediumint(10) 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_user_voting(WP_REST_Request $request){
    global $wpdb;
    $vote_result_variants = array('plus','minus');
    $table_name  = $wpdb->prefix .'drk_voting_users';
    $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));
    }
    $vuser_id = $request->get_param('user_id');
    if($vuser_id == $user->ID){
        return new WP_Error('self_vote_restricted', 'Self vote restricted', array('status' => 500));
    }
    $user_vote_data = drk_check_user_voted_user($user->ID,$vuser_id);

    if($user_vote_data == null){
        $insert_result = $wpdb->insert($table_name,array("v_user_id"=>$vuser_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']));
    }

    return drk_get_users_votes($user->ID, $vuser_id);
}

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

function drk_get_users_votes($user_id, $v_user_id)
{
    global $wpdb;
    $table_name  = $wpdb->prefix .'drk_voting_users';
    $profile_id = drk_get_user_profile_id($v_user_id);
    $result = $wpdb->get_results("SELECT * FROM $table_name WHERE v_user_id=$v_user_id",ARRAY_A);
    $minus_vote = 0;
    $plus_vote = 0;
    $stars = 5;
    foreach ($result as $vote){
        if($vote['result'] == 'minus') $minus_vote ++;
        if($vote['result'] == 'plus') $plus_vote ++;
    }
    $count_vote = count($result);
    $rate = $plus_vote - $minus_vote;
    if($count_vote > 0)
        $stars = round($rate / $count_vote * 10);
    if($stars < 0) $stars = 1;

    update_post_meta($profile_id,'_rate', intval($rate));
    update_post_meta($profile_id,'_rate_stars', intval($stars));
    update_post_meta($profile_id,'_vote_count', intval($count_vote));

    $current_user_vote = $wpdb->get_results("SELECT * FROM $table_name WHERE user_id = $user_id AND v_user_id=$v_user_id",ARRAY_A);
    return array(
        "v_user_id"=>$v_user_id,
        "profile_id"=>$profile_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
    );
}

function drk_add_rating_to_user(WP_User $user, WP_User $vuser,  $vote_result)
{
    global $wpdb;
    $table_name  = $wpdb->prefix .'drk_voting_users';
    $user_vote_data = drk_check_user_voted_user($user->ID,$vuser->ID);

    if($user_vote_data == null){
        $insert_result = $wpdb->insert($table_name,array("v_user_id"=>$vuser->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']));
    }


    return drk_get_users_votes($user->ID, $vuser->ID);
}