<?php
if(!defined('BASEPATH')) exit('Hacking Attempt : Will Kill You Do Not Worry..!!');

class Broadcast extends MY_Controller
{

	var $model ='Broadcast_model';
	
	public function __construct(){
		parent::__construct();
		if($this->session->userdata('isLogin') == FALSE ){ redirect(base_url('admin/login/login_form'));}	
		$this->load->model('admin/'.$this->model); 
		
		$config['upload_path']          = 'uploads/broadcast/';
		$config['allowed_types']        = 'gif|jpg|png|jpeg';
		$config['max_size'] 			= 12000;
        $config['max_width'] 			= 13500;
        $config['max_height'] 			= 13500;
		$this->upload->initialize($config);
	}
	
	public function index(){
			
	}

/*##########################################################*/
/*################ Merchant GROUPS ####################*/
/*##########################################################*/

	
	
	public function whatsapp(){
			
			if(isset($_POST['submit'])){
				$braodcastdata=array();
				$braodcastdata['merchantId']=$_POST['merchant'];
				$braodcastdata['templateId']=$_POST['template'];
				$braodcastdata['parameters']=serialize($_POST['parameters']);
				$sendno = explode(PHP_EOL, $_POST['contacts']);
				print_r($braodcastdata);
				print_r($sendno);

			}
			
			$data['pagetitle']='Whatsapp';
			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['merchantoptions'] = getdata('merchantId,storename','merchant',array('status='=>1));
			$footer['pagejs']=$this->preview();
			$this->adminview('broadcast/sendwhatsapp',$data,$header,$footer);			
	}
	
	public function gettemplates(){
		$merchantId = $_POST['merchantId'];
		$merchanttemplates = $this->Broadcast_model->get_merchant_templates($merchantId);
		$option='';
		foreach($merchanttemplates as $mt){
			$option.='<option value="'.$mt->templateId.'">'.$mt->templatename.'</option>';
		}
		
		echo $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" class="form-control">
							</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" placeholder="Enter Parameter '.$i.'">
							</div>
					</div>'; 
		}
		
		echo $html;
	}
	
	public function preview(){
		$js='';
		$js.="$(document).ready(function(){";
 
		$js.= "$('.prevfield' ).on('change', function(){
					
					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 grouppublish($para=null){
		
			$formerror=0;
			
			//print_r($_POST);
			if(isset($_POST['submit'])){
				$rules = array(
									array(
											'field' => 'title',
											'label' => 'Group Title',
											'rules' => 'required'
									)
							);

				$this->form_validation->set_rules($rules);
				if ($this->form_validation->run() == FALSE) { 
					$formerror = 1; 
					$this->session->set_flashdata('form_error', '<div class="alert alert-danger text-center"> '.validation_errors().'</div>');
				}else{$formerror = 0; }
				
				if($_POST['iconold'] != $_FILES['icon']['name'] && $_FILES['icon']['name'] !=''){
					if (!$this->upload->do_upload('icon')) {    
						$this->session->set_flashdata('image_error', '<div class="alert alert-danger text-center"> '.$this->upload->display_errors().'</div>');
						$formerror = 1; 
					} 				
					else {  
						$imgdata = $this->upload->data('file_name');  $formerror = 0; 
						$data['icon']=$imgdata;		
					}
				}
				
				
				
				if($_POST['id'] ==''){
					if(checkunique('title',array('title'=>$_POST['title']),'merchant_group')){
						$this->session->set_flashdata('image_error', '<div class="alert alert-danger text-center"> Merchant Group Already In Database...</div>');
							$formerror = 1; 
					}
				}
				
				if(!$formerror){
					
					$id = $_POST['id'];
					$data['title']=$_POST['title'];
					$data['description']=$_POST['description'];
					if(isset($_POST['status'])){$data['status']=1;}else{$data['status'] = 0;}
					if($id ==''){$data['createdon']=date('Y-m-d H:i:s');}					
					$data['updatedon']=date('Y-m-d H:i:s');
					$id = $this->Merchants_model->set_merchant_group($data,$id);
					
					$this->session->set_flashdata('page_message', '<div class="alert alert-success text-center"> Merchant Group Updated Successfully...</div>');
					redirect(base_url('admin/merchants/groups'));
				}else{
					$data['title']=$_POST['title'];
					$data['description']=$_POST['description'];
					if(@$_POST['status'] == 'on'){$data['status']=1;}else{$data['status'] = 0;}
				}
			
			}
			
			if($para >0){
					
					$response = $this->Merchants_model->get_single_merchant_group($para);
					$data['id']=$response[0]->merchantgroupId;
					$data['title']=$response[0]->title;
					$data['description']=$response[0]->description;
					$data['icon']=$response[0]->icon;
					$data['status']=$response[0]->status;
			}
			$data['pagetitle']='Update Merchants Group';	
			$this->adminview('merchants/grouppublish',$data);
	}

	public function groupdelete($para = null){
		$this->Merchants_model->delete_merchant_group($para);
		$this->session->set_flashdata('page_message', '<div class="alert alert-danger text-center"> Selected Entry Deleted Successfully</div>');
		redirect(base_url('admin/merchants/groups'));
	}
/*#######################################################################*/

	
/*##########################################################*/
/*################ Merchants ####################*/
/*##########################################################*/	

public function merchants(){
			$data['pagetitle']='Merchants';
			if(isset($_POST['status'])){$data['status'] = $_POST['status'];}else{$data['status']='-1';}
			
			$data['response'] = $this->Merchants_model->get_merchant($data['status']);
			$data['updatelink']=base_url('admin/merchants/merchantspublish');
			$data['deletelink']=base_url('admin/merchants/merchantsdelete');
			$this->adminview('merchants/merchants',$data);
	}
	
	public function merchantspublish($para=null){
		
			$formerror=0;
			
			//print_r($_POST);
			if(isset($_POST['submit'])){
				$rules = array(
									array(
											'field' => 'accountId',
											'label' => 'Merchant Account Id',
											'rules' => 'required'
									),
									array(
											'field' => 'storename',
											'label' => 'Merchant Store Name',
											'rules' => 'required'
									),
									array(
											'field' => 'name',
											'label' => 'Merchant Name',
											'rules' => 'required'
									),
									array(
											'field' => 'email',
											'label' => 'Merchant Email Id',
											'rules' => 'required'
									),
									array(
											'field' => 'contact',
											'label' => 'Merchant Contact No.',
											'rules' => 'required'
									),
									array(
											'field' => 'whatsappno',
											'label' => 'Merchant Whatsapp No.',
											'rules' => 'required'
									)
							);

				$this->form_validation->set_rules($rules);
				if ($this->form_validation->run() == FALSE) { 
					$formerror = 1; 
					$this->session->set_flashdata('form_error', '<div class="alert alert-danger text-center"> '.validation_errors().'</div>');
				}else{$formerror = 0; }
				
				if($_POST['iconold'] != $_FILES['icon']['name'] && $_FILES['icon']['name'] !=''){
					if (!$this->upload->do_upload('icon')) {    
						$this->session->set_flashdata('image_error', '<div class="alert alert-danger text-center"> '.$this->upload->display_errors().'</div>');
						$formerror = 1; 
					} 				
					else {  
						$imgdata = $this->upload->data('file_name');  $formerror = 0; 
						$data['icon']=$imgdata;		
					}
				}
				
				
				
				if($_POST['id'] ==''){
					if(checkunique('accountId',array('accountId'=>$_POST['accountId']),'merchant')){
						$this->session->set_flashdata('image_error', '<div class="alert alert-danger text-center"> Merchant Account Id Already In Database...</div>');
							$formerror = 1; 
					}
				}
				
				if(!$formerror){
					
					$id = $_POST['id'];
					$data['accountId']=$_POST['accountId'];
					$data['groupId']=$_POST['groupId'];
					$data['storename']=$_POST['storename'];
					$data['name']=$_POST['name'];
					$data['email']=$_POST['email'];
					$data['contact']=$_POST['contact'];
					$data['whatsappno']=$_POST['whatsappno'];
					$data['description']=$_POST['description'];
					
					if(isset($_POST['status'])){$data['status']=1;}else{$data['status'] = 0;}
					if($id ==''){$data['createdon']=date('Y-m-d H:i:s');}					
					$data['updatedon']=date('Y-m-d H:i:s');
					$id = $this->Merchants_model->set_merchant($data,$id);
					
					$this->session->set_flashdata('page_message', '<div class="alert alert-success text-center"> Merchant Updated Successfully...</div>');
					redirect(base_url('admin/merchants/merchants'));
				}else{
					$data['accountId']=$_POST['accountId'];
					$data['groupId']=$_POST['groupId'];
					$data['storename']=$_POST['storename'];
					$data['name']=$_POST['name'];
					$data['email']=$_POST['email'];
					$data['contact']=$_POST['contact'];
					$data['whatsappno']=$_POST['whatsappno'];
					$data['description']=$_POST['description'];
					
					if(@$_POST['status'] == 'on'){$data['status']=1;}else{$data['status'] = 0;}
				}
			
			}
			
			if($para >0){
					
					$response = $this->Merchants_model->get_single_merchant($para);
					$data['id']=$response[0]->merchantId;
					$data['accountId']=$response[0]->accountId;
					$data['groupId']=$response[0]->groupId;
					$data['storename']=$response[0]->storename;
					$data['name']=$response[0]->name;
					$data['email']=$response[0]->email;
					$data['contact']=$response[0]->contact;
					$data['whatsappno']=$response[0]->whatsappno;
					$data['description']=$response[0]->description;
					$data['icon']=$response[0]->icon;
					$data['status']=$response[0]->status;
			}
			$data['pagetitle']='Update Merchants';
			$data['group'] = $this->Merchants_model->get_merchant_group(1);	
			$this->adminview('merchants/merchantspublish',$data);
	}

	public function merchantsdelete($para = null){
		$this->Merchants_model->delete_merchant($para);
		$this->session->set_flashdata('page_message', '<div class="alert alert-danger text-center"> Selected Entry Deleted Successfully</div>');
		redirect(base_url('admin/merchants/merchants'));
	}

}	

?>