<?php
defined('ABSPATH') or die();

function drk_get_user_messages_lists(WP_REST_Request $request)
{
    global $wpdb;
    $user = wp_get_current_user();
    $query = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "drk_user_chat WHERE
    (user_id = " . $user->ID . " OR sender_id = " . $user->ID . ")
    ORDER BY message_time DESC LIMIT 100", ARRAY_A);
    $message_list = array();
    foreach ($query as $message){

        $recipient = $message['user_id'];
        $sender = $message['sender_id'];
        $user_data = get_user_by('ID',$recipient);
        $sender_data = get_user_by('ID',$sender);
        $message['user_avatar'] = drk_get_user_avatar_from_profile($user_data->ID);
        $message['sender_avatar'] = drk_get_user_avatar_from_profile($sender_data->ID);
        if($message['user_id'] == $user->ID){
            $chat_id    = $message['sender_id'];
            $avatar     = $message['sender_avatar'];
            $name       = $message['sender_name'];
            $role       = get_userdata($message['sender_id'])->roles;
        }else{
            $chat_id    = $message['user_id'];
            $avatar     = $message['user_avatar'];
            $name       = $message['user_name'];
            $role       = get_userdata($message['user_id'])->roles;
        }

        if(!$message_list[" ".$chat_id]
            ||
            ($message_list[$chat_id] && $message_list[" ".$chat_id]["last_message"]['message_time'] < $message['message_time'])){
            $message_list[$chat_id]["last_message"] = $message;
            $message_list[$chat_id]["avatar"] = $avatar;
            $message_list[$chat_id]["nickname"] = $name;
            $message_list[$chat_id]["role"] = $role;
            $message_list[$chat_id]["id"] = $chat_id;
        }

    }

    return $message_list;
}

function drk_get_user_chat(WP_REST_Request $request){
    global $wpdb;
    $user = wp_get_current_user();
    $query = $wpdb->get_results("SELECT DISTINCT * FROM " . $wpdb->prefix . "drk_user_chat WHERE
    (user_id = " . $user->ID . " AND sender_id = " . $request->get_param('chat_id') . ") OR
    (user_id = " . $request->get_param('chat_id') . " AND sender_id = " . $user->ID . ")
    ORDER BY id ASC", ARRAY_A);

    foreach ($query as $key => $value) {
        if ($value["parent_message_id"]) {
            $parent_message = drk_get_message_by_id($value["parent_message_id"]);
            $query[$key]["parent_message_text"] = $parent_message[0]['message'];
        }
          $user_data = get_user_by('ID',$value['user_id']);
          $sender_data = get_user_by('ID',$value['sender_id']);
          $query[$key]['user_id'] = $user_data->ID;
          $query[$key]['user_avatar'] = drk_get_user_avatar_from_profile($user_data->ID);
          $query[$key]['user_nickname'] = $user_data->data->display_name;
          $query[$key]['user_role'] = get_userdata($user_data->ID)->roles;

          $query[$key]['sender_id'] = $sender_data->ID;
          $query[$key]['sender_avatar'] = drk_get_user_avatar_from_profile($sender_data->ID);
          $query[$key]['sender_nickname'] = $sender_data->data->display_name;
          $query[$key]['sender_role'] = get_userdata($sender_data->ID)->roles;

          $wpdb->update($wpdb->prefix . "drk_user_chat",array("is_read"=>true), array("ID"=>$value['id']));
    }


    return $query;
}

function drk_get_user_messages(WP_REST_Request $request)
{
    global $wpdb;
    $user = wp_get_current_user();
    $query = array();
    if ($user) {
        $last_user_message_id = $request->get_header('Last-User-Message');
        if ($last_user_message_id == "") {
            $query = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "drk_user_chat WHERE 
        user_id = " . $user->ID . " OR sender_id = " . $user->ID . " 
        ORDER BY id DESC LIMIT 50", ARRAY_A);
        } else {
            $query = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "drk_user_chat WHERE
        id > " . $last_user_message_id . " AND 
        (user_id = " . $user->ID . " OR sender_id = " . $user->ID . ") 
        ORDER BY id DESC", ARRAY_A);
        }

        foreach ($query as $key => $value) {
            if ($value["parent_message_id"]) {
                $parent_message = drk_get_message_by_id($value["parent_message_id"]);
                $query[$key]["parent_message_text"] = $parent_message[0]['message'];
                $query[$key]["parent_message_author"] = $parent_message[0]['sender_name'];
            }
        }
    }
    $response = new WP_REST_Response($query, 200);
    $response->header('Last-User-Message', $query[0]["id"]);
    return $response;
}

function send_user_message(WP_REST_Request $request)
{
    global $wpdb;

    $user = wp_get_current_user();

    $user_id = $request->get_param('user_id');
    $user_name = get_user_by('ID', $user_id)->display_name;
    $sender_id = $user->ID;
    $sender_name = $user->data->display_name;
    $message = $request->get_param('message');
    $parent_message_id = $request->get_param('parent_message_id');

    $result = $wpdb->insert($wpdb->prefix . 'drk_user_chat', array(
        'user_id' => $user_id,
        'user_name' => $user_name,
        'sender_id' => $sender_id,
        'sender_name' => $sender_name,
        'message' => $message,
        'parent_message_id' => $parent_message_id
    ), array('%d', '%s', '%d', '%s', '%s','%d'));
    return $result;
}

function drk_delete_user_message(WP_REST_Request $request)
{
    $message_id = $request->get_param('message_id');

    global $wpdb;
    $query = $wpdb->delete($wpdb->prefix. "drk_user_chat",array('id'=>$message_id));
    return $query;
}

function drk_get_message_by_id($id)
{
    global $wpdb, $last_user_message_ID;
    $user = wp_get_current_user();
    $query = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "drk_user_chat WHERE
    id = " . $id . " AND
    (user_id = " . $user->ID . " OR sender_id = " . $user->ID . ") 
    ORDER BY id DESC", ARRAY_A);

    return $query;
}
function drk_get_room_message_by_id($id)
{
    global $wpdb, $last_user_message_ID;
    $user = wp_get_current_user();
    $query = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "drk_forum_chat WHERE
    id = " . $id . " ORDER BY id DESC", ARRAY_A);

    return $query;
}
function get_room_messages(WP_REST_Request $request)
{
    global $wpdb;
    $user = wp_get_current_user();
    $query = array();
    if ($user) {
        $last_room_message_id = $request->get_header('Last-Room-Message');
        if ($last_room_message_id == "") {
            session_start();
            $query = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "drk_forum_chat 
        ORDER BY id DESC LIMIT 100", ARRAY_A);
        } else {
            $query = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "drk_user_chat WHERE
        id > " . $last_room_message_id . "
        ORDER BY id DESC LIMIT 100", ARRAY_A);
        }

        foreach ($query as $key => $value) {
            if ((integer)$value["parent_message_id"]>0) {
                $parent_message = drk_get_room_message_by_id((integer)$value["parent_message_id"]);
                $query[$key]["parent_message_text"] = $parent_message[0]['message'];
                $query[$key]["parent_message_author"] = $parent_message[0]['sender_name'];

            }
            $sender_data = get_user_by('ID',$value['sender_id']);
            $query[$key]['sender_role'] = get_userdata($value['sender_id'])->roles;
            $query[$key]['sender_avatar'] = drk_get_user_avatar_from_profile($sender_data->ID);
        }
        $response = new WP_REST_Response($query, 200);
        $response->header('Last-Room-Message', $query[0]["id"]);
        return $response;
    }


    return $query;
}

function send_room_message(WP_REST_Request $request)
{
    global $wpdb;

    $user = wp_get_current_user();
    $sender_id = $user->ID;
    $sender_name = $user->data->display_name;
    $message = $request->get_param('message');
    $parent_message_id = $request->get_param('parent_message_id');

    $result = $wpdb->insert($wpdb->prefix . 'drk_forum_chat', array(
        'sender_id' => $sender_id,
        'sender_name' => $sender_name,
        'message' => $message,
        'parent_message_id' => $parent_message_id
    ), array('%d', '%s', '%s', '%d'));
    return $result;
}

function drk_delete_room_message(WP_REST_Request $request)
{
    $message_id = $request->get_param('message_id');
    global $wpdb;
    $query = $wpdb->delete($wpdb->prefix. "drk_forum_chat",array('id'=>$message_id), array('%d'));
    return $query;
}

function drk_time_since($original)
{

    $chunks = array( // unix time (seconds)
        array(60 * 60 * 24 * 365, esc_html__('year', 'simple-ajax-chat')),
        array(60 * 60 * 24 * 30, esc_html__('month', 'simple-ajax-chat')),
        array(60 * 60 * 24 * 7, esc_html__('week', 'simple-ajax-chat')),
        array(60 * 60 * 24, esc_html__('day', 'simple-ajax-chat')),
        array(60 * 60, esc_html__('hour', 'simple-ajax-chat')),
        array(60, esc_html__('minute', 'simple-ajax-chat')),
    );

    $original = $original - 10; // fixes bug where $time & $original match
    $today = current_time('timestamp'); // current unix time
    $since = $today - $original;

    for ($i = 0, $j = count($chunks); $i < $j; $i++) {

        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];

        if (($count = floor($since / $seconds)) != 0) {

            break;

        }

    }

    $print = ($count == 1) ? '1 ' . $name : "$count {$name}" . esc_html__('s', 'drk-chat');

    if ($i + 1 < $j) {

        $seconds2 = $chunks[$i + 1][0];
        $name2 = $chunks[$i + 1][1];

        if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {

            $print .= ($count2 == 1) ? ', 1 ' . $name2 : ", $count2 {$name2}" . esc_html__('s', 'simple-ajax-chat');

        }

    }

    return apply_filters('drk_time_since', $print);
}

function drk_create_user_chat_table()
{

    global $wpdb;

    if (!current_user_can('activate_plugins')) return;

    $table_name  = $wpdb->prefix .'drk_user_chat';
    $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,
			user_id mediumint(10) UNSIGNED NOT NULL,
			user_name varchar(200)  NOT NULL DEFAULT '',
			sender_id mediumint(10) UNSIGNED NOT NULL,
			sender_name varchar(200)  NOT NULL DEFAULT '',
			message_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
			message varchar(9999) NOT NULL DEFAULT '',
			parent_message_id mediumint(10) UNSIGNED DEFAULT NULL,
			is_read tinyint(1) NOT NULL DEFAULT 0,  
			PRIMARY KEY (id)
		) ". $charset_collate .";";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

}
function drk_create_forum_chat_table()
{

    global $wpdb;

    if (!current_user_can('activate_plugins')) return;

    $table_name  = $wpdb->prefix .'drk_forum_chat';
    $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,
			sender_id mediumint(10) UNSIGNED NOT NULL,
			sender_name varchar(200)  NOT NULL DEFAULT '',
			message_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
			message varchar(9999) NOT NULL DEFAULT '',
			parent_message_id mediumint(10) UNSIGNED DEFAULT NULL,
			PRIMARY KEY (id)
		) ". $charset_collate .";";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

}