<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class PaymentReminder {

	private $CI = null;

	public $error = "";

	public $message = "";

	public function __construct()
	{
		$this->CI = &get_instance();
		$this->CI->load->model('cronModel');
		$this->error = '';
		$this->message = '';
	}

	public function trigger($job,$fromOutstanding=false)
	{    
		$contentCode	= 'PAYRM';
		$contentCode1  ='PAYRM';
		
		// $cut_ts = strtotime('-10 day', strtotime(gmdate('Y-m-d H:i:s')));
		$cut_ts = strtotime(gmdate('Y-m-d H:i:s'));
		$config = JSON_decode($job['actConfig'],true);
		// $config = JSON_decode('{"remindAfter":10,"remindAgain":0,"remindAbove":5500,"paymentautoremind":true,"Z":true,"ignoreCustomer":true,"noTransOver":"1","sendEmail":true,"sendSms":true,"exceptionFor":["C:13","2","C:17"]}',true);
		
		if (!$job || !$config['paymentautoremind'])
		{ 
			return false;
		}
		$cId 		= $job['cId'];		
		$cur_date 	= gmdate('Y-m-d');
		$noTransOver = date('Y-m-d', strtotime($cur_date.- (!empty($config["noTransOver"]) ? $config["noTransOver"] : 0 ).' Month')); // Ignore contact those not have transaction post months
		// $remindAfter = date('Y-m-d', strtotime($cur_date.- $config["remindAfter"].' days')); //Remind after days of Invoice Due Date
		// Remind again after last remaind Days
		$rmd_ts = strtotime('-'.$config['remindAgain'].' days', $cut_ts);
		    if($fromOutstanding){
				$contentCode1="OI";
			}
	
		// check email || sms content exists
			$this->CI->db->select('c.content, c.subject,c.cc,c.contentCode,sp.settings');
			$this->CI->db->from('compcontent as c');
			if($fromOutstanding){
				$this->CI->db->join('compsmtp as sp','sp.cId='.$cId.' and sp.type=replace(replace(c.contentCode,"'.$contentCode1.'",""),"'.$contentCode.'","")');
			}else{
		    	$this->CI->db->join('compsmtp as sp','sp.cId='.$cId.' and sp.type=replace(c.contentCode,"'.$contentCode.'","")');}
			$this->CI->db->where_in('c.contentCode', array($contentCode1 . 'E',$contentCode . 'S'));
			$this->CI->db->where_in('c.cId',array($cId,0));
			$this->CI->db->group_by('c.contentCode');
			$this->CI->db->order_by('c.cId desc');
			$data = $this->CI->db->get()->result_array();
		// print_E($this->CI->db->last_query());
		// print_E($data);
		// exit;
		//print_r($data);exit;
		if (!$data) {
				$this->CI->db->select('c.content, c.subject,c.cc,c.contentCode,sp.settings');
				$this->CI->db->from('compcontent as c');
				if($fromOutstanding){
					$this->CI->db->join('compsmtp as sp','sp.cId='.$cId.' and sp.type=replace(replace(c.contentCode,"'.$contentCode1.'",""),"'.$contentCode.'","")');
				}else{
				    $this->CI->db->join('compsmtp as sp','sp.cId='.$cId.' and sp.type=replace(c.contentCode,"'.$contentCode.'","")');}
				$this->CI->db->where_in('c.contentCode', array($contentCode1 . 'E',$contentCode . 'S'));
				$this->CI->db->where_in('c.cId',array(0));
				$this->CI->db->group_by('c.contentCode');
				$this->CI->db->order_by('c.cId desc');
				$data = $this->CI->db->get()->result_array();
			if (!$data) {
				$this->error = 'Default Content Required';
				return false;
			}
		}
	
	$data = array_key_index($data,'contentCode');
	if(!empty($config['sendEmail']) && empty($data[$contentCode1.'E'])){
		$this->error = 'SMTP Email Content Required';
		return false;
	}
	if(!empty($config['sendSms']) && empty($data[$contentCode.'S'])){
		$this->error = 'SMS details Required';
		return false;
	}
	
		//get company details
		$comp = $this->CI->db->select('name as CompanyName,phone as Companyphone')->from('companies')->where('id',$cId)->get()->row_array();
		$this->CI->db->select('ta.conId,ta.dueAmount,t.dueDate,t.tDate,if(cc.value,cc.value,0) as lst_ts',false);
		$this->CI->db->from('trans as t');
		$this->CI->db->join('trans_acc as ta','ta.transId=t.id and ta.conId!=0');
		$this->CI->db->join('contacts_config as cc','cc.conId=ta.conId and cc.code="ALERTDUE"','left');
		//$this->CI->db->join('contacts_config as cc','cc.conId=ta.conId','left');
		$where = array('t.cId' => $cId, 'ta.dueAmount >' => 0);
		$this->CI->db->where($where);
		if (!empty($config['exceptionFor'])) {
			$conIds = $tagIds = array();
			foreach ($config['exceptionFor'] as $val)
			{
				$val = explode(':',$val);
				if (count($val)>1) {
					$conIds[] = $val[1];
				} else {
					$tagIds[] = $val[0];
				}
			}

			if ($conIds) {
				$this->CI->db->where_not_in('ta.conId',$conIds);
			}
			if ($tagIds) {
				$this->CI->db->join('contacts_tags as ct','ct.conId=ta.conId','left');
				$this->CI->db->where_not_in('ct.tagId',$tagIds);
			}

		} else if(!empty($config['includeContact']) && count($config['includeContact']) > 0) {
			$this->CI->db->where_in('ta.conId',$config['includeContact']);
		}
		// $this->CI->db->group_by('ta.conId');
		if(!$fromOutstanding){
		$this->CI->db->having('lst_ts <=',$rmd_ts); }// remind again
		$this->CI->db->where_in('t.tType',array(SALINV, DBNOTE));
		// echo $this->CI->db->get_compiled_select();exit;
           //newly added --SUM(src.dueAmount) AS trdueAmount
		$query = 'SELECT c.id,c.name as conName,c.email,c.contactPersonMobile as phone,SUM(src.dueAmount) AS InvoiceDueAmount,c.balance AS totAmount,DATEDIFF(now(), min(src.dueDate)) as ddate, max(src.tDate) as dueDate FROM '
		.'('.$this->CI->db->get_compiled_select().') as src ' 
		.'JOIN '.$this->CI->db->dbprefix('contacts').' as c ON c.id=src.conId AND c.balance > 0'
		.(!empty($config['ignoreCustomer']) && !empty($config["noTransOver"]) ? (' where src.dueDate >"'.$noTransOver.'"'):'') // Ignore contact those not have transaction post months
		.(!empty($config['remindAfter']) ? (' group by src.conId having ddate  >='.$config['remindAfter'] .' and ') : ' group by src.conId having ')  //Remind after days of Invoice Due Date
		.'totAmount >='.(!empty($config['sendTotalDueOver']) && !empty($config['totalDueOver']) ? $config['totalDueOver'] : 0); //totalDueOver
		$rows = $this->CI->db->query($query)->result_array();

		$conName = trim(implode(PHP_EOL, array_column($rows, "conName")));
		$conName = $conName ? PHP_EOL . $conName : "";

		if (!empty($config['includeContact']) && count($config['includeContact']) > 0)
		{
			if(!empty(count($rows)))
			{
				$this->message = "Manual remainder tiggered successful For (".count($rows).") contact";
			}
			else
			{
				$this->message = "No payment reminders were sent. Try again later.";
			}
			
			file_put_contents('cron.txt',"Manual Remainder tiggered => (".count($rows).") contact : " . $conName . PHP_EOL,FILE_APPEND);
		}
		else
		{
			file_put_contents('cron.txt',"Payment Remainder tiggered => (".count($rows).") contact : " . $conName . PHP_EOL,FILE_APPEND);
		}
		
		if ($rows) {
			$count=0;
			foreach ($rows as $res) {
			
				$res = array_merge($res,$comp);
				$res["dueAmount"] = !empty($res["dueAmount"]) ? $res["dueAmount"] : $res["totAmount"];
				$this->CI->load->library('parser');
				if (!empty($config['sendEmail']) && !empty($data[$contentCode1 . 'E']) && !empty($res['email'])) {
					// email
					$eml = $data[$contentCode1. 'E'];
					if (!empty($eml['content']) && !empty($res['email']))
					{  
						if($fromOutstanding ){
						$eml["attach"]= $config["attach"][$res["id"]];}
						$eml['email'] 	= $res['email'];
						$res['CustomerName'] = $res['conName'];
						$res['DueDate'] = $res['dueDate'];
						$res['Total'] = $res['dueAmount'];
						$sms['cId']	= $cId;
						$sms['transId']='';
						$eml['subject'] = $this->CI->parser->parse_string($eml['subject'], $res, true);
						$eml['content'] = $this->CI->parser->parse_string($eml['content'], $res, true);						
						$result = $this->CI->cronModel->trigger_email($eml);
						if(empty($result)) {
							$this->error = $this->CI->cronModel->error;
						}
					}
				}

  
				if (!empty($config['sendSms']) && !empty($res['phone'])) {
					// sms
					$sms = $data[$contentCode . 'S'];
					$sms['settings'] = json_decode($sms['settings'],true);
					$sms['phone']	= $res['phone'];
					$sms['cId']	= $cId;
					$sms['transId']='';
					$sms['content'] = $this->CI->parser->parse_string($sms['content'], $res, true);					
					$sms = array_merge($sms,$res);					
					$result = $this->CI->cronModel->trigger_sms($sms);
					if(empty($result)) {
						$this->error = $this->CI->cronModel->error;
					}
				}
				// if(empty($this->error)) {
					// After sending an alert save the datetime(UTC) in ob_contacts_config with code as "ALERTDUE"
					$cur_qry = 'INSERT INTO ' . $this->CI->db->dbprefix("contacts_config").' (cId,conId,code,value) '
					.'VALUES ('.$cId.','.$res['id'].',"ALERTDUE",'.$cut_ts.') ON DUPLICATE KEY UPDATE value='.$cut_ts;
					$this->CI->db->query($cur_qry);
				// }
			$count++;	
			}
		}
		return true;
	}
}
