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

class Merchants extends MY_Controller {

	function __construct(){
		parent::__construct();	
		$this->load->model('admin/Merchants_model');
		$this->load->model('Users_model');
		$this->load->model('admin/Broadcast_model');
		$this->load->model('Home_model');	

		$config['upload_path']          = 'uploads/broadcast/';
		$config['allowed_types']        = 'gif|jpg|png|jpeg|pdf|txt|mp4';
		$config['max_size'] 			= 12000000;
        $config['max_width'] 			= 15500000;
        $config['max_height'] 			= 15500000;
		$this->upload->initialize($config);	
	}


	
		public function index($param=null)
	{
			echo $param;
	}
	
	public function auth($param=null)
	{
			if($param)
			{
				$count = $this->Merchants_model->authchk($param);
				if($count == 1){
					$response = $this->Merchants_model->merchantData($param);
					//print_r($response);					
					$this->session->set_userdata('isLogin', TRUE);
					
					$this->session->set_userdata('merchantId',$response->merchantId);
					$this->session->set_userdata('merchantname',$response->name);
					$this->session->set_userdata('merchantemail',$response->email);
					$this->session->set_userdata('merchantcontact',$response->contact);
					$this->session->set_userdata('merchantavtar',$response->icon);
					$this->session->set_userdata('infobipheader',$response->headerkeyINFOBIP);
					$this->session->set_userdata('rmlheader',$response->headerkeyRML);
					//added by mithlesh for Airtel
					$this->session->set_userdata('Airtelheader',$response->headerkeyAirtel);
					//added by mithlesh for Airtel
					$this->session->set_userdata('infobipscenario',$response->scenariokeyINFOBIP);
					
					$this->session->set_userdata('systype','MERCHANTS');
						//print_r($_SESSION);
					redirect(base_url('merchants/broadcast'));
				
				}else{
					echo "Account Not Exists";
					$this->data['msg']='<div class="alert alert-danger">Failed Login: Use Username & Password to Login!</div>';
					//$this->merchantloginview('login',$this->data);
				}
			}
			else{
				
			}
	}
	
	public function broadcast()
	{		
	//print_r($_SESSION);
			if($this->session->userdata('isLogin') == FALSE && $this->session->userdata('systype') != 'MERCHANTS'){ redirect(base_url('merchants/login')); }
			if(isset($_POST['submit'])){
				
				$braodcastdata=array();
				$braodcastdata['campaignname']= $_POST['campaignname'];
				$braodcastdata['merchantId']= @$_SESSION['merchantId'];
				$braodcastdata['templateId']=$_POST['template'];
				$braodcastdata['parameters']=serialize(@$_POST['parameters']);
				$braodcastdata['createdon']=date('Y-m-d H:i:s');
				$braodcastdata['sendon']=$_POST['scheduledate'];
				
				$braodcastdata['btn1url']=@$_POST['btn1'];
				$braodcastdata['btn2url']=@$_POST['btn2'];
				
				if(@$_FILES['image']['name'] !=''){
					if (!$this->upload->do_upload('image')) {
						$this->session->set_flashdata('page_message', '<div class="alert alert-danger text-center"> '.$this->upload->display_errors().'</div>');
						$formerror = 1; 
						$braodcastdata['media']='';
						//print_r($this->upload->display_errors());
						//exit;
					} 				
					else {  
						$imgdata = $this->upload->data('file_name');  $formerror = 0; 
						$braodcastdata['media']=$imgdata;		
					}
				}				
				
				elseif(@$_FILES['video']['name'] !=''){
					if (!$this->upload->do_upload('video')) {
						$this->session->set_flashdata('page_message', '<div class="alert alert-danger text-center"> '.$this->upload->display_errors().'</div>');
						$formerror = 1; 
						$braodcastdata['media']='';
						//print_r($this->upload->display_errors());
						//exit;
					} 				
					else {  
						$imgdata = $this->upload->data('file_name');  $formerror = 0; 
						$braodcastdata['media']=$imgdata;		
					}
				}
				elseif(@$_FILES['document']['name'] !=''){
					if (!$this->upload->do_upload('document')) {
						$this->session->set_flashdata('page_message', '<div class="alert alert-danger text-center"> '.$this->upload->display_errors().'</div>');
						$formerror = 1; 
						$braodcastdata['media']='';
						//print_r($this->upload->display_errors());
						//exit;
					} 				
					else {  
						$imgdata = $this->upload->data('file_name');  $formerror = 0; 
						$braodcastdata['media']=$imgdata;		
					}
				}else{
					$braodcastdata['media']='';
				}
				
				
				
				
				$sendno = explode(PHP_EOL, $_POST['contacts']);
				
				
				//print_r($braodcastdata);
				//echo $_POST['contacts'];
				//print_r($sendno);
				//exit;
				$totalno=0;
				$scheduledno=0;
				$errno=0;
				
				$totalrecords = array();
				$r=0;
				foreach ($sendno as $contact){
						$contact = preg_replace('/\s+/', '', $contact);
						if(validate_mobile($contact))
						{
							$entry=array();
							$entry['campaignname']=$braodcastdata['campaignname'];
							$entry['merchantId']=$braodcastdata['merchantId'];
							$entry['templateId']=$braodcastdata['templateId'];
							$entry['parameters']=$braodcastdata['parameters'];
							$entry['contact']= $contact;
							$entry['media']=$braodcastdata['media'];
							$entry['createdon']=$braodcastdata['createdon'];
							$entry['sendon']=$braodcastdata['sendon'];
							$entry['btn1url']=$braodcastdata['btn1url'];
							$entry['btn2url']=$braodcastdata['btn2url'];
							//print_r($entry);
							$totalrecords[$r]=$entry;
							//$this->Broadcast_model->insert_merchant_campaign($entry);
							$scheduledno++;
							$r++;
						}else{
							$errno++;
						}
						
						$totalno++;						
				}
				
				$this->Broadcast_model->insert_merchant_campaign_bulk($totalrecords);
				
				$this->session->set_flashdata('page_message', '<div class="alert alert-success text-center"> 
				<b>Total Numbers Found :</b> '.$totalno.'<br/> <b>Total Message Scheduled :</b>'.$scheduledno.'<br/>
				<b>Invalid Contacts Found :</b>'.$errno.'</div>');
				
				$mdata=array();					
				$mdata['credits']=$scheduledno;
				$mdata['mode']='MERCHANT';
				$mdata['txnId']='';
				$mdata['message']='MERCHANT CONSUPTION';
				$mdata['type']='DEBIT';
				$mdata['amount']='0';
				$mdata['createdon']=date('Y-m-d H:i:s');
				$mdata['updatedon']=date('Y-m-d H:i:s');
				$this->Merchants_model->remove_credit_account(@$_SESSION['merchantId'],$mdata);
				
				//$this->sendwahtsappmessage();
				
				redirect(base_url('merchants/broadcast'));
				}		
			
			else{
			$data['pagetitle']='WhatsApp Messaging Templates for Marketing';
			if(isset($_POST['status'])){$data['status'] = $_POST['status'];}else{$data['status']='-1';}
			
			//$data['response'] = $this->Merchants_model->get_merchant_group($data['status']);
			$data['updatelink']=base_url('admin/broadcast/grouppublish');
			$data['deletelink']=base_url('admin/broadcast/groupdelete');
			$header=$footer=array();
			$data['templateesoptions'] =$this->gettemplates();
			$footer['pagejs']=$this->preview();
			$data['response']=$this->Broadcast_model->get_merchant_messages($_SESSION['merchantId']);
			$this->merchantview('broadcast/sendwhatsapp',$data,$header,$footer);
			}			
		
	}
	
	public function gettemplates(){
		$merchantId = $_SESSION['merchantId'];
		$merchanttemplates = $this->Broadcast_model->get_merchant_templates($merchantId);
		//$merchanttemplates =getdata('*','templates');
		$option='';
		foreach($merchanttemplates as $mt){
			$option.='<option value="'.$mt->templateId.'">'.$mt->templatename.'</option>';
		}
		
		return $option;
	}
	
	public function gettemplatesdata(){
		$templateId = $_POST['templateId'];
		$templatedata = getdata('*','templates',array('templateId='=>$templateId));
		$html='';
		
		if($templatedata[0]->header_type == 'TEXT'){
		/*$html.='<div class="form-group row">
							<label for="input-21" class="col-sm-3 col-form-label">Template Name</label>
							<div class="col-sm-9">
								<input type="text" name="name" class="form-control" placeholder="Enter Template Name">
							</div>
					</div>'; */
		}elseif($templatedata[0]->header_type == 'MEDIA'){
			$html.='<div class="form-group row">
							<label for="input-21" class="col-sm-3 col-form-label">Select Image To Send</label>
							<div class="col-sm-9">
								<input type="file" name="image" id="uploadmedia" class="form-control sendmedia" onChange="validate(this,\'image\')" accept=".jpg,.png,.jpeg">
							<div id="sendmediaerr" class="p-2" style="display:none"></div>
							</div>
					</div>';
		}
		
		elseif($templatedata[0]->header_type == 'VIDEO'){
			$html.='<div class="form-group row">
							<label for="input-21" class="col-sm-3 col-form-label">Select Video To Send</label>
							<div class="col-sm-9">
								<input type="file" name="video" id="uploadmedia" class="form-control sendmedia" onChange="validate(this,\'video\')" accept=".mp4">
							<div id="sendmediaerr" class="p-2" style="display:none"></div>
							</div>
					</div>';
		}
		
		elseif($templatedata[0]->header_type == 'DOCUMENT'){
			$html.='<div class="form-group row">
							<label for="input-21" class="col-sm-3 col-form-label">Select Document To Send</label>
							<div class="col-sm-9">
								<input type="file" name="document" id="uploadmedia" class="form-control sendmedia" onChange="validate(this,\'doc\')" accept=".pdf,.txt,.doc">
							<div id="sendmediaerr" class="p-2" style="display:none"></div>
							</div>
					</div>';
		}
		
		for($i=1;$i<=$templatedata[0]->parameters;$i++){
			$html.='<div class="form-group row">
							<label for="input-21" class="col-sm-3 col-form-label">Parameter '.$i.'</label>
							<div class="col-sm-9">
								<input type="text" name="parameters[]" class="form-control prevfield" placeholder="Enter Parameter '.$i.'">
							</div>
					</div>'; 
		}
		
		if(strpos($templatedata[0]->btn_1_url, '{{var}}') !== false){
			$html.='<div class="form-group row">
							<label for="input-21" class="col-sm-3 col-form-label">Button One Url</label>
							<div class="col-sm-9">
								<input type="text" name="btn1" class="form-control prevfield" placeholder="Enter Button One URL">
							</div>
					</div>'; 
		}
		
		if(strpos($templatedata[0]->btn_2_url, '{{var}}') !== false){
			$html.='<div class="form-group row">
							<label for="input-21" class="col-sm-3 col-form-label">Button Two Url</label>
							<div class="col-sm-9">
								<input type="text" name="btn2" class="form-control prevfield" placeholder="Enter Button Two URL">
							</div>
					</div>'; 
		}
		
		echo $html;
	}
	
	public function preview(){
		$js='';
		$js.="$(document).ready(function(){";
 
		$js.= "$('.prevfield' ).on('change', function(){
					console.log('preview');
					var headertxt=$('#headertext').val();
					var headerimgfile=$('#headerfile')[0].files[0];
					var headerimg=$('#prvlink').val(headerimgfile);
					var bodytxt=$('#bodytxt').val();
					var footer=$('#footertxt').val();
					var btn1txt=$('#btn1text').val();
					var btn2txt=$('#btn2text').val();
					
					console.log(headertxt);
					console.log(headerimg);
					console.log(bodytxt);
					console.log(footer);
					console.log(btn1txt);
					console.log(btn2txt);
					
					var prevcontain = '';
					
					if( headertxt ) {prevcontain=prevcontain+'<div class=\"prvhead\">'+headertxt+'</div>';}
					
					if( bodytxt ) {prevcontain=prevcontain+'<div class=\"prvbody\">'+bodytxt+'</div>';}
					
					if( footer ) {prevcontain=prevcontain+'<div class=\"prvfooter\">'+footer+'</div>';}
					
					if( btn1txt ) {prevcontain=prevcontain+'<button class=\"btn btn-primary btn-block\">'+btn1txt+'</button><br/>';}
					
					if( btn2txt ) {prevcontain=prevcontain+'<button class=\"btn btn-primary btn-block\">'+btn2txt+'</button><br/>';}
					
					console.log(prevcontain);
					$('.wamsg-prev').html(prevcontain);
					
				 });"; 
					
		$js.="});";
		$js.='function PreviewImage(file) {
       		var reader = new FileReader();

        reader.onload = function (e) {
           // console.log(e.target.result);
			$("#prvlink").val(e.target.result);
        }
        reader.readAsDataURL($("#headerfile")[0].files[0]);
        };
    ';				 
		return $js;
	}
	
	public function csvfilecheck(){
		if(!empty($_FILES["file"]["name"]))
{
 
			// Allowed mime types
			$fileMimes = array(
				'text/x-comma-separated-values',
				'text/comma-separated-values',
				'application/octet-stream',
				'application/vnd.ms-excel',
				'application/x-csv',
				'text/x-csv',
				'text/csv',
				'application/csv',
				'application/excel',
				'application/vnd.msexcel',
				'text/plain'
			);
		 	
			$number = '';
			// Validate whether selected file is a CSV file
			if (!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $fileMimes))
			{
		 
					// Open uploaded CSV file with read-only mode
					$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
		 
					// Skip the first line
					fgetcsv($csvFile);
		 	
					// Parse data from CSV file line by line
					 while(($row = fgetcsv($file_data)) !== FALSE)
  {
						// Get row data
						//$number.= $getData[0];
						 print_r($row);
					}
		 
					// Close opened CSV file
					fclose($csvFile);
		 			
					echo $number;
					echo "Success";
				 
			}
			else
			{
				echo "Invalid File Selected";
			}
		}else{
		  echo "Invalid File Selected";  
		}
	}
	
	
	public function sendwahtsappmessage(){
		$this->load->model('Cronjob_model');
		$messages = $this->Cronjob_model->getmessages();
		//print_r($messages);
		foreach($messages as $msg){
			if($msg->operator == 'Infobip')
			{
				$this->sendinfobipmsg($msg);
				//$this->sendrmlmsg($msg);
			}
			elseif($msg->operator == 'RMS')
			{
				$this->sendrmlmsg($msg);
			}
			//Added by Mithlesh
			elseif($msg->operator == 'Airtel')
			{
				$this->sendAirtelmsg($msg);
			}
			//Added by Mithlesh
		}
	}
	
	public function sendinfobipmsg($msg){
		//	echo "Infobip";
		//	echo "<br/>";
		//	echo "<br/>";
			
			
			if($msg->btn_1_url != null && $msg->btn_1_url == "{{var}}"){
				$msg->btn1url = 'https://bynow.co.in/redirect.html?url='.$msg->btn1url;
			}
			elseif($msg->btn_1_url != null && $msg->btn_1_url != "{{var}}"){
				$msg->btn1url = $msg->btn1url;
			}
			
			if($msg->btn_2_url != null && $msg->btn_2_url == "{{var}}"){
				$msg->btn2url = 'https://bynow.co.in/redirect.html?url='.$msg->btn2url;
			}
			elseif($msg->btn_2_url != null && $msg->btn_2_url != "{{var}}"){
				$msg->btn2url = $msg->btn2url;
			}
			//print_r($msg);
			//echo "<br/>";
			//echo "<br/>";
			if($msg->header_type == 'VIDEO'){
				videoheader($msg->name,'+91'.$msg->contact,unserialize($msg->parameters),$msg->media,$msg->header_type,$msg->btn1url,$msg->btn2url);
			}else{
				imageheader($msg->name,'+91'.$msg->contact,unserialize($msg->parameters),$msg->media,$msg->header_type,$msg->btn1url,$msg->btn2url);
			}
	}
	
	public function sendrmlmsg($msg=null){
			//echo "RMS";
			//print_r($msg);
			
			if($msg->btn_1_url != null && $msg->btn_1_url == "{{var}}"){
				$msg->btn1url = 'https://bynow.co.in/redirect.html?url='.$msg->btn1url;
			}
			elseif($msg->btn_1_url != null && $msg->btn_1_url != "{{var}}"){
				$msg->btn1url = $msg->btn1url;
			}
			
			if($msg->btn_2_url != null && $msg->btn_2_url == "{{var}}"){
				$msg->btn2url = 'https://bynow.co.in/redirect.html?url='.$msg->btn2url;
			}
			elseif($msg->btn_2_url != null && $msg->btn_2_url != "{{var}}"){
				$msg->btn2url = $msg->btn2url;
			}
			
			rml_imageheader($msg->name,'+91'.$msg->contact,unserialize($msg->parameters),$msg->media,$msg->header_type,$msg->btn1url,$msg->btn2url);
			
			//rml_imageheader('seasonalgreetting_1','+917838222290','test');
			
	}
	//Added funtion by Mithlesh for sendairtelmsg

	public function sendairtelmsg($msg = null, $header_type = null)
	{
		// Adjust the button URLs
		
		$notifyURL = ''; 
		$method = ''; 
		$headers = []; 
	
		// Call the appropriate function based on the message type
		if ($header_type == "no_header") {
			airtel_noheader($msg->templateId, $msg->to, $msg->from, $msg->headerVars, $msg->variables, $msg->payload, $header_type);
		} elseif ($header_type == "IMAGE") {
			airtel_imageheader($msg->templateId, $msg->to, $msg->from, $msg->headerVars, $msg->variables, $msg->payload, $msg->mediaType, $msg->mediaId, $header_type);
		} elseif ($header_type == "callback") {
			airtel_callback($msg->templateId, $msg->to, $msg->from, $msg->headerVars, $msg->variables, $msg->payload, $notifyURL, $method, $headers, $header_type);
		} elseif ($header_type == "VIDEO") {
			airtel_imageheader($msg->templateId, $msg->to, $msg->from, $msg->headerVars, $msg->variables, $msg->payload, $msg->mediaType, $msg->mediaId, $header_type);
		} elseif ($header_type == "DOCUMENT") {
			airtel_imageheader($msg->templateId, $msg->to, $msg->from, $msg->headerVars, $msg->variables, $msg->payload, $msg->mediaType, $msg->mediaId, $header_type);
		}
	}
	

	//till here by Mithlesh
	
	public function gettemplateprv(){
		//echo "This is preview";
		//print_r($_POST);
		//print_r($_FILES);
		
		if(isset($_POST['template']) && $_POST['template'] !=NULL )
		{
		$prevdata=array();
		
		$templatedata = getdata('*','templates',array('templateId='=>@$_POST['template']));
		
		if($templatedata){
		if($templatedata[0]->header_type == 'TEXT'){
		}elseif($templatedata[0]->header_type == 'MEDIA'){
			$prevdata['link']='image';
			$prevdata['media']="<img src='".base_url('uploads/imgprev.jpg')."'>";
			if(isset($_POST['mediaurl']) && $_POST['mediaurl'] !=''){
				$prevdata['media']="<a href='".$_POST['mediaurl']."' target='_blank'><img style='width:250px;' src='".$_POST['mediaurl']."'></a>";
			}
		}
		
		elseif($templatedata[0]->header_type == 'VIDEO'){
			$prevdata['link']='video';
			$prevdata['media']="<img src='".base_url('uploads/videoprev.jpg')."'>";
			if(isset($_POST['mediaurl']) && $_POST['mediaurl'] !=''){
				$prevdata['media']="<video controls width='250'><source src='".$_POST['mediaurl']."' type='video/mp4'></video>";
			}
		}
		
		elseif($templatedata[0]->header_type == 'DOCUMENT'){
			$prevdata['link']='document';
			$prevdata['media']="<img src='".base_url('uploads/docprev.jpg')."'>";
			
 if(isset($_POST['mediaurl']) && $_POST['mediaurl'] !=''){
				$prevdata['media']='<a href="'.$_POST['mediaurl'].'" target="_blank"><iframe scrolling="no" src="'.$_POST['mediaurl'].'" style="overflow: hidden;width:250px; height: 170px;" frameborder="0"></iframe></a>';
			}
		}
		
		$prevdata['body'] = $templatedata[0]->body;
		
		if(@$templatedata[0]->parameters){
			for($i=0;$i<$templatedata[0]->parameters;$i++){
				if(@$_POST['parameters'][$i]!=''){
					$prevdata['param'][$i]=@$_POST['parameters'][$i];
				}else{
					$prevdata['param'][$i]='<b>Parameter</b>';
				}
						
			}
			
			foreach($prevdata['param'] as $prm){
			$prevdata['body'] = preg_replace('/{{var}}/', '<b>'.$prm.'</b>', $prevdata['body'],1);
			}
		}
		
		if(strpos($templatedata[0]->btn_1_url, '{{var}}') !== false){
				$prevdata['btn1txt']=$templatedata[0]->btn_1_text;
				if(isset($_POST['btn1']) && $_POST['btn1'] !==''){$prevdata['btn1url']='https://bynow.co.in/redirect.html?url='.@$_POST['btn1'];}
				else{ $prevdata['btn1url']='https://bynow.co.in';}		
				
		}
		elseif(strpos($templatedata[0]->btn_1_url, '{{var}}') == false && @$_POST['btn1'] !=null){
			$prevdata['btn1url']=$templatedata[0]->btn_1_url;
		}	
		
		if(strpos($templatedata[0]->btn_2_url, '{{var}}') !== false){
				$prevdata['btn2txt']=$templatedata[0]->btn_2_text;
				if(isset($_POST['btn2']) && $_POST['btn2'] !==''){$prevdata['btn2url']='https://bynow.co.in/redirect.html?url='.@$_POST['btn2'];}
				else{ $prevdata['btn2url']='https://bynow.co.in';}		
		}
		
		elseif(strpos($templatedata[0]->btn_2_url, '{{var}}') == false && @$_POST['btn2'] !=null){
			$prevdata['btn2url']=$templatedata[0]->btn_2_url;
		}
		
		if($templatedata[0]->footer != null || $templatedata[0]->footer !=''){
			$prevdata['footer']=$templatedata[0]->footer;
		}
		
		if($templatedata[0]->header_value != null || $templatedata[0]->header_value !=''){
			$prevdata['header']=$templatedata[0]->header_value;
		}
		
		
						
		$prevcontain = '';
					
		if(@$prevdata['media']){ $prevcontain.='<div class="prvmedia">'.$prevdata['media'].'</div>';}
		if(@$prevdata['header']){ $prevcontain.='<div class="prvhead">'.$prevdata['header'].'</div>';}
		if(@$prevdata['body']) {$prevcontain.='<div class="prvbody">'.$prevdata['body'].'</div>';}
		if(@$prevdata['footer']) {$prevcontain.='<div class="prvfooter">'.$prevdata['footer'].'</div>';}
		if(@$prevdata['btn1url']) {$prevcontain.='<a href="'.$prevdata['btn1url'].'" class="btn btn-primary btn-block" target="_blank">'.$prevdata['btn1txt'].'</a><br/>';}
		if(@$prevdata['btn2url']) {$prevcontain.='<a href="'.$prevdata['btn2url'].'" class="btn btn-primary btn-block" target="_blank">'.$prevdata['btn2txt'].'</a><br/>';}
			
		if(@$templatedata[0]->calltoactionbtn) {$prevcontain.='<a href="tel:917669666978" class="btn btn-primary btn-block" target="_blank">Call</a><br/>';}	
					
		echo $prevcontain;
		}
		}
	}
	
}
