<?php
/*+**********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 ************************************************************************************/

require_once 'modules/com_vtiger_workflow/VTEventHandler.inc';
require_once 'modules/Emails/mail.php';
require_once 'modules/HelpDesk/HelpDesk.php';

class CommentsTagsHandler extends VTEventHandler {

	function handleEvent($eventName, $data) {
		global $site_URL, $adb, $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID;
		if($eventName == 'vtiger.entity.aftersave.final') {
			$moduleName = $data->getModuleName();
			if ( $moduleName == 'ModComments' ) {
				$id = $data->getId();
				$assigned_user_id = $data->get('assigned_user_id');
				$comentario = $data->get('commentcontent');
				$relatedToId = $data->get('related_to');
				$rs = $adb->pquery("SELECT setype FROM vtiger_crmentity where crmid = ?", array($relatedToId));
				$tabname = $adb->query_result($rs, 0, 'setype');
				$rs = $adb->pquery("SELECT ap.appname, t.tablabel, t.tabid FROM vtiger_app2tab ap
							inner join vtiger_tab t on ap.tabid = t.tabid 
							where t.tablabel = ? and ap.visible = 1
							limit 1", array($tabname));
				$appname = $adb->query_result($rs, 0, 'appname');
				$tabid = $adb->query_result($rs, 0, 'tabid');

				// 41 = Comentarios
				$rs = $adb->pquery("SELECT relation_id FROM vtiger_relatedlists where tabid = ? and related_tabid = 41", array($tabid));
				$relation_id = $adb->query_result($rs, 0, 'relation_id');

				$arr = explode(" ",$comentario);
				$users = array();
				$arr_emails = array();
				foreach($arr as $string) {
					if ( stripos($string,"@") !== false ) {
						$username = substr(trim($string), 1);
						$user = $this->CommentsTagsHandler_getUserByName($username);
						$users[] = $user;
						$arr_emails[] = $user['email'];
					}
				}
				
				if ( empty($users) ) return true;

				$url = $site_URL."index.php?module=$tabname&view=Detail&record=$relatedToId&mode=showDetailViewByMode&requestMode=summary&tab_label=&app=$appname";
				$link = "<a href='$url' target='_blank'>". vtranslate($tabname, $tabname) ."</a>";

				$files = $this->CommentsTagsHandler_getPathFiles($id);

				$usuario_comentario = $this->CommentsTagsHandler_getUsuarioComentario($id);

				require_once("modules/Emails/mail.php");
				$subject = "[CRM] Nuevo comentario de ".$usuario_comentario['nombre'];
			
				$contents = "Estimado(a), el usuario ".$usuario_comentario['nombre']." lo ha etiquetado en un comentario de ". vtranslate($tabname, $tabname) .": $link";
				$contents .= "<br><br><strong>Comentario:</strong>";
				$contents .= "<br><br> $comentario";
				if ( !empty($files) ) {
					$contents .= "<br><br>Documentos adjuntos: ";
					foreach ($files as $path => $title) {
						$contents .= "<br>";
						$contents .= "- <a href='$path' target='_blank'>$title</a>";
					}
				}

				$url_comm = $site_URL."index.php?module=$tabname&relatedModule=ModComments&view=Detail&record=$relatedToId&mode=showRelatedList&relationId=$relation_id&tab_label=ModComments&app=$appname";
				$link_comentarios = "<a href='$url_comm' target='_blank'>Ver comentario</a>";
				$contents .= "<br><br> Para ver el comentario haga clic en el siguiente enlace: $link_comentarios";
				$to_email = $arr_emails[0];
				// echo $subject;
				// echo "<br>";
				// echo $contents;
				// var_dump($arr_emails);
				send_mail($tabname, $to_email, $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID, $subject, $contents,$arr_emails,$bcc,'','','',true);
				// die();
			}
		}
	}

	function CommentsTagsHandler_getUserByName($username){
		global $adb;
		$rs = $adb->pquery("SELECT id, email1 as email, trim(concat(first_name,' ',last_name)) as nombre from vtiger_users where user_name = ? AND status = 'Active' AND deleted = '0'", array($username));
		$row = $adb->query_result_rowdata($rs);
		return array_map("decode_html", $row);
	}
	function CommentsTagsHandler_getUsuarioComentario($id_comentario){
		global $adb;
		$rs = $adb->pquery("SELECT id, email1 as email, trim(concat(first_name,' ',last_name)) as nombre FROM vtiger_crmentity e inner join vtiger_users u on e.smownerid = u.id where crmid = ?", array($id_comentario));
		$row = $adb->query_result_rowdata($rs);
		return array_map("decode_html", $row);
	}
	function CommentsTagsHandler_getPathFiles($id_comentario){
		global $adb, $site_URL, $root_directory;
		$rs = $adb->pquery("SELECT a.`name` as title, CONCAT(a.path,a.attachmentsid,'_',a.`name`) as file
					FROM vtiger_modcomments m INNER JOIN vtiger_seattachmentsrel r on m.modcommentsid = r.crmid
					inner join vtiger_attachments a on r.attachmentsid = a.attachmentsid
					WHERE m.modcommentsid = ?", array($id_comentario));
		$files = array();
		while ($row = $adb->fetch_row($rs)) {
			$file = $row['file'];
			if ( file_exists($root_directory.$file) ){
				$files[$site_URL.$file] = decode_html($row['title']);
			}
		}
		return $files;
	}
}