<?php
/**
 * @package Sj Contact Ajax
 * @version 1.3.2
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @copyright (c) 2013 YouTech Company. All Rights Reserved.
 * @author YouTech Company http://www.smartaddons.com
 *
 */

defined('_JEXEC') or die;
use Joomla\Component\Contact\Site\Controller\ContactController;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;

class ContactAjaxHelper
{
	public static function getList(&$params)
	{
		$list = array();
		$contact_id = (int)$params->get('contact_id');
		
		$app = Factory::getApplication();

		if ($contact_id != '') {
			
			$model = $app->bootComponent('com_contact')
				->getMVCFactory()->createModel('form', 'Site', ['ignore_request' => true]);		
			
			$list = $model->getItem($contact_id);
			
			return $list;
		} else {
			return false;
		}
	}

	public static function _processSendMail($mail_to)
	{
		$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
		if ($is_ajax) {
			$app = Factory::getApplication();
			$name = isset($_POST['name']) ? $_POST['name'] : '';
			$email = isset($_POST['email']) ? $_POST['email'] : '';
			$subject = isset($_POST['subject']) ? $_POST['subject'] : '';
			$date = isset($_POST['date']) ? $_POST['date'] : '';
			$body = isset($_POST['message']) ? $_POST['message'] : '';
			$prefix = Text::sprintf('COM_CONTACT_ENQUIRY_TEXT', Uri::base());
			//$body = $prefix . "\n" . $name . ' <' . $email . '>' . "\r\n\r\n" . stripslashes($body);
			$body = $prefix . "\n" . $name . ' <' . $email . '>' ."\n" . 'Date:' .$date . "\r\n\r\n" . stripslashes($body);
			$mailfrom = $app->get('mailfrom');
			$fromname = $app->get('fromname');
			$sitename = $app->get('sitename');
			$mail_to = ($mail_to != '') ? $mail_to : $mailfrom;
			$mail = Factory::getMailer();
			$mail->addRecipient($mail_to);
			$mail->addReplyTo($email, $name);
			$mail->setSender(array($mailfrom, $fromname));
			$mail->setSubject($sitename . ': ' . $subject);
			$mail->setBody($body);

			$sent = $mail->Send();


			if (isset($_POST['send_copy']) && $_POST['send_copy'] == 1) {
				$copytext = Text::sprintf('COM_CONTACT_COPYTEXT_OF', $name, $sitename);
				$copytext .= "\r\n\r\n" . $body;
				$copysubject = Text::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);

				$mail = Factory::getMailer();
				$mail->addRecipient($email);
				$mail->addReplyTo($email, $name);
				$mail->setSender(array($mailfrom, $fromname));
				$mail->setSubject($copysubject);
				$mail->setBody($copytext);
				$sent = $mail->Send();
			}
			$result = new stdClass();
			if ($sent !== true) {
				$result->status = 0;
				$result->message = 'Mail is not sent';
			} else {
				$result->status = 1;
				$result->message = 'Your email has been sent.';

			}
			echo json_encode($result);
			die();
		}
		return true;
	}

	public static function captcha()
	{

	}

}
