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

class RecurringTransaction {

	private $CI = null;

	public $error = '';

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

	public function trigger($job)
	{
		if (!$job)
		{
			return;
		}
		$cur_date = gmdate('Y-m-d');
		
		// get compcontent
		$content = $this->CI->db->select('cId,contentCode,content,subject,cc')->from('compcontent')->where(array('id' => $job['primeRefId']))->get()->row_array();
		if ($content) {
			$job = array_merge($job, $content);
		}
			
		// get job reference
		//get conId
		$this->CI->db->select('if(ct.conId,ct.conId,oja_r.refId) as conId',false);
		$this->CI->db->from('obojobact_ref as oja_r');
		$this->CI->db->join('contacts_tags as ct','ct.tagId=oja_r.refId and oja_r.refType="#"','left');
		$this->CI->db->where(array('oja_r.jobActId' => $job['jobActId']));
		$con_query = $this->CI->db->get_compiled_select();

		$this->CI->db->select('c.id')->from('contacts as c');
		$this->CI->db->where('c.id in ('.$con_query.')',null,false);
		$refs = $this->CI->db->get()->result_array();

		if (!$refs)
		{
			return true;
		}
		
		$this->CI->load->model('Users');
		$this->CI->Users->set_company_data($content['cId'], 0);

		$tmp_content = JSON_decode($job['content'],true);		
		// $actConfig = JSON_decode($job['actConfig'],true);
		$actConfig = $job['actConfig'];
				
		foreach ($refs as $ref)
		{
			// if ($ref['refType']=='C')
			// {
				$this->CI->load->model('contactsModel');
				$this->CI->load->model('transModel');
				$this->CI->load->model('companyModel');

				// overwrite contact details
				$tType = ltrim($job['contentCode'],'T');
				$con = $this->CI->contactsModel->get_conTrans_details($tType,$ref['id'],array('cId' => $job['cId']));

				// ignore con details
				if ($con['contact']) {
					unset($con['contact']['defaultPayAcc']);
					unset($con['contact']['plId']);
					unset($con['contact']['tds']);
					unset($con['contact']['salesDiscount']);
				}

				// select template based on client tax
				$data	= $tmp_content['I'];
				$data['allow_duplicate'] = true;
				if (get_company('stateId')!=$con['contact']['stateId']) {
					$data	= $tmp_content['X'];
				}
				$data['contact'] = (!empty($data['contact']) && is_array($data['contact']))?$data['contact']:array();
				$contacts = $data['contact'] = array_merge($data['contact'],$con['contact']);
				$data['conId']			= $ref['id'];
				$data['conTaxNo'] 		= $contacts['conTaxNo'] = $contacts['taxNo'];				
				$data['conName'] 		= $contacts['name'];
				$data['conStateCode'] 	= $contacts['stateCode'];
				$data['conStateId'] 	= $contacts['stateId'];
				$data['conTaxScheme'] 	= $contacts['conTaxScheme'];

				// address
				if ($con['address']) {
					$data['shippingAddr'] = $data['billingAddr'] = $con['address'][0];
					if ($data['billingAddr']['addrType']!='A') {
						$data['shippingAddr'] = $con['address'][1];
					}
					$data['shippingAddr']['name'] = $data['billingAddr']['name'] = $data['contact']['name'];
				}
				
				$data['tDate'] 		= !empty($data['tDate'])?$data['tDate']:$cur_date;
				$data['dueDate'] 	= !empty($data['dueDate'])?$data['dueDate']:$cur_date;

				$due_diff 	= abs(strtotime($data['dueDate']) - strtotime($data['tDate'])) / (60 * 60 * 24);
				
				if(strtotime($data['tDate']) < strtotime($cur_date)) {
					$data['dueDate'] 	= $data['tDate'] = $cur_date;
				}
				
				if ($due_diff>0)
				{
					$data['dueDate'] 	= date('Y-m-d', strtotime($data['tDate']." + $due_diff days"));
				}

				/* check duplicate already exists

				if the same item is chosen for the same customer with the same quantity but different notes or terms selected, those will still not enter
				##wrinklefreeit##

				$this->CI->db->select('t.id, group_concat(ti.itemId) as itmids')->from('trans as t');
				$this->CI->db->join('trans_items as ti','ti.transId=t.id');
				$this->CI->db->where(array('t.cId' => $job['cId'], 't.tDate' => $data['tDate'], 't.tType' => $data['tType'],
				't.conId' => $data['conId'], 't.taxableAmount ' => $data['taxableAmount'], 't.totAmount' => $data['totAmount']));
				$tmp = $this->CI->db->get()->row_array();
				if (!empty($tmp['itmids'])) {
					$item_ids = explode(',',$tmp['itmids']);
					foreach ($data['details'] as $itm)
					{ // check items unique
						$item_ids = array_diff($item_ids, array($itm['itemId']));
					}
					if (!$item_ids)
					{
						$this->error_log(array('error' => 'Duplicate'.PHP_EOL.'=='.PHP_EOL.print_R($data,true),'cId' => $job['cId'], 'type' => 'Recurring transaction'));
						continue;
					}					
				}*/

				$data['bId'] = $job['bId'];

				if (!$result = $this->CI->transModel->save($data)) {
					$this->error.= $this->CI->transModel->message;
					$this->error_log(array('error' => $this->CI->transModel->message.PHP_EOL.'=='.PHP_EOL.print_R($data,true),'cId' => $job['cId'], 'type' => 'Recurring transaction'));
					continue;
				}

				if (in_array($tType,array(SALINV,SALRETAIL)) && empty($actConfig['isDraft']))
				{
					$mail_params = array('tId' => $result['id'],'status' => 'S','tType' => $tType);
					if (!empty($actConfig['sendEmail']))
					{
						$config = $this->CI->companyModel->emailcontent($result['id']);
						$mail_params = array_merge($mail_params,$config);
					}

					if ($this->CI->transModel->sendmail($mail_params)) {
						// $this->error.= $this->CI->transModel->message;
						$this->error_log(array('error' => $this->CI->transModel->message.PHP_EOL.'=='.PHP_EOL.print_R($data,true),'cId' => $job['cId'], 'type' => 'Recurring transaction'));
					}
				}
			// }
		}

		return true;
	}

	private function error_log($log) {
		$this->CI->load->helper('file');
        $file_path = 'temp'.DS.'cron'.DS.'recurring'.DS.$log['cId'];

        if(!is_dir($file_path))
        {
            mkdir($file_path, 0755, TRUE);
		}
		
		$output ="=====================".base_url(uri_string())."=====================\n";
		$output.=$log['error']."\n";
		if ( ! write_file(FCPATH  . $file_path."/log.txt", $output, 'a+')){
            log_message('debug','Unable to write query the file');
        }
	}
}
