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

class EmailTemplate extends CI_Controller
{

	/** 
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	var $columnNames = [];
	var $customCol = [
		"company_id" => ["table" => "info_settings", "alias" => "dc", "column" => "companyName", "key2" => "infoID" , "select" => ""],
		"modified_by" => ["table" => "admin", "alias" => "am", "column" => "name", "key2" => "adminID" , "select" => ""],
		"created_by" => ["table" => "admin", "alias" => "ad", "column" => "name", "key2" => "adminID" , "select" => ""],			
	];

	function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->model('CommonModel');
		$this->load->library("pagination");
		$this->load->library("response");
		$this->load->library("ValidateData");
		$this->load->library("Datatables");
		$this->load->library("Filters");
	}

	public function list(){
		$this->access->checkTokenKey();
		$this->response->decodeRequest();
		$this->menuID = $this->input->post('menuId');
		$isAll = $this->input->post('getAll');
		$curPage = $this->input->post('curpage');
		$orderBy = $this->input->post('orderBy');
		$order = $this->input->post('order');
		$statuscode = $this->input->post('status');
		$isSystem = $this->input->post('is_sys_temp');
		$wherec = $join = array();
		$config = $this->config->item('pagination');
		if($isAll !="Y"){
			$this->filters->_initialize();
			$wherec = $join = array();
			$wherec = $this->whereData["wherec"];
			$other = $this->whereData["other"];
			$join = $this->whereData["join"];
			$selectC = $this->whereData["select"];	
		}else{
			if (isset($statuscode) && !empty($statuscode)) {
				$statusStr = str_replace(",", '","', $statuscode);
				$wherec["t.status"] = 'IN ("' . $statusStr . '")';
			}
			$wherec["t.is_sys_temp ="] = "'no'";
		}
		if (!isset($orderBy) || empty($orderBy)) {
			$orderBy = "tempID";
			$order = "ASC";
		}
		$other["orderBy"] = $orderBy;
		$other["order"]= $order;
		$config["base_url"] = base_url() . "email_master";
		$config["total_rows"] = $this->CommonModel->getCountByParameter('t.tempID', "email_master", $wherec);
		$config["uri_segment"] = 2;
		$this->pagination->initialize($config);
		if (isset($curPage) && !empty($curPage)) {
			$curPage = $curPage;
			$page = $curPage * $config["per_page"];
		} else {
			$curPage = 0;
			$page = 0;
		}
		if ($isAll == "Y") {
			$emailsDetails = $this->CommonModel->GetMasterListDetails($selectC="tempID,tempName,emailContent,smsContent",'email_master',$wherec,'','',$join,$other);	
		}else{
			$selectC = ($selectC != "") ? 't.tempName,t.subjectOfEmail,t.emailContent,t.created_date,'.$selectC : 't.tempName,t.subjectOfEmail,t.emailContent,t.created_date';
			$emailsDetails = $this->CommonModel->GetMasterListDetails($selectC, 'email_master', $wherec, $config["per_page"], $page, $join, $other);
		}
		$status['data'] = $emailsDetails;
		$status['paginginfo']["curPage"] = $curPage;
		$status['paginginfo']["prevPage"] = ($curPage <= 1) ? 0 : $curPage - 1 ; 
		$status['paginginfo']["pageLimit"] = $config["per_page"];
		$status['paginginfo']["nextpage"] =  $curPage + 1;
		$status['paginginfo']["totalRecords"] =  $config["total_rows"];
		$status['paginginfo']["start"] =  $page;
		$status['paginginfo']["end"] =  $page + $config["per_page"];
		$status['loadstate'] = true;
		if ($config["total_rows"] <= $status['paginginfo']["end"]) {
			$status['msg'] = $this->systemmsg->getErrorCode(232);
			$status['statusCode'] = 400;
			$status['flag'] = 'S';
			$status['loadstate'] = false;
			$this->response->output($status, 200);
		}
		if ($emailsDetails) {
			$status['msg'] = "sucess";
			$status['statusCode'] = 400;
			$status['flag'] = 'S';
			$this->response->output($status, 200);
		} else {
			$status['msg'] = $this->systemmsg->getErrorCode(227);
			$status['statusCode'] = 227;
			$status['flag'] = 'F';
			$this->response->output($status, 200);
		}
	}
	public function templateDetails($id = ''){
		//$this->access->checkTokenKey();
		$this->response->decodeRequest();
		$this->menuID = $this->input->post('menuId');
		$method = $this->input->method(TRUE);
		$emailMasterDetails = array();
		$updateDate = date("Y/m/d H:i:s");
		if ($method == "PUT" || $method == "POST") {
			$emailMasterDetails['tempName'] = $this->validatedata->validate('tempName', 'Temp Name', true, '', array());
			$emailMasterDetails['readName'] = $this->validatedata->validate('readName', 'Email Name', false, '', array());
			$emailMasterDetails['emailContent'] = $this->validatedata->validate('emailContent', 'Email Content', true, '', array());
			//$emailMasterDetails['smsContent'] = $this->validatedata->validate('smsContent', 'SMS Content', true, '', array());
			$emailMasterDetails['subjectOfEmail'] = $this->validatedata->validate('subjectOfEmail', 'Subject Of Email', false, '', array());
			$emailMasterDetails['status'] = 'active';//$this->validatedata->validate('status', 'status', true, '', array());

			$menuDetails = $this->datatables->getMenuDetails($this->menuID);
    		$fieldData = $this->datatables->mapDynamicFeilds($menuDetails->menuLink, $this->input->post());

			if ($method == "PUT") {
				$emailMasterDetails['tempUniqueID'] = "temp_" . rand(0, 9999);
				$emailMasterDetails['created_by'] = $this->input->post('SadminID');
				$emailMasterDetails['created_date'] = $updateDate;
				$emailMasterDetails['modified_date'] = null;

				$this->db->trans_start();
				$iscreated = $this->CommonModel->saveMasterDetails('email_master', $emailMasterDetails);
				if (!$iscreated) {
					$this->db->trans_rollback();
					$status['msg'] = $this->systemmsg->getErrorCode(998);
					$status['statusCode'] = 998;
					$status['data'] = array();
					$status['flag'] = 'F';
					$this->response->output($status, 200);
				} else {
					$this->filters->upsertDynamicData();
					$this->db->trans_commit();
					$status['msg'] = $this->systemmsg->getSucessCode(400);
					$status['statusCode'] = 400;
					$status['data'] = array();
					$status['flag'] = 'S';
					$this->response->output($status, 200);
				}
			}

			if ($method == "POST") {
				$where = array('tempID' => $id);
				if (!isset($id) || empty($id)) {
					$status['msg'] = $this->systemmsg->getErrorCode(998);
					$status['statusCode'] = 998;
					$status['data'] = array();
					$status['flag'] = 'F';
					$this->response->output($status, 200);
				}
				$emailMasterDetails['modified_by'] = $this->input->post('SadminID');
				$emailMasterDetails['modified_date'] = $updateDate;
				$this->db->trans_start();
				$iscreated = $this->CommonModel->updateMasterDetails('email_master', $emailMasterDetails, $where);
				if (!$iscreated) {
					$this->db->trans_rollback();
					$status['msg'] = $this->systemmsg->getErrorCode(998);
					$status['statusCode'] = 998;
					$status['data'] = array();
					$status['flag'] = 'F';
					$this->response->output($status, 200);
				} else {
					$this->filters->upsertDynamicData($id);
					$this->db->trans_commit();
					$status['msg'] = $this->systemmsg->getSucessCode(400);
					$status['statusCode'] = 400;
					$status['data'] = array();
					$status['flag'] = 'S';
					$this->response->output($status, 200);
				}
			}
		} else if ($method == "DELETE") {
			$emailMasterDetails = array();
			$where = array('tempID' => $id);
			if (!isset($id) || empty($id)) {
				$status['msg'] = $this->systemmsg->getErrorCode(996);
				$status['statusCode'] = 996;
				$status['data'] = array();
				$status['flag'] = 'F';
				$this->response->output($status, 200);
			}
			$iscreated = $this->CommonModel->deleteMasterDetails('email_master', $where);
			if (!$iscreated) {
				$status['msg'] = $this->systemmsg->getErrorCode(996);
				$status['statusCode'] = 996;
				$status['data'] = array();
				$status['flag'] = 'F';
				$this->response->output($status, 200);
			} else {
				$status['msg'] = $this->systemmsg->getSucessCode(400);
				$status['statusCode'] = 400;
				$status['data'] = array();
				$status['flag'] = 'S';
				$this->response->output($status, 200);
			}
		} else {
			if($id ==""){
				$status['msg'] = $this->systemmsg->getSucessCode(400);
				$status['statusCode'] = 400;
				$status['data'] =array();
				$status['flag'] = 'S';
				$this->response->output($status,200);
			}
			$this->filters->_initialize('yes');
			$wherec = $join = array();
			$wherec = $this->whereData["wherec"];
			$other = $this->whereData["other"];
			$join = $this->whereData["join"];
			$selectC = $this->whereData["select"];	
			$wherec["t.tempID ="] = "'".$id."'";	
			if ($selectC != "") {
				$selectC = "t.*," . $selectC;
			}
			$emailMasterDetails = $this->CommonModel->GetMasterListDetails($selectC, $this->menuDetails->table_name, $wherec, '', '', $join, array());
			if (isset($emailMasterDetails) && !empty($emailMasterDetails)) {
				$status['data'] = $emailMasterDetails;
				$status['statusCode'] = 200;
				$status['flag'] = 'S';
				$this->response->output($status, 200);
			} else {
				$status['msg'] = $this->systemmsg->getErrorCode(227);
				$status['statusCode'] = 227;
				$status['data'] = array();
				$status['flag'] = 'F';
				$this->response->output($status, 200);
			}
		}
	}
	public function emailMasterDataChangeStatus()
	{
		$this->access->checkTokenKey();
		$this->response->decodeRequest();
		$action = $this->input->post("action");
		if (trim($action) == "changeStatus") {
			$ids = $this->input->post("list");
			$statusCode = $this->input->post("status");
			$changestatus = $this->CommonModel->changeMasterStatus('email_master', $statusCode, $ids, 'tempID');

			if ($changestatus) {

				$status['data'] = array();
				$status['statusCode'] = 200;
				$status['flag'] = 'S';
				$this->response->output($status, 200);
			} else {
				$status['data'] = array();
				$status['msg'] = $this->systemmsg->getErrorCode(996);
				$status['statusCode'] = 996;
				$status['flag'] = 'F';
				$this->response->output($status, 200);
			}
		}
	}

	public function multipleemailChangeStatus(){
		$this->access->checkTokenKey();
		$this->response->decodeRequest();
		$action = $this->input->post("action");
		$ids = $this->input->post("list");
		$statusCode = $this->input->post("status");
		$menuId = $this->input->post("menuId");
		if (trim($action) == "delete") {
			$whereIn ['tempID']= $ids;
			$changestatus = $this->CommonModel->multipleDeleteMasterDetails('email_master', '',$whereIn);
		}else{
			$changestatus = $this->CommonModel->changeMasterStatus('email_master', $action, $ids, 'tempID');
		}
		if ($changestatus) {				
			$status['data'] = array();
			$status['statusCode'] = 200;
			$status['flag'] = 'S';
			$this->response->output($status, 200);
		} else {
			$this->response->outputErrorResponse(996);
		}
	}

}
