<?php
/**
 * @package		SMS Notification for RSTickets!
 * @version		1.0.2
 * @author		www.golchinonline.ir
 * @copyright	(C) 2019 kiasaty.com All rights reserved.
 * @license		GNU General Public License version 2 or later
 */

// no direct access
defined( '_JEXEC' ) or die;

class plgSystemSmsnotificationforrstickets extends JPlugin
{
	/**
	 * Load the language file on instantiation. Note this is only available in Joomla 3.1 and higher.
	 * If you want to support 3.0 series you must override the constructor
	 *
	 * @var    boolean
	 * @since  3.1
	 */
	protected $autoloadLanguage = true;

	/**
	 * Plugin method with the same name as the event will be called automatically.
	 */
	function onAfterStoreTicket($data)
	{
   
	    echo '<pre>';
	    var_dump($data);
	    echo '</pre>';
	    exit();
		$ticketCode = $data['code'];

		$sendNotificationToCustomer = $this->params->get('customer_notification');
		if ($sendNotificationToCustomer) {
			$customerID = $data['customer_id'];

			// get customer's name
			$customerName = '';
			if (array_key_exists('name', $data)) {
				// if the user is not logged in, RSTicket asks her/his name
				$customerName = $data['name'];
			} else {
				// if the user is logged in, find the customers name (because RSTickets doesn't provide the name)
				$customerName = $this->findNameByID($customerID);
			}

			// get customer's phone number
			$customerPhoneNumber = $this->findPhoneNumberByUserID($customerID);

			// get the staff name
			$staffID = $data['staff_id'];
			$staffName = $this->findNameByID($staffID);

			$customerMessage = $this->params->get('customer_message');
			$StringsToReplace = array('{customer_name}' => $customerName, '{code}' => $ticketCode, '{staff_name}' => $staffName);
			$customerMessage = $this->replaceStringsInMessage($customerMessage, $StringsToReplace);
			$this->sendSMS($customerMessage, $customerPhoneNumber);
		}
		
		$sendNotificationToStaff = $this->params->get('staff_notification');
		if ($sendNotificationToStaff) {
			$staffID = $data['staff_id'];
			$subject = $data['subject'];

			// get staff's phone number
			$staffPhoneNumber = $this->findPhoneNumberByUserID($staffID);

			$staffMessage = $this->params->get('staff_message');
			$StringsToReplace = array('{subject}' => $subject, '{code}' => $ticketCode);
			$staffMessage = $this->replaceStringsInMessage($staffMessage, $StringsToReplace);
			$this->sendSMS($staffMessage, $staffPhoneNumber);
		}
		return true;
	}

	/**
	 * Plugin method with the same name as the event will be called automatically.
	 */
	function onAfterStoreTicketReply($data)
	{
        echo "salamssss";
    die();
		$ticketID = $data['ticket_id'];
		$ticketCode = $this->findTicketCodeByTicketID($ticketID);

		$userID = $data['user_id'];

		// get customer's name
		$staffID = '';
		if (array_key_exists('staff_id', $data)) {
			// if RSTickets has provided staff_id, get it
			$staffID = $data['staff_id'];
		} else {
			// if RSTickets hasn't provided staff_id, find it using ticket id
			$staffID = $this->findStaffIDByTicketID($ticketID);
		}
		$staffName = $this->findNameByID($staffID);

		// get customer's name
		$customerID = '';
		if (array_key_exists('customer_id', $data)) {
			// if RSTickets has provided customer_id, get it
			$customerID = $data['customer_id']; 
		} else {
			// if RSTickets hasn't provided customer_id, find it using ticket id
			$customerID = $this->findCustomerIDByTicketID($ticketID);
		}
		$customerName = $this->findNameByID($customerID);
		
		// if the staff has replied, notify the customer
		if ($userID == $staffID) {
			$sendNotificationToCustomer = $this->params->get('customer_notification');
			if ($sendNotificationToCustomer) {
				// find the customer's phone number
				$customerPhoneNumber = $this->findPhoneNumberByUserID($customerID);
				// prepare the message
				$customerMessage = $this->params->get('customer_message_on_staff_reply');
				$StringsToReplace = array('{customer_name}' => $customerName, '{staff_name}' => $staffName, '{code}' => $ticketCode);
				$customerMessage = $this->replaceStringsInMessage($customerMessage, $StringsToReplace);
				// notify the customer
				$this->sendSMS($customerMessage, $customerPhoneNumber);
			}
		}
		
		// if the customer has replied, notify the staff
		if ($userID == $customerID) {
			$sendNotificationToStaff = $this->params->get('staff_notification');
			if ($sendNotificationToStaff) {
				// find the staff's phone number
				$staffPhoneNumber = $this->findPhoneNumberByUserID($staffID);
				// prepare the message
				$staffMessage = $this->params->get('staff_message_on_customer_reply');
				$StringsToReplace = array('{customer_name}' => $customerName, '{staff_name}' => $staffName, '{code}' => $ticketCode);
				$staffMessage = $this->replaceStringsInMessage($staffMessage, $StringsToReplace);
				// notify the customer
				$this->sendSMS($staffMessage, $staffPhoneNumber);
			}
		}
		return true;
	}

	/**
	 * This method sends SMS using REST
	 */
	private function sendSMS($message, $phoneNumber)
	{
		$url = 'https://ippanel.com/services.jspd';
		$username = $this->params->get('username');
		$password = $this->params->get('password');
		$sender = $this->params->get('from');
		
		$recipients = array($phoneNumber);

		$fields = array
					(
						'uname'=>$username,
						'pass'=>$password,
						'from'=>$sender,
						'message'=>$message,
						'to'=>json_encode($recipients),
						'op'=>'send'
					);
					
		$handler = curl_init($url);             
		curl_setopt($handler, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($handler, CURLOPT_POSTFIELDS, $fields);                       
		curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);
		$result = curl_exec($handler);

		return $result;
	}

	/**
	 * This method replaces strings in a given message
	 */
	private function replaceStringsInMessage($message, $stringArray)
	{
		// if stringArray is not an array, return and do not preceed.
		if (!is_array($stringArray)) {
			return $message;
		}

		foreach ($stringArray as $key => $value) {
			if (strpos($message, $key) !== false) {
				$message = str_replace($key, $value, $message);
			}
		}
		return $message;
	}

	/**
	 * This method finds Ticket code using Ticket id
	 */
	private function findTicketCodeByTicketID($ticketID)
	{
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select($db->quoteName(array('code')));
        $query->from($db->quoteName('#__rsticketspro_tickets'));
        $query->where($db->quoteName('id') . " = " . $db->quote($ticketID));
		$query->setLimit('1');

        $db->setQuery($query);
        $ticketCode = $db->loadResult();

        return $ticketCode;
	}

	/**
	 * This method finds Staff id using Ticket id
	 */
	private function findStaffIDByTicketID($ticketID)
	{
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select($db->quoteName(array('staff_id')));
        $query->from($db->quoteName('#__rsticketspro_tickets'));
        $query->where($db->quoteName('id') . " = " . $db->quote($ticketID));
		$query->setLimit('1');

        $db->setQuery($query);
        $staffID = $db->loadResult();

        return $staffID;
	}

	/**
	 * This method finds Customer id using Ticket id
	 */
	private function findCustomerIDByTicketID($ticketID)
	{
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select($db->quoteName(array('customer_id')));
        $query->from($db->quoteName('#__rsticketspro_tickets'));
        $query->where($db->quoteName('id') . " = " . $db->quote($ticketID));
		$query->setLimit('1');

        $db->setQuery($query);
        $customerID = $db->loadResult();

        return $customerID;
	}

	/**
	 * This method find user's name using her/his id.
	 */
	private function findNameByID($userID)
	{
		$userData = JFactory::getUser($userID);
		return $userData->name;
	}

	/**
	 * This method find user's Phone Number using her/his id.
	 */
	private function findPhoneNumberByUserID($userID)
	{
		$userProfile = JUserHelper::getProfile($userID);
		$phoneNumber = $userProfile->profile['phone'];

		return $this->validatePhoneNumber($phoneNumber);
	}

	/**
	 * This method checkes if the phone number is not empty and is valid
	 */
	private function validatePhoneNumber($phoneNumber)
	{
		if ($phoneNumber) {
			return $phoneNumber;
		} else return false;
	}
}