<?php 

// session_start();

require_once("../../../config.php");
require_once("../../../app/functions.php");
require_once("../../../app/table-functions.php");
// require_once("../../../app/includes/phpmailer/class.phpmailer.php");
spl_autoload_register(function($class_name) {
	$file = "../../../app/classes/class-".$class_name.".php";
	if (file_exists($file)) {
		include $file;
	}
});

require_once("../plugins.php");
$plugins = new plugins();
$plugins->load();

$session = Session::getInstance();

if ($_SERVER["REQUEST_METHOD"] == "POST") :

	if(isset($_POST['action'])){
		$response = array();
		$args = $_POST;
		unset($args['action']);
		$user = new user;
		$post = new post;
		$support = new support(['software_engineer', 'super_admin']);

		switch ($_POST['action']) {
			case 'new_chat':
				if(!isset($args['receiver'])) {
					$response['msg'] = 'You did not specify receiver';
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				$msg = MessagingOps::getInstance();
				$msg->message = $args['new_message'];
				$msg->receiver = $args['receiver'];
				$msg->new_message();
				$response['id'] = $session->id;
				$response['trend'] = $msg->trend;
				$response['msg'] = 'Message sent successfully';
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'refresh_messages':
				$res = $post->get_post_by_meta_data(['type' => 'message', 'trend' => $args['trend']]);
				$msg = MessagingOps::getInstance();
				$msg->mark_as_read($args['trend']);
				$response['messages'] = $res;
				echo json_encode($response);
				exit();
				break;

			case 'get_user_image':
				$response['image'] = get_user_image($args['id']);
				echo json_encode($response);
				exit();
				break;

			case 'get_fullname':
				$response['fullname'] = get_fullname($args['id']);
				echo json_encode($response);
				exit();
				break;

			case 'get_last_messages':
				$msg = MessagingOps::getInstance();
				$last_massages = $msg->get_last_messages();
				$res = array();
				if($last_massages) {
					foreach ($last_massages as $last_msg_meta) {
						$second_party = ($last_msg_meta['sender'] == $session->id) ? $last_msg_meta['receiver'] : $last_msg_meta['sender'];
						$last_msg_meta['fullname'] = get_fullname($second_party);
						$last_msg_meta['image'] = get_user_image($second_party);
						$last_msg_meta['me'] = $session->id;
						array_push($res, $last_msg_meta);
					}
				}
				$response['lastmessages'] = $res;
				echo json_encode($response);
				exit();
				break;

			case 'send_bulk_sms':
				$receivers = get_bulk_receivers($args['receivers']);
				$result = $support->send_sms($receivers, $args['msg'], $sender = $args['sender'], $args['numbers']);
				$response['res'] = $result;
				$response['r'] = $receivers;
				if(!$result) {
					// $response['result'] = $result;
					$response['msg'] = 'Message not sent! Check and see if you enabled SMS sending.';
					$response['error'] = 1;
				} else {
					if($result->status == "OK") {
						$response['msg'] = 'Message sent successfully! Total messages sent was '.$result->count.' and the sum of '.toMoney($result->price).' was charged from your account.';
						$response['error'] = 0;
					} else {
						$response['msg'] = 'Oops! Message was not sent. Error: '.$result->errno.' '.$result->error;
						$response['error'] = 1;
					}
				}
				echo json_encode($response);
				exit();
				break;

			case 'send_bulk_email':
				$receivers = get_bulk_receivers($args['receivers']);
				$ref = get_upload_ref("email-att");
				$files = get_upload_library_files($ref);
				$attachments = array();
				if($files) {
					$attachments = array_column($files['files'], 'file_name');
				}
				$result = $support->send_mail($args['subject'], $receivers, $args['msg'], $args['email'], $attachments);
				$response['args'] = $args;
				$response['res'] = $result;
				$response['r'] = $receivers;
				if($support->error) {
					$response['msg'] = 'Message not sent. Error: '.$support->error;
					$response['error'] = 1;
				} else {
					remove_library_file_by_ref($ref);
					$response['msg'] = 'Message sent successfully!';
					$response['error'] = 0;
				}
				echo json_encode($response);
				exit();
				break;

			case 'new_sms_list':
				$receivers = array_keys(get_bulk_receivers($args['receivers']));
				$list = get_option("sms_list");
				if(isset($list[$args['name']])) {
					$response['error'] = 1;
					$response['msg'] = "Oops! the name of the list is already in our database. Choose a different name please.";
				} else {
					$list[$args['name']] = [
						'group_name' => $args['name'],
						'callback' => 'custom_sms_receivers_list',
						'args' => $receivers,
						'added_by' => $session->id
					];
					update_option("sms_list", $list);
					$response['error'] = 0;
					$response['msg'] = "You have successfully added this list";
				}
				echo json_encode($response);
				exit();
				break;

			case 'edit_sms_list':
				$receivers = array_keys(get_bulk_receivers($args['receivers']));
				$list = get_option("sms_list");
				if(isset($list[$args['name']])) {
					$list[$args['name']]['args'] = $receivers;
					$list[$args['name']]['edited_by'] = $session->id;
					update_option("sms_list", $list);
					$response['error'] = 0;
					$response['msg'] = "You have successfully updated this list";
				}
				echo json_encode($response);
				exit();
				break;

			case 'get_sms_list':
				$response = get_option('sms_list');
				echo json_encode($response);
				exit();
				break;

			case "new_ticket_get_user":
				$response = $user->get_user_meta($args['selector']);
				echo json_encode($response);
				exit();
				break;

			case "new_support_ticket":
				$args['ticket_number'] = pm_ticket_number();
				$args['type'] = 'support_ticket';
				$args['status'] = 'active';
				$args['user_id'] = $user->get_user_meta($args['user_id']) ? $args['user_id'] : $session->id;
				$res = $post->add_post($args);
				if($res) {
					$response['error'] = 0;
					$response['msg'] = "You have successfully created a new support ticket. Your ticket number is: ".$args['ticket_number'];
					$subject = "NEW SUPPORT TICKET #".$args['ticket_number'].": ".$args['subject'];
					$info = $args['message'];
					$action = get_option("home_url")."view-ticket?id=".$res;
					inform_admins($info, $subject, $action, "super_admin_tech", "admin_tech", "software_engineer", "admin");
				} else {
					$response['error'] = 1;
					$response['msg'] = "Sorry, something went wrong and you cannot create a new ticket";
				}
				echo json_encode($response);
				exit();
				break;

			case "get_support_tickets":
				$args = ['type' => 'support_ticket'];
				if(!current_user_can("respond_to_others_support_tickets")) {
					$args['user_id'] = $session->id;
					$args['status'] = 'active';
				}
				$tickets = $post->get_post_by_meta_data($args, "LIKE", false, 100, 0);
				$sorting = new sorting;
				$tickets = $sorting->sort_by_meta_value($tickets, "last_convo", "DESC");
				$table = new table("support-tickets", $tickets);
				$table->set_display_columns([
					"sn" => "SN",
					"posted_on" => "Date",
					"user_id" => "Name of User",
					"ticket_number" => "Ticket Number",
					"subject" => "Subject",
					"responses" => "Responses",
					"status" => "Status"
				]);
				$table->set_dynamic_columns([
					"user_id" => "_tf_get_fullname_id",
					"status" => "_tf_msg_status",
					"responses" => "_tf_msg_responses"
				]);
				$table->set_action_links([
					"View Ticket" => "support-ticket",
					"Delete Ticket" => false
				]);
				$table->set_action_access([
					"View Ticket" => "view_ticket",
					"Delete Ticket" => "delete_support_ticket"
				]);
				$table->set_action_callback([
					"Delete Ticket" => "delete_support_ticket"
				]);
				$table->set_action_args([
					"View Ticket" => ["id" => "id", "content" => "view-ticket"],
					"Delete Ticket" => ["id" => "id"]
				]);
				$response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case "get_recepients_form":
				$response = msg_get_recepients_form($args);
				echo json_encode($response);
				exit();
				break;

			case "create_announcement":
				set_time_limit(80);
				$db_section_id = $args['db_section_id'];
				$user_meta = $user->get_user_meta($session->id);
				$db_section_id[] = $user_meta['db_section_id'];
				$args['db_section_id'] = "[".implode("][", $db_section_id)."]";
				$args['type'] = 'announcement';
				$args['status'] = 'active';
				$args['from'] = strtotime($args['from']);
				$args['to'] = strtotime("11.59 PM ". $args['to']);
				$res = $post->add_post($args);
				if($res) {
					$users = $user->get_user_by_meta_data(['db_section_id' => $db_section_id, 'role' => ['member', 'corporate', 'admin', 'super_admin', 'admin_tech', 'super_admin_tech'], 'apply_db_session' => 1]);
					$support = new support;
					$support->ready_state();
					$support->set_receivers($users);
					$support->subject = "Announcement ".$args['caption'];
					$support->set_content($args['content']);
					$support->send_notice(NOTIFICATION, SMS);
					$response['msg'] = "Announcement sent successfully";
					$response['error'] = 0;
				} else {
					$response['msg'] = "Sorry, Announcement could not be sent";
					$response['error'] = 1;
				}
				echo json_encode($response);
				exit();
				break;

			case "create_announcement__edit":
				set_time_limit(80);
				$db_section_id = $args['db_section_id'];
				$user_meta = $user->get_user_meta($session->id);
				$db_section_id[] = $user_meta['db_section_id'];
				$args['db_section_id'] = "[".implode("][", $db_section_id)."]";
				$args['from'] = strtotime($args['from']);
				$args['to'] = strtotime("11.59 PM ". $args['to']);
				$res = $post->update_post_meta($args['id'], $args);
				$response['msg'] = "Done";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			
			default:
				$response['error'] = 1;
				$response['msg'] = "You have not created the module ".$_POST['action']." to handle you request";
				echo json_encode($response);
				exit();
				break;
		}
		// json_encode($response);
	}

endif;