<?php 

require_once(dirname(__FILE__)."/pages.php");
// require_once(ABSPATH."app/html_elements.php");

class MessagingOps {

	private $post;
	private $user;
	private $session;
	private $sorting;
	public $trend;
	public static $instance;
	public $message;
	public $sender;
	public $receiver;

	public function __construct() {
		$this->post = new post;
		$this->user = new user;
		$this->sorting = new sorting;
		$this->session = Session::getInstance();
	}

    public function add_to_list($group_name, $callback, $args = array()) {
        $list = ($option = get_option("sms_list")) ? $option : array();
        if(function_exists($callback)) {
            $list[$group_name] = ['callback' => $callback, 'group_name' => $group_name, 'args' => $args];
            update_option("sms_list", $list);
        }
        return $list;
    }

    public function call_from_list($group_name) {
        $list = get_option("sms_list");
        if($list && isset($list[$group_name]) && function_exists($list[$group_name]['callback'])) {
            return $list[$group_name]['callback']($list[$group_name]['args']);
        }
        return array();
    }

	public function new_trend() {
		do {
			$trend = rand(999, 9999).time();
		}
		while (!$this->is_unique($trend));
		$this->trend = $trend;
	}

	public function is_unique($trend) {
		$res = $this->post->get_post_by_meta_data(['type' => 'message', 'trend' => $trend]);
		if(_count($res) > 0) {
			return false;
		} else return true;
	}

	public static function getInstance() {
		if(!isset(self::$instance)) {
			self::$instance = new self;
		}
		return self::$instance;
	}

	public function __set( $name , $value )
    {
        $this->instance->name = $value;
    }
   
    public function __get( $name )
    {
        if ( isset($this->instance->name))
        {
            return $this->instance->name;
        }
    }

    public function message_exists() {
    	if(isset($this->trend)) {
    		unset($this->trend);
    	}
    	$res = $this->post->get_post_by_meta_data(['type' => 'message', 'sender' => $this->sender, 'receiver' => $this->receiver]);
    	$res = array_merge($res, $this->post->get_post_by_meta_data(['type' => 'message', 'receiver' => $this->sender, 'sender' => $this->receiver]));
    	if(_count($res) > 0) {
    		$res = array_shift($res);
    		$this->trend = $res['trend'];
		} else $this->new_trend();
		return $this->trend;
    }

    public function get_message_meta($msg_id) {
    	return $this->post->get_post_meta($msg_id);
    }

    public function mark_as_read($trend) {
    	$res = $this->post->get_post_by_meta_data(['type' => 'message', 'trend' => $trend, 'receiver' => $this->session->id, 'status' => 'unread']);
    	if(_count($res) > 0) {
    		foreach ($res as $msg_meta) {
    			$this->post->update_post_meta($msg_meta['id'], ['status' => 'read']);
    		}
    	}
    	
    }

    public function new_message() {
    	$this->sender = $this->session->id;
    	if(isset($this->message) && isset($this->receiver)) {
    		$trend = $this->message_exists();
    		$args = [
    			'type' => 'message',
    			'sender' => $this->sender,
    			'receiver' => $this->receiver,
    			'message' => $this->message,
    			'trend' => $trend,
    			'status' => 'unread'
    		];
    		$this->post->add_post($args);
    	}
    }

    public function get_last_messages() {
    	$messages = $this->post->get_post_by_meta_data(['type' => 'message', 'sender' => $this->session->id]);
    	$messages = array_merge($messages, $this->post->get_post_by_meta_data(['type' => 'message', 'receiver' => $this->session->id]));
    	if(_count($messages) > 0) {
			foreach ($messages as $key => $value) {
				$result[$value['trend']][] = $value;
			}
		} else return false;
		$fin_res = array();
		foreach ($result as $trend => $value) {
			$result = $this->sorting->sort_by_meta_value($value, 'posted_on', 'desc');
			$fin_res[] = array_shift($result);
		}
		return $this->sorting->sort_by_meta_value($fin_res, 'posted_on', 'desc');
    }

    public function get_unread_messages() {
        $messages = $this->post->get_post_by_meta_data(['type' => 'message', 'receiver' => $this->session->id, 'status' => 'unread']);
        return $messages;
    }

}

function display_new_messages() {
    $msg = MessagingOps::getInstance();
    $unread = $msg->get_unread_messages();
    ?>
    <div class="dropdown for-message">
      <button class="btn btn-secondary dropdown-toggle" type="button"
            id="message"
            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <i class="fas fa-envelope"></i>
        <span class="count bg-primary"><?php echo _count($unread); ?></span>
      </button>
      <div class="dropdown-menu" aria-labelledby="message">
        <p class="red">You have <?php echo _count($unread); ?> Mails</p>
        <?php if (_count($unread) > 0): ?>
            <?php foreach ($unread as $msg_meta): ?>
                <a class="dropdown-item media bg-flat-color-1" href="support">
                    <span class="photo media-left"><img alt="avatar" src="<?php echo get_user_image($msg_meta['sender']); ?>"></span>
                    <span class="message media-body">
                        <span class="name float-left"><?php echo get_fullname($msg_meta['sender']); ?></span>
                        <span class="time float-right"><?php echo time_elapsed_string(date('Y-m-d H:i:s', $msg_meta['posted_on'])); ?></span>
                            <p><?php echo substr($msg_meta['message'], 0, 30); ?></p>
                    </span>
                </a>
            <?php endforeach ?>
        <?php endif ?>
      </div>
    </div>
    <?php
}

function add_mail_to_dash($args) {
    $msg = MessagingOps::getInstance();
    $unread = $msg->get_unread_messages();
    ?>
    <li class="list-group-item">
        <a href="support"> <i class="far fa-envelope"></i> New Messages <span class="pull-right r-activity"><?php echo _count($unread) ?></span></a>
    </li>
    <?php
}

function get_contact_groups($exclude = array()) {
    $sms_list = get_option("sms_list");
    $groups = array();
    if($sms_list) {
        foreach ($sms_list as $group_name => $group_meta) {
            if(!in_array($group_name, $exclude)) {
                $groups[$group_name] = $group_name;
            }
        }
    }
    return $groups;
}

function get_bulk_receivers($receivers) {
    $post = new post;
    $user = new user;
    $msg = MessagingOps::getInstance();
    $res = [];
    if(_count($receivers) > 0) {
        foreach ($receivers as $receiver) {
            set_time_limit(200);
            $int_val = (int) $receiver;
            if($int_val !== 0) {
                $_user_meta = $user->get_user_meta($int_val);
                $res[$_user_meta['id']] = $_user_meta;
            } else {
                $grp = $msg->call_from_list($receiver);
                if(_count($grp) > 0){
                    foreach($grp as $each_meta) {
                        $res[$each_meta['id']] = $each_meta;
                    }
                }
            }
        }
    }
    set_time_limit(200);
    return $res;
}

function bulk_sms_bal_to_dash($args) {
    $support = new support;
    if(!current_user_can('super_admin')) {
        return;
    }
    $bal_obj = $support->fetch_sms_details('balance');
    if(!$bal_obj) {
        return;
    }
    ?>
    <li class="list-group-item">
        <a href="support"> <i class="fas fa-money"></i> Bulk SMS Balance <span class="pull-right r-activity"><?php echo toMoney($bal_obj->balance); ?></span></a>
    </li>
    <?php
}

function custom_sms_receivers_list($list) {
    $user = new user;
    if(_count($list) && is_array($list)) {
        foreach ($list as $key => &$value) {
            $value = $user->get_user_meta($value);
        }
    }
    return $list;
}

function pm_ticket_number($prefix = "T-") {
    $suffix = date("my", time());
    do {
        $ticket_number = $prefix.$suffix.rand(1000, 9999).rand(1000, 9999);
    } while (db_post_unique(['type' => 'support_ticket', 'ticket_number' => $ticket_number]));
    return $ticket_number;
}

function msg_get_recepients_form($args) {
    $session = Session::getInstance();
    if(isset($session->message_receipients)) {
        return $session->message_receipients;
    }
    require_once(ABSPATH."app/elements/form.php");
    $roles = get_system_roles($args['exclude']);
    $groups = get_contact_groups($args['exclude']);
    $recipients = array('GROUPS' => $groups);
    if(_count($roles)) {
        foreach ($roles as $role_name => $role_slug) {
            $recipients = array_merge($recipients, [strtoupper($role_name) => get_select_options_from_user(['role' => $role_slug, 'status' => 'active', 'apply_db_session' => 1])]);
        }
    }
    $html = selectgrp_html(['label' => 'Receivers', 'id' => 'receivers', 'name' => 'receivers[]', 'class' => 'standardSelect', "tabindex"=>"1", 'multiple' => 'multiple'], $recipients);
    $session->message_receipients = $html;
    return $html;
}

function messaging_get_announcements($user_meta) {
    $post = new post;
    if(!is_array($user_meta)) {
        $user = new user;
        $user_meta = $user->get_user_meta($user_meta);
    }
    $now = time();
    $q = ['type' => 'announcement', 'from' => $now, 'to' => $now];
    if(get_option("section_database")) {
        if(!in_array($user_meta['role'], get_option('exempt_users'))) {
            $q['db_section_id'] = ['%['.$user_meta['db_section_id'].']%', $user_meta['db_section_id']];
        }
    }
    return $post->get_post_by_meta_data($q, ['from' => '<', 'to' => '>']);
}