<?php
/**
 * Ticket Support
 * https://webenginecms.org/
 * 
 * @version 1.6.0
 * @author Lautaro Angelico <http://lautaroangelico.com/>
 * @copyright (c) 2013-2025 Lautaro Angelico, All Rights Reserved
 * @build w641ba01901cb0925ec50f543e59acbd
 */

class ticketSystem {
	
	private $_subjectMinLen = 10;
	private $_subjectMaxLen = 50;
	private $_messageMinLen = 10;
	private $_messageMaxLen = 5000;
	private $_staffMemberNickname = 'Staff';
	
	private $_id;
	private $_subject;
	private $_message;
	private $_username;
	private $_isAdmin = false;
	
	private $_usercpmenu = array(
		array(
			'active' => true,
			'type' => 'internal',
			'phrase' => 'plugin_ticketsupport_2',
			'link' => 'tickets/list',
			'icon' => 'usercp_default.png',
			'visibility' => 'user',
			'newtab' => false,
			'order' => 999,
		),
		array(
			'active' => true,
			'type' => 'internal',
			'phrase' => 'plugin_ticketsupport_1',
			'link' => 'tickets/new',
			'icon' => 'usercp_default.png',
			'visibility' => 'user',
			'newtab' => false,
			'order' => 999,
		),
	);
	
	private $db;
	
	function __construct() {
		
		$this->db = Connection::Database('Me_MuOnline');
		
		$cfg = gconfig('ticketsystem');
		if(!is_array($cfg)) throw new Exception(lang('plugin_ticketsupport_20', true));
		
		$this->_subjectMinLen = $cfg['subject_min_limit'];
		$this->_messageMinLen = $cfg['message_min_limit'];
		$this->_messageMaxLen = $cfg['message_max_limit'];
		$this->_staffMemberNickname = $cfg['staff_nick'];
	}
	
	public function setUsername($username) {
		if(!check_value($username)) throw new Exception(lang('plugin_ticketsupport_21', true));
		
		$this->_username = $username;
	}
	
	public function setId($id) {
		if(!check_value($id)) throw new Exception(lang('plugin_ticketsupport_22', true));
		if(!Validator::UnsignedNumber($id)) throw new Exception(lang('plugin_ticketsupport_22', true));
		
		$this->_id = $id;
	}
	
	public function setSubject($subject) {
		if(!check_value($subject)) throw new Exception(lang('plugin_ticketsupport_23', true));
		if(!Validator::Length($subject, $this->_subjectMaxLen, $this->_subjectMinLen)) throw new Exception(lang('plugin_ticketsupport_24', true));
		
		$this->_subject = $subject;
	}
	
	public function setMessage($message) {
		if(!check_value($message)) throw new Exception(lang('plugin_ticketsupport_25', true));
		if(!Validator::Length($message, $this->_messageMaxLen, $this->_messageMinLen)) throw new Exception(lang('plugin_ticketsupport_26', true));
		
		$this->_message = $message;
	}
	
	public function isAdmin() {
		$this->_isAdmin = true;
	}
	
	public function create() {
		if(!check_value($this->_username)) throw new Exception(lang('plugin_ticketsupport_21', true));
		if(!check_value($this->_subject)) throw new Exception(lang('plugin_ticketsupport_23', true));
		if(!check_value($this->_message)) throw new Exception(lang('plugin_ticketsupport_25', true));
		
		$create_date = time();
		
		$ticket_data = array(
			$this->_subject,
			$_SESSION['username'],
			$create_date
		);
		
		$createTicket = $this->db->query("INSERT INTO ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM (ticket_subject, ticket_author, ticket_create_date) VALUES (?, ?, ?)", $ticket_data);
		if(!$createTicket) throw new Exception(lang('plugin_ticketsupport_31', true));
		
		$ticketIdInfo = $this->db->query_fetch_single("SELECT * FROM ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM WHERE ticket_author = ? AND ticket_create_date = ?", array($_SESSION['username'], $create_date));
		if(!is_array($ticketIdInfo)) throw new Exception(lang('plugin_ticketsupport_31', true));
		
		$ticketId = $ticketIdInfo['id'];
		
		$reply_data = array(
			$ticketId,
			$_SESSION['username'],
			$create_date,
			$this->_message
		);
		
		$createMessage = $this->db->query("INSERT INTO ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM_CONTENT (ticket_id, reply_author, reply_date, reply_content) VALUES (?, ?, ?, ?)", $reply_data);
		if(!$createMessage) throw new Exception(lang('plugin_ticketsupport_31', true));
		
	}
	
	public function reply() {
		if(!check_value($this->_id)) throw new Exception(lang('plugin_ticketsupport_22', true));
		if(!check_value($this->_username)) throw new Exception(lang('plugin_ticketsupport_21', true));
		if(!check_value($this->_message)) throw new Exception(lang('plugin_ticketsupport_25', true));
		
		$ticketData = $this->getTicketData();
		if(!is_array($ticketData)) throw new Exception(lang('plugin_ticketsupport_27', true));
		
		if(!$this->_isAdmin) {
			if($ticketData['ticket_status'] != 0) throw new Exception(lang('plugin_ticketsupport_28', true));
			if($ticketData['ticket_author'] != $this->_username) throw new Exception(lang('plugin_ticketsupport_29', true));
		}
		
		$replyDate = time();
		$data = array(
			$this->_id,
			$this->_username,
			$replyDate,
			$this->_message
		);
		
		$result = $this->db->query("INSERT INTO ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM_CONTENT (ticket_id, reply_author, reply_date, reply_content) VALUES (?, ?, ?, ?)", $data);
		if(!$result) throw new Exception(lang('plugin_ticketsupport_30', true));
		
		$this->updateTicketReplyData($this->_id, $replyDate, $this->_username);
	}
	
	public function acp_getOpenTickets() {
		$data = $this->db->query_fetch("SELECT * FROM ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM WHERE ticket_status = 0 ORDER BY id ASC");
		if(!is_array($data)) return;
		return $data;
	}
	
	public function acp_getClosedTickets() {
		$data = $this->db->query_fetch("SELECT * FROM ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM WHERE ticket_status = 1 ORDER BY id ASC");
		if(!is_array($data)) return;
		return $data;
	}
	
	public function getTicketData() {
		if(!check_value($this->_id)) return;
		$ticket = $this->db->query_fetch_single("SELECT * FROM ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM WHERE id = ?", array($this->_id));
		if(!is_array($ticket)) return;
		return $ticket;
	}
	
	public function getTicketReplies() {
		if(!check_value($this->_id)) return;
		$replies = $this->db->query_fetch("SELECT * FROM ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM_CONTENT WHERE ticket_id = ? ORDER BY reply_id ASC", array($this->_id));
		if(!is_array($replies)) return;
		return $replies;
	}
	
	private function updateTicketReplyData($id,$date,$user) {
		$update = $this->db->query("UPDATE ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM SET ticket_last_reply_date = ?, ticket_last_reply_user = ? WHERE id = ?", array($date, $user, $id));
		if(!$update) return;
		return true;
	}
	
	public function deleteReply($reply_id) {
		if(!Validator::Number($reply_id)) throw new Exception(lang('plugin_ticketsupport_32', true));
		
		$delete = $this->db->query("DELETE FROM ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM_CONTENT WHERE reply_id = ?", array($reply_id));
		if(!$delete) throw new Exception(lang('plugin_ticketsupport_33', true));
	}
	
	public function getUserTickets() {
		if(!check_value($this->_username)) return;
		$tickets = $this->db->query_fetch("SELECT * FROM ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM WHERE ticket_author = ? ORDER BY id DESC", array($this->_username));
		if(!is_array($tickets)) return;
		return $tickets;
	}
	
	public function updateTicketStatus($id,$new_status=0) {
		if(!check_value($id)) return;
		$update = $this->db->query("UPDATE ".WE_PREFIX."WEBENGINE_PLUGIN_TICKETSYSTEM SET ticket_status = ? WHERE id = ?", array($new_status, $id));
		if(!$update) return;
		return true;
	}
	
	public function checkPluginUsercpLinks() {
		if(!is_array($this->_usercpmenu)) return;
		$cfg = loadConfig('usercp');
		if(!is_array($cfg)) return;
		foreach($cfg as $usercpMenu) {
			$usercpLinks[] = $usercpMenu['link'];
		}
		foreach($this->_usercpmenu as $pluginMenuLink) {
			if(in_array($pluginMenuLink['link'],$usercpLinks)) continue;
			$cfg[] = $pluginMenuLink;
		}
		usort($cfg, function($a, $b) {
			return $a['order'] - $b['order'];
		});
		$usercpJson = json_encode($cfg, JSON_PRETTY_PRINT);
		$cfgFile = fopen(__PATH_CONFIGS__.'usercp.json', 'w');
		if(!$cfgFile) throw new \Exception('There was a problem opening the usercp file.');
		fwrite($cfgFile, $usercpJson);
		fclose($cfgFile);
	}
	
}