<?php
include_once ("_dirinfo.php");
include_once (PATH_TO_ROOT."CRM/_CRM_config.php");
include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."config.php");
include_once(PATH_TO_ROOT."CRM/class/class.checkString.php");
require_once(PATH_TO_ROOT.'TCPDF/config/lang/eng.php');
require_once(PATH_TO_ROOT.'TCPDF/tcpdf.php');
require_once (PATH_TO_ROOT."CRM/class/PHPMailer/class.phpmailer.php");

ini_set("display_errors", 1);

echo "<pre>";

$sql = "SELECT * FROM ".WARPIT_CRM."._CRMConfig WHERE prefix = 'autogeneratePDF'";
$res = $db->SQLexecute($sql);
while($row = $db->fetchAssoc($res)){
	$config[$row['cName']] = $row['cValue'];
}
$sql = "SELECT * FROM ".DB_WARPIT_MAIN."._WarpitConfig WHERE prefix='CRM' OR prefix='CRM_PDF'";
$res = $db->SQLexecute($sql);
while($row = $db->fetchAssoc($res)){
    $pdfSettings[$row['cName']] = $row['cValue'];
}

$ignoreDays = explode(", ",$config['ignore_days']);
$day = date("N");
foreach($ignoreDays as $key => $value){
	if($day == $value)
		exit;
}
$now = date("H:i");

$print = false;
$fileTime = "";
foreach($config as $key => $value){
	if(preg_match("/^time/", $key)){
		$nowTime = date("H:i",strtotime($now));
		$valueTime = date("H:i", strtotime($value));
		$nextTime = date("H:i", strtotime($nowTime . " -15 minutes")); 
		if($valueTime <= $nowTime  && $valueTime >= $nextTime){
			$fileTime = $value;
			$print = true;
		}
	}
}
$print = true;

if($print){
	$project = WEEK_NAME."_".date("W", strtotime("+1 weeks"))."_".date("Y");
	if($day == 1){
		$project = WEEK_NAME."_".date("W")."_".date("Y");
	}
	$fileName = "/tmp/[".date("Y-m-d H-i")."]".$project.".pdf";
	
	$sql = "SELECT id FROM ".DB_WARPIT_WEBCATI_BASE."._Projects WHERE proj_name = '".$project."'";
	$res = $db->SQLexecute($sql);
	$dat = $db->fetchAssoc($res);
	$projectId = $dat['id'];
	
	$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI.".".$project."_language WHERE `id_question` IN ( 9, 10 ) AND `id_text_type` = 3";
	$res = $db->SQLexecute($sql);
	while($row = $db->fetchAssoc($res)){
		$lang[] = explode("/", $row['lngText']);
	}
	foreach ($lang[0] as $day) {
		$tmp = explode(" ", $day);
		$days[$tmp[0]]['label'] = str_replace($tmp[0]." ", "", $day);	
	}
	foreach ($lang[1] as $t) {
		$tmp = explode(" ", $t);
		$time[$tmp[0]]['label'] = str_replace($tmp[0]." ", "", $t);
	}
	
	$sql = "SELECT id_tel FROM ".WARPIT_CRM."._actionLogger WHERE id_project = '".$projectId."'";
	$res = $db->SQLexecute($sql);
	$log = array();
	while($row = $db->fetchAssoc($res)){
		$log[] = $row['id_tel'];
	}
	
	$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".".$project."_structure WHERE status = 1 AND status_rec = 1";
	if(sizeof($log) > 0)
		$sql .= " AND id_tel NOT IN (".implode(", ", $log).")";
	
	$data = array();
	$res = $db->SQLexecute($sql);
	while($row = $db->fetchAssoc($res)){
		$data[] = $row;
	}
	if(sizeof($data) > 0 ){
			
		if($pdfSettings['useHTML'] == 0){
		
			$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			
			// set default header data	
			// set header and footer fonts
			
			$pdf->setPrintFooter(false);
			$pdf->setPrintHeader(false);
			//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, '', '');
			
			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
			$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
			
			//set margins
			$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_ODMIK_DESNO);
			
			//set auto page breaks
			$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
			
			//set image scale factor
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
			
			//set some language-dependent strings
			$lg = Array();
			$lg['a_meta_charset'] = 'UTF-8';
			$lg['a_meta_language'] = 'slv';
			$lg['w_page'] = 'Stran';
			$pdf->setLanguageArray($lg);
			$pdf->setHeaderTemplateAutoreset(TRUE);
			// ---------------------------------------------------------
			
			// set default font subsetting mode
			$pdf->setFontSubsetting(true);
			
			// Set font
			// dejavusans is a UTF-8 Unicode font, if you only need to
			// print standard ASCII chars, you can use core fonts like
			// helvetica or times to reduce file size.
			$pdf->SetFont('arial', '', PDF_VELIKOST_FONTA, '', true);
			
			// Add a page
			// This method has several options, check the source code documentation for more information.
			
			foreach($data as $item){
				$pdf->AddPage();
				//$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
$html = <<<EOD
		{$item['oseba_1']}<br>
		{$item['oseba_2']}<br>
		{$item['oseba_3']}<br>
EOD;
	$pdf->writeHTMLCell($w=0, $h=0, $x=PDF_ODMIK_LEVO, $y=PDF_ODMIK_ZGORAJ, $html, $border=0, $ln=1, $fill=0, $reseth=true, $align='', $autopadding=true);
	$pdf->SetFont('arial','',PDF_DOGODEK_VELIKOST_FONTA,'',true);
$html = <<<END
		Čas: {$days[$item['dan']]['label']}
		{$time[$item['ura']]['label']}<br>
		Kraj: {$item['dogodek_2']}<br>
END;
			$pdf->writeHTMLCell($w=0, $h=0, $x=PDF_DOGODEK_ODMIK_LEVO, $y=PDF_DOGODEK_ODMIK_ZGORAJ, $html, $border=0, $ln=1, $fill=0, $reseth=true, $align='', $autopadding=true);
		}
			 
			// Close and output PDF document
			// This method has several options, check the source code documentation for more information.
			
		}else{
			$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			
			// set default header data	
			// set header and footer fonts
			
			$pdf->setPrintFooter(false);
			$pdf->setPrintHeader(false);
			//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, '', '');
			
			
			// set default monospaced font
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
			$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
			
			//set margins
			$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_ODMIK_DESNO);
			
			//set auto page breaks
			$pdf->SetAutoPageBreak(FALSE);
			
			//set image scale factor
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
			
			//set some language-dependent strings
			$pdf->setHeaderTemplateAutoreset(TRUE);
			// ---------------------------------------------------------
			
			// set default font subsetting mode
			//$pdf->setFontSubsetting(true);
			
			// Set font
			// dejavusans is a UTF-8 Unicode font, if you only need to
			// print standard ASCII chars, you can use core fonts like
			// helvetica or times to reduce file size.
			
			//NI BOLD
			//$pdf->SetFont('arial', '', PDF_VELIKOST_FONTA, '', true);
			
			//JE BOLD 
			$pdf->SetFont('dejavusans', '', PDF_VELIKOST_FONTA, '', true);
			// Add a page
			// This method has several options, check the source code documentation for more information.
			
			foreach($data as $item){
				$pdf->AddPage();
				$html = $pdfSettings['HTML_template'];
				//print_r($item);
				$krajInfo = explode(" ", $item['oseba_3']);
				$imeInfo = explode(" ", $item['oseba_1']);
				$dogodekInfo = explode(",", $item['dogodek_2'], 2);
				
				$html = str_replace("«Firstname_Surname»", $item['oseba_1'], $html);
				$html = str_replace("«City»", $krajInfo[1], $html);
				$html = str_replace("«Address»", $item['oseba_2'], $html);
				$html = str_replace("«Post_code»", $krajInfo[0], $html);
				$html = str_replace("«Firstname»", $imeInfo[0], $html);
				$html = str_replace("«HOTEL»", $dogodekInfo[0], $html);
				$html = str_replace("«Location»", trim($dogodekInfo[1]), $html);
				$html = str_replace("«Time»", $days[$item['dan']]['label']. ", ". $time[$item['ura']]['label'], $html);
				//$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
				$pdf->writeHTMLCell(0,0,PDF_ODMIK_LEVO, PDF_ODMIK_ZGORAJ, $html, false, true, false, false, false, '');
				$pdf->lastPage();
			}
			 
			// Close and output PDF document
			// This method has several options, check the source code documentation for more information.
			
		}
	}
	$pdf->Output($fileName, 'F');
	$sql = "SELECT MAX(id_print) as max FROM ".WARPIT_CRM."._actionLogger";
    $rez = $db->SQLexecute($sql);
    $dat = $db->fetchAssoc($rez);
    $max = intval($dat['max'])+1;
	foreach ($data as $key => $value) {
		$sql = "INSERT INTO ".WARPIT_CRM."._actionLogger (id_project, id_filter, id_tel, id_action, actionDate, id_print, autoSent) VALUES('".$projectId."',   '".$value['smpl_var']."', '".$value['id_tel']."', '1', NOW(), '".$max."', 1)";
        $db->SQLexecute($sql);
	}
}

$mail = new PHPMailer(true);


$mail->IsSMTP(); // telling the class to use SMTP
try{
$mail->CharSet = 'UTF-8';
$mail->Host       = "mail.sors.si"; // SMTP server
$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "mail.sors.si"; // sets the SMTP server
$mail->Port       = 465;                    // set the SMTP port for the GMAIL server
$mail->Username   = "elixor@solve-x.net"; // SMTP account username
$mail->Password   = "el1xorSOLVEXXX";        // SMTP account password

$mail->From = 'elixor@solve-x.net';
$mail->FromName = "=?UTF-8?B?".base64_encode('PDF')."?=";

$to = explode(", ", $config['emails']); 
if(is_array($to)){
    foreach ($to as $key => $value) {
        $mail->AddAddress($value);
    }
}else{
    $mail->AddAddress($to);
}
$mail->AddBCC("marko.nniicc@gmail.com");

$mail->AddAttachment($fileName);         // Add attachments
//$mail->AddAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->IsHTML(true);                                  // Set email format to HTML
$subject = "PDF za ".$project;
$invited = sizeof($data);
$messageHTML = <<<EBO
<h1>Pozdravljeni</h1>
Pošiljamo vam PDF povabljenih za $project.<br>
Kjer je bilo povabljenih $invited ljudi
EBO;
$mail->Subject =  "=?UTF-8?B?".base64_encode( $subject )."?=";
$mail->Body    = $messageHTML;

if(!$mail->Send()) {
   echo "Something went wrong"; //če ni bilo poslano vrne 0
}  else {
    echo "It should be sent at ".date('d.m.Y H:i:s');   
}
}catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
//print_r($mail);
echo "</pre>";
?>