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

class Voucher extends CI_Controller {

	public $userInfo;

    public function __construct()
    {
        parent::__construct();
        $this->load->library("hajanasms");
		$this->user_model->check_login("home");
		$this->load->model("voucher_model");
		$this->load->model("api_model");
		$this->branch = $this->user_model->getBranch();
        $this->load->model("report_model");
		$this->userInfo = $this->user_model->userInfo("first_name,last_name");
    }

	public function index($date='')
	{
		$this->user_model->check_permissions("voucher/index");
		$branch = $this->user_model->getBranch();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
		$data['userInfo'] = $this->userInfo;
        if($date==''){
              $date = date('d-m-Y');  
            }
            $data['date'] = $date;
		if($this->user_model->is_super())
		{
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
		} else {
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `id`='$branch' AND `is_delete`='0'")->result_array();
		}
		/* Start Add Month List For Creating Fee of Additional Months*/
		for ($i=1; $i <=12 ; $i++) { 
			$data['add_months'][]=date('Y-m',strtotime("first day of +".$i." month"));
		}
		/* End Month List For Creating Fee of Additional Months*/
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('voucher/index',$data);
	}
	
	public function index_left_student($date='')
	{
	    $this->user_model->check_permissions("voucher/index_left_student");
		$branch = $this->user_model->getBranch();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
		$data['userInfo'] = $this->userInfo;
        if($date==''){
              $date = date('d-m-Y');  
            }
            $data['date'] = $date;
		if($this->user_model->is_super())
		{
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
		} else {
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `id`='$branch' AND `is_delete`='0'")->result_array();
		}
		/* Start Add Month List For Creating Fee of Additional Months*/
		for ($i=1; $i <=12 ; $i++) { 
			$data['add_months'][]=date('Y-m',strtotime("first day of +".$i." month"));
		}
		/* End Month List For Creating Fee of Additional Months*/
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('voucher/index_left',$data);
	}

	public function view($p)
	{
	    $data['encrpt']=$p;
        $p = explode(SALT,json_decode(base64_decode($p)))[0];      
	
         
		if(!empty($p))
		{
                       
			$branch = $this->user_model->getBranch();
			$data['menu'] = $this->load_model->menu();
			$data['base_url'] = base_url();

			$data['userInfo'] = $this->userInfo;
                         //var_dump($this->userInfo);die;
			$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$p' AND `is_delete`='0'")->result_array()[0];
// 			Gett All Additional Month Fee off Intended Voucher
			$data['add_months']=@$this->db->where('invoice_id',$p)->where('is_delete',0)->get('fee_add_months')->result_array();
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `id`='".$invoice['branch_id']."' AND `is_delete`='0'")->result_array()[0];
			$data['student'] = $this->db->query("SELECT `grno`,`sid`,`student_name`,`class`.`class_name`,`father_name`,`student_contact`,`father_contact` FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` INNER JOIN `class` ON `class`.`class_id`=`promotion`.`class_id` WHERE `promotion`.`id`='".$invoice['student_id']."'")->result_array()[0];
// 			Get All Other Fees Associated with the Selected/Indexed Voucher
			$data['fee'] = $this->db->query("SELECT `fee_def`.`name`,`fee_installment`.`amount` FROM `fee_installment` INNER JOIN `fee_def` ON `fee_def`.`id`=`fee_installment`.`fee_id` WHERE `fee_installment`.`invoice`='$p' AND `fee_installment`.`is_delete`='0'")->result_array();
			$tot = $this->db->query("SELECT sum(`amount`) as sum FROM `fee_installment` WHERE `invoice`='$p' AND `is_delete`='0'")->result_array()[0]['sum'];
			$data['total'] = $tot + $invoice['fee_pack'];
		
			//$lastv = @$this->db->query("SELECT `id`,`status`,`advance`,`remaining`,`late_fine`,`fee_pack` FROM  `invoice` WHERE `id` <>  '$p' AND `branch_id` =  '".$invoice['branch_id']."' AND  `student_id` =  '".$invoice['student_id']."' AND  `id` <  '".$p."' AND is_delete='0'  ORDER BY  `id` DESC ")->result_array();
			$lastv=$this->voucher_model->getLastVoucher($invoice['student_id'],$invoice['id']);
            
            $last_submitted_voucher=$this->db->select('id')
			                                 ->from('invoice')
			                                 ->where('student_id',$invoice['student_id'])
			                                 ->where('status',1)
			                                 ->limit(1)
			                                 ->order_by('id','desc')
			                                 ->get()->row_array()['id'];
			                                 
// 			echo "<pre>";print_r($lastv);exit;
			//arrears logic
			$data['lastadv'] = 0;
			$data['lastrem'] = 0;
		        if($lastv && $lastv[0]['status']==1)
		        {
		            //echo "There";exit;
				$data['lastadv'] = $lastv[0]['advance'];
				$data['lastrem'] = $lastv[0]['remaining']+$invoice['remaining'];
				}
		        
		        elseif($lastv && $lastv[0]['status']==0)
		        {
			     $data['lastrem'] = $this->voucher_model->countArrears($invoice['id'],$invoice['student_id'],0,$invoice['remaining']);
		         if($data['lastrem'] < 0){
		             $data['lastadv'] = abs($data['lastrem']);
	             }else{
		              $this->db->select("sum(advance) as advance")
		                                          ->from("invoice")
		                                          ->where("student_id",$invoice['student_id'])
		                                          ->where("is_delete","0");
		                                  if(!empty($last_submitted_voucher))
		                                  {
		                                      $this->db->where('id>=',$last_submitted_voucher);
		                                  }
		              $data['lastadv'] =@$this->db->get()->row()->advance;
		            // $data['lastadv'] = @$this->db->select("sum(advance) as advance")->from("invoice")->where("student_id",$invoice['student_id'])->where("is_delete","0")->get()->row()->advance;
	             }
		        }
		        else{
    				$data['lastrem'] = $invoice['remaining'];
				}
		  //  echo "<pre>";print_r($data['lastadv']);exit;      
		  //  echo "<pre>";print_r($data['lastrem']);exit;

			//end arrears logic
			$due = date("Y-m-d",strtotime($invoice['date_expire']));
			$date = date("Y-m-d");

			if ($due<=$date && $invoice['status']==0) {
				$per = ($data['total'] * $invoice['late_fine']) / 100;
				if(!empty($data['add_months'])) {
					foreach ($data['add_months'] as $key => $value) {
						$per += ($value['fee'] * $invoice['late_fine']) / 100;
					}
				}
				$data['net'] = $data['total'] + $per;
				$data['fine'] = $per;
			} else {
				$data['net'] = $data['total'];
				$data['fine'] = 0;
			}
			//============adding additional months fee to $data[total]====================

			if(!empty($data['add_months'])) {
				foreach ($data['add_months'] as $key => $value) {
					$data['total'] += $value['fee'];
				}
			}

			//============================================================================
			$data['invoice'] = $invoice;
			$this->load->view('header',$data);
			$this->load->view('sidebar',$data);
			$this->load->view('voucher/view',$data);
		}else {
			redirect("voucher/listv","refresh");
		}
	}
public function createUnexpectedVoucher()
	{
		$this->user_model->check_permissions("voucher/index");
		$branch = $this->user_model->getBranch();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
		$data['userInfo'] = $this->userInfo;

		if($this->user_model->is_super())
		{
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
		} else {
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `id`='$branch' AND `is_delete`='0'")->result_array();
		}
		$data['session'] = $this->db->query("SELECT * FROM `session` WHERE `is_delete`='0'")->result_array();

		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('voucher/FormUnexpectedVoucher',$data);
	}

	public function creatingUnexpectedVoucher()
	{
		$data=$this->input->post();
		$branch=$data['branch'];
		$promotion_id=$data['student'];
		$fee=$data['fee'];
		
		$late_fine = (int)$this->db->query("SELECT `branch`.`late_fine` FROM `branch` WHERE `branch`.`id`=$branch AND `branch`.`is_delete`='0'")->row('late_fine');
		$date = date("Y-m-d");
		$exp_date = date("Y-m-d", strtotime('+11 days'));

		$invoice = array(
			'branch_id' => $branch,
			"student_id"=>$promotion_id,
			"fee_pack"=>0,
			"date"=>$date,
			"date_expire"=>$exp_date,
			"late_fine"=>$late_fine,
		);
		$this->db->insert("invoice",$invoice);

		$inv = $this->db->insert_id();
		if(@!empty($fee))
		{
			foreach ($fee as $k => $d) {
				if(isset($d['name']))
				{
					$install = array(
						'invoice' => $inv,
						'amount' => $d['value'],
						'fee_id' => $k
					);
					$this->db->insert('fee_installment',$install);
				}
			}
		}

		redirect("voucher/listv","refresh");
		
	}
	public function listV()
	{
        $p = explode(SALT,json_decode(base64_decode($this->uri->segment(3))))[0];
  
		$this->user_model->check_permissions("voucher/index");
		$data['edit_delete']=$this->user_model->checkEditDelete('voucher/index');

		$data['is_super'] = $this->user_model->is_super();
		$branch = $this->user_model->getBranch();

		$data['menu'] = $this->load_model->menu();
		$data['base_url'] = base_url();
		$data['userInfo'] = $this->userInfo;
		  
		$ym = date("Y-m");
		if($this->user_model->is_super())
		{
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
			$data['voucher'] = $this->db->query("SELECT `student`.`sid`,`student`.`student_name`,`student`.`grno`,`invoice`.`remaining`,`invoice`.`id` as `invoice`,`invoice`.`status`,`invoice`.`date`,`invoice`.`date_expire`,`class`.`class_name`,`section`.`section_name` FROM `invoice` INNER JOIN `promotion` ON `promotion`.`id` = `invoice`.`student_id` INNER JOIN `student` ON `student`.`id` = `promotion`.`student_id` INNER JOIN `class` ON `promotion`.`class_id` = `class`.`class_id` INNER JOIN `section` ON `promotion`.`section_id` = `section`.`section_id` WHERE `invoice`.`is_delete`='0' AND (LEFT(`invoice`.`date`,7)='$ym') ORDER BY invoice.id DESC")->result_array();
		}
		else
		{
	        $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->result_array();
			$data['voucher'] = $this->db->query("SELECT `student`.`sid`,`student`.`student_name`,`student`.`grno`,`invoice`.`remaining`,`student`.`father_name`,`student`.`father_contact`,`invoice`.`id` as `invoice`,`invoice`.`status`,`invoice`.`date`,`invoice`.`date_expire`,`class`.`class_name`,`section`.`section_name` FROM `invoice` INNER JOIN `promotion` ON `promotion`.`id` = `invoice`.`student_id` INNER JOIN `student` ON `student`.`id` = `promotion`.`student_id` INNER JOIN `class` ON `promotion`.`class_id` = `class`.`class_id` INNER JOIN `section` ON `promotion`.`section_id` = `section`.`section_id` WHERE `invoice`.`is_delete`='0' AND `invoice`.`branch_id`='$branch' AND `student`.`branch`='$branch' AND `class`.`branch`='$branch' AND `section`.`branch`='$branch' AND LEFT(`invoice`.`date`,7)='$ym' ORDER BY invoice.id DESC")->result_array();
		}
		//echo "<pre>";print_r($data['voucher']);exit;
		$data['session'] = $this->db->query("SELECT * FROM `session` WHERE `is_delete`='0'")->result_array();
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
        $this->load->view('voucher/list',$data);
	}

	public function doPrint($id='',$fine='')
	{
		if (!empty($id)) {
			$data['base_url'] = base_url();
			$branch = $this->user_model->getBranch();
			$is_super = $this->user_model->is_super();
			if($is_super)
				$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$id' AND `is_delete`='0'")->result_array()[0];
			else
				$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$id' AND `is_delete`='0' AND `branch_id`='$branch'")->result_array()[0];
// 			Get All Add Month Fees of the Selected Voucher to be Print
			$data['add_months']=@$this->db->where('invoice_id',$id)->where('is_delete',0)->get('fee_add_months')->result_array();
			$data['student'] = $this->db->query("SELECT `student`.`grno`,`student`.`student_name`,`student`.`father_name`,`student`.`student_contact`,`class`.`class_name`,`section`.`section_name` FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` INNER JOIN `class` ON `promotion`.`class_id`=`class`.`class_id` INNER JOIN `section` ON `section`.`section_id`=`promotion`.`section_id` WHERE `promotion`.`id`='".$invoice['student_id']."'")->result_array()[0];
// 			Get All Add Other Fees of the Selected Voucher to be Print
			$data['fee'] = $this->db->query("SELECT `fee_def`.`name`,`fee_installment`.`amount` FROM `fee_installment` INNER JOIN `fee_def` ON `fee_def`.`id`=`fee_installment`.`fee_id` WHERE `fee_installment`.`invoice`='$id' AND `fee_installment`.`is_delete`='0'")->result_array();
			$tot = $this->db->query("SELECT sum(`amount`) as sum FROM `fee_installment` WHERE `invoice`='$id' AND `is_delete`='0'")->result_array()[0]['sum'];
			$lastv=$this->voucher_model->getLastVoucher($invoice['student_id'],$invoice['id']);
			
			//arrears logic
			$data['lastadv'] = 0;
			$data['lastrem'] = 0;
		        if($lastv && $lastv[0]['status']==1)
		        {
				$data['lastadv'] = $lastv[0]['advance'];
				$data['lastrem'] = $lastv[0]['remaining']+$invoice['remaining'];;			
		        }
		        
		        elseif($lastv && $lastv[0]['status']==0)
		        {
			     $data['lastadv'] = 0;
			     $data['lastrem'] = $this->voucher_model->countArrears($invoice['id'],$invoice['student_id'],0);
		        }
		        else{
		         $data['lastadv'] = $invoice['advance'];
			     $data['lastrem'] = $invoice['remaining'];
		       }
			//end arrears logic
			$data['b_header'] = $this->db->query("SELECT * FROM `branch` WHERE `id`='".$invoice['branch_id']."' AND `is_delete`='0'")->result_array()[0];
			$data['total'] = $tot + $invoice['fee_pack'];
			foreach ($data['add_months'] as $key => $value) {
				$data['total']+=$value['fee'];
			}
			$data['invoice'] = $invoice;
// 			Start Show Fine on the Print Voucher If CheckBox of Fine is Selected
            if($fine == 1){
			    $data['fine_chk'] = 1;
			}
			else{
			    $data['fine_chk'] = 0;    
			}
			
// 			End Show Fine on the Print Voucher If CheckBox of Fine is Selected
			
			$this->load->view('printable/voucher',$data);
		}else{
			redirect("home","refresh");
		}
	}
	
		public function doPrint1($id='',$fine='')
	{
		if (!empty($id)) {
			$data['base_url'] = base_url();
			$branch = $this->user_model->getBranch();
			$is_super = $this->user_model->is_super();
			if($is_super)
				$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$id' AND `is_delete`='0'")->result_array()[0];
			else
				$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$id' AND `is_delete`='0' AND `branch_id`='$branch'")->result_array()[0];
// 			Get All Add Month Fees of the Selected Voucher to be Print
			$data['add_months']=@$this->db->where('invoice_id',$id)->where('is_delete',0)->get('fee_add_months')->result_array();
			$data['student'] = $this->db->query("SELECT `student`.`grno`,`student`.`student_name`,`student`.`father_name`,`student`.`student_contact`,`class`.`class_name`,`section`.`section_name` FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` INNER JOIN `class` ON `promotion`.`class_id`=`class`.`class_id` INNER JOIN `section` ON `section`.`section_id`=`promotion`.`section_id` WHERE `promotion`.`id`='".$invoice['student_id']."'")->result_array()[0];
// 			Get All Add Other Fees of the Selected Voucher to be Print
			$data['fee'] = $this->db->query("SELECT `fee_def`.`name`,`fee_installment`.`amount` FROM `fee_installment` INNER JOIN `fee_def` ON `fee_def`.`id`=`fee_installment`.`fee_id` WHERE `fee_installment`.`invoice`='$id' AND `fee_installment`.`is_delete`='0'")->result_array();
			$tot = $this->db->query("SELECT sum(`amount`) as sum FROM `fee_installment` WHERE `invoice`='$id' AND `is_delete`='0'")->result_array()[0]['sum'];
			$lastv=$this->voucher_model->getLastVoucher($invoice['student_id'],$invoice['id']);
			
			//arrears logic
			$data['lastadv'] = 0;
			$data['lastrem'] = 0;
		        if($lastv && $lastv[0]['status']==1)
		        {
				$data['lastadv'] = $lastv[0]['advance'];
				$data['lastrem'] = $lastv[0]['remaining']+$invoice['remaining'];;			
		        }
		        
		        elseif($lastv && $lastv[0]['status']==0)
		        {
			     $data['lastadv'] = 0;
			     $data['lastrem'] = $this->voucher_model->countArrears($invoice['id'],$invoice['student_id'],0);
		        }
		        else{
		         $data['lastadv'] = $invoice['advance'];
			     $data['lastrem'] = $invoice['remaining'];
		       }
			//end arrears logic
			$data['b_header'] = $this->db->query("SELECT * FROM `branch` WHERE `id`='".$invoice['branch_id']."' AND `is_delete`='0'")->result_array()[0];
			$data['total'] = $tot + $invoice['fee_pack'];
			foreach ($data['add_months'] as $key => $value) {
				$data['total']+=$value['fee'];
			}
			$data['invoice'] = $invoice;
// 			Start Show Fine on the Print Voucher If CheckBox of Fine is Selected
            if($fine == 1){
			    $data['fine_chk'] = 1;
			}
			else{
			    $data['fine_chk'] = 0;    
			}
			
// 			End Show Fine on the Print Voucher If CheckBox of Fine is Selected
			
			$this->load->view('printable/receipt',$data);
		}else{
			redirect("home","refresh");
		}
	}

    public function print_install()
	{
	   // echo "<pre>";print_r($this->input->post());exit;
	    $id = $this->input->post('id',true);
	    $data['install'] = $this->input->post();
		if (!empty($id)) {
			$data['base_url'] = base_url();
			$branch = $this->user_model->getBranch();
			$is_super = $this->user_model->is_super();
			if($is_super)
				$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$id' AND `is_delete`='0'")->result_array()[0];
			else
				$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$id' AND `is_delete`='0' AND `branch_id`='$branch'")->result_array()[0];
			$data['student'] = $this->db->query("SELECT `student`.`grno`,`student`.`student_name`,`student`.`father_name`,`student`.`student_contact`,`class`.`class_name`,`section`.`section_name` FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` INNER JOIN `class` ON `promotion`.`class_id`=`class`.`class_id` INNER JOIN `section` ON `section`.`section_id`=`promotion`.`section_id` WHERE `promotion`.`id`='".$invoice['student_id']."'")->result_array()[0];
			
			$data['b_header'] = $this->db->query("SELECT `title`,`tagline`,`short_address`,`phone_no`,`email`,`logo1`,`logo2` FROM `branch` WHERE `id`='".$invoice['branch_id']."' AND `is_delete`='0'")->result_array()[0];
			$data['invoice'] = $invoice;
			$this->load->view('printable/install_voucher',$data);
		}else{
			redirect("home","refresh");
		}
	}
    
       public function getStudent($date='')
	{
	   $last_month = date('Y-m',strtotime("-2 month"));
	   if($date<$last_month){
	   	echo "";
	   }
	   else
	   {
		$branch = $this->user_model->getBranch();
		$is_super = $this->user_model->is_super();
        if($this->user_model->is_super())
		{
			$voucher = $this->db->query("SELECT student.sid,`student`.`student_name`,`student`.`grno`,`student`.`father_name`,`student`.`father_contact`,`invoice`.`remaining`,`invoice`.`id` as `invoice`,`invoice`.`status`,`invoice`.`date`,`invoice`.`date_expire`,`class`.`class_name`,`section`.`section_name` FROM `invoice` INNER JOIN `promotion` ON `promotion`.`id` = `invoice`.`student_id` INNER JOIN `student` ON `student`.`id` = `promotion`.`student_id` INNER JOIN `class` ON `promotion`.`class_id` = `class`.`class_id` INNER JOIN `section` ON `promotion`.`section_id` = `section`.`section_id` WHERE `invoice`.`is_delete`='0' AND LEFT(`invoice`.`date`,7)='$date'")->result_array();
		}
		else
		{
			$voucher = $this->db->query("SELECT student.sid,`student`.`student_name`,`student`.`grno`,`student`.`father_name`,`student`.`father_contact`,`invoice`.`remaining`,`invoice`.`id` as `invoice`,`invoice`.`status`,`invoice`.`date`,`invoice`.`date_expire`,`class`.`class_name`,`section`.`section_name` FROM `invoice` INNER JOIN `promotion` ON `promotion`.`id` = `invoice`.`student_id` INNER JOIN `student` ON `student`.`id` = `promotion`.`student_id` INNER JOIN `class` ON `promotion`.`class_id` = `class`.`class_id` INNER JOIN `section` ON `promotion`.`section_id` = `section`.`section_id` WHERE `invoice`.`is_delete`='0' AND `invoice`.`branch_id`='$branch' AND LEFT(`invoice`.`date`,7)='$date'")->result_array();
		}
		
		$return ="" ;
		$remaining =0;
		//var_dump($voucher);die();
		$i=1;
        foreach ($voucher as $key => $value) 
        {
            $return .= "<tr>";
            $return .= "<td>".$i++."</td>";
            $return .= "<td>".$value['sid']."</td>";
            $return .= "<td>".$value['grno']."</td>";
            $return .= "<td>".$value['invoice']."</td>";
            $return .= "<td>".$value['student_name']."</td>";
            $return .= "<td>".$value['father_name']."</td>";
            $return .= "<td>".$value['father_contact']."</td>";
            $return .= "<td>".$value['class_name']."</td>";
            $return .= "<td>".$value['section_name']."</td>";
            //Show Fee on Voucher List As per different Scenarios
            if($value['remaining'] == 0 && $value['status'] == 1){$remaining = 0;}elseif($value['remaining'] > 0 && $value['status'] != 0){$remaining = $value['remaining'];}else{ if($this->voucher_model->countTotalFee($value['invoice']) >= 0){$remaining = ($this->voucher_model->countTotalFee($value['invoice']));}else{$remaining=0;}};
            $return .= "<td>".$remaining."</td>";
            $return .= "<td>".date("d-m-Y",strtotime($value['date']." +0 day"))."</td>";
 			$return .= "<td>".date("d-m-Y",strtotime($value['date_expire']." -1 day"))."</td>";
			//Start Status Login to be show on Voucher List as Per Scecnario
			$due = date("Y-m-d",strtotime($value['date_expire']." -1 day"));
              $date = date("Y-m-d");
              if ($due<$date && $value['status']==0) {
                $status = "Defaulter";
              }else if ($value['status']==1 && $value['remaining'] != 0) {
                $status = "Partial Paid";
              }else if($value['status']==1 && $value['remaining'] == 0)
              {
                $status = "Paid";
              }
              else{
                if ($value['status']==0) {
                  $status = "Due";
                }elseif ($value['status']==1 && $value['remaining'] == 0) {
                  $status = "Paid";
                }else {
                  $status = "Partial Paid";
                }}            	
            $return .= "<td>".$status."</td>";                
            //End Status Login to be show on Voucher List as Per Scecnario
			if(!$is_super){
            	$return .= "<td> 
            	<a href=".base_url()."voucher/view/".base64_encode(json_encode($value['invoice'].SALT))." target='_blank' class='btn btn-md btn-info'>P Pay</a>";
            	if ($value['status']==0) {
            	 $return .="<a href=".base_url()."voucher/full_submit/".$value['invoice']." onclick='return confirm(Are You Sure Full Submit Voucher...?)'  class='btn btn-md btn-primary'>F Pay</a>";
                 $return .="<a href=".base_url()."voucher/full_submit_receipt/".$value['invoice']." onclick='return confirm(Are You Sure Full Submit & Receipt Voucher...?)'  class='btn btn-success'>F Pay & Receipt</a>";           
            	}
            	$return .="</td>";
            
            	$return .= "</tr>";
                        
                 }

             }

                        echo $return;
            }
		
	}    



	public function create()
	{
	    
	   // echo "<pre>";print_r($this->input->post());exit;
		if($this->input->post())
		{
			$date = $this->input->post("date",true);
			//echo "<pre>";print_r($date);exit;
			$branch = $this->input->post("branch",true);
			$class = $this->input->post("class",true);
			$section = $this->input->post("section",true);
			$student = $this->input->post("student",true);
			$fee = $this->input->post("fee",true);
			$add_months= $this->input->post("add_months",true);
			$tution_check= $this->input->post("tution_check",true);
			//Start Selection of student filtered from the above Inputs
            $this->db->select("promotion.id,student.disc_type,student.disc_value");
			$this->db->join("promotion","student.id=promotion.student_id");
			$this->db->where("student.status",'0');
			$this->db->where("student.branch",$branch);
			$this->db->where("promotion.class_id",$class);
			$this->db->where("promotion.section_id",$section);
			$this->db->where_in("promotion.student_id",$student);
			$this->db->where("promotion.is_active",'1');
			$this->db->where("promotion.is_delete",'0');
			$students = $this->db->get("student")->result_array();
			//End Selection of student filtered from the above Inputs

			//Get Tuition Fee and Admission Fee of the Selected Class
			$this->db->select("tution_fee,admin_fee");
			$this->db->where("is_delete",'0');
			$this->db->where("class_id",$class);
			$c_data = $this->db->get("class")->result_array()[0];

            //Get Late Fine  & Due Date to the Current or Selected Branch 
			$this->db->select("late_fine,due_date");
			$this->db->where("is_delete",'0');
			$this->db->where("id",$branch);
			$branch_data = $this->db->get("branch")->result_array()[0];


			$fee_pack = $c_data['tution_fee'];
			$admin_fee = $c_data['admin_fee'];
			$first_day_of_date=date('Y-m-d',strtotime("$date first day of this month"));
			$due_date=date('Y-m-d',strtotime("$date +".$branch_data['due_date']." days"));
			$late_fine = $branch_data['late_fine'];

    		foreach ($students as $key => $v) {
				    $accumulate_fee = 0;    //It will sum the All feeses & check the Fee should be enough to pay From Advance on Voucher Creation
					$student = $v['id'];
					$disc_type = $v['disc_type'];
					$disc_value = $v['disc_value'];
	                // Start Calculate the Discount Percentage/Rupee
					if($disc_value!=0)
					{
						if($disc_type=="percentage")
						{
							$calc = ($fee_pack * $disc_value) / 100;
							$fee_pack_final = $fee_pack - $calc;
						}else if($disc_type=="rupees")
						{
							$fee_pack_final = $fee_pack - $disc_value;
						}
					}else{
						$fee_pack_final = $fee_pack;
					}
					//End Calculate the Discount Percentage/Rupee
					$accumulate_fee += $fee_pack_final;
					
					//Get the Arrears of Student
					$result = @$this->db->select('id,amount,for_month')->from('arrears')->where('promotion_id',$v['id'])->get()->row();
					
					$last_voucher = @$this->db->where('student_id',$student)->where('status',1)->order_by('id','DESC')->get('invoice')->row();
					$actual_last_voucher = @$this->db->where('student_id',$student)->order_by('id','DESC')->get('invoice')->row_array()['id'];
					
					if(!empty($last_voucher) && !empty($actual_last_voucher))
					{
					    if($actual_last_voucher!=$last_voucher->id)
    					{
    					    $accumulate_fee +=$this->voucher_model->getRemainingAmount($actual_last_voucher);
    					}else{
    					    $accumulate_fee +=$last_voucher->remaining;
    					}
					}
					
			
    				$invoice = array(
						'branch_id' => $branch,
						"student_id"=>$student,
						"fee_pack"=>($tution_check == 'on') ? '0' : $fee_pack_final,
						"admin_fee"=>$admin_fee,
						"date"=>$first_day_of_date,
						"date_expire"=>$due_date,
						"late_fine"=>$late_fine,
				// 		IF Arrears Exist Then Include it in Voucher
						"remaining" => empty($result) ? "0" : ((strtotime($date) >= strtotime($result->for_month) && $tution_check != 'on') ? $result->amount : "0")
    				);
					$this->db->insert("invoice",$invoice);
					
					$inv = $this->db->insert_id();
					//Reset Arrears If Added to the Voucher
					if($result){
    					if(strtotime($date) >= strtotime($result->for_month) && $tution_check != 'on'){
                            $accumulate_fee +=$result->amount;
                            $this->db->where('id',$result->id);
    					    $this->db->update('arrears',array('status'=>'1','amount'=>0));
    					}
					}
					//Other Fee Added to the Voucher
					if(@!empty($fee))
					{
						foreach ($fee as $k => $d) {
							if(isset($d['name']))
							{
								$install = array(
									'invoice' => $inv,
									'amount' => $d['value'],
									'fee_id' => $k
								);
								$this->db->insert('fee_installment',$install);
								$accumulate_fee +=$d['value'];
							}
						}
					}
					//Additional Month Added to the Voucher
					if(@!empty($add_months)) {
						foreach ($add_months as $key => $select_month) {
							$fee_add_months=array(
								'invoice_id'=>$inv,
								'month'=>$select_month,
								'fee'=>$fee_pack_final
							);
							$this->db->insert('fee_add_months',$fee_add_months);
							$accumulate_fee +=$fee_pack_final;
						}
					}
					//Start Voucher Submission from the advance
					if($last_voucher && $last_voucher->advance >= $accumulate_fee){
					    $user_id = $this->user_model->userInfo("id")['id'];
					    $contact_id=$this->voucher_model->getVoucherContactNumber($inv)['id'];
			            $data = array(
            				"status"=> "1",
            				"remaining"=>0,
            				"is_auto"=>1,
            				"recieved"=>$accumulate_fee,
            				"advance"=>($last_voucher->advance - $accumulate_fee),
            				"submitted_at"=>$first_day_of_date
    			        );
        			$this->db->where("id",$inv);
        			if($this->db->update("invoice",$data)){
        			    //Entry on Fee_Submit_Log
            		    date_default_timezone_set("Asia/Karachi");
                        $datee = date('Y-m-d');
            		    $submit_detail = array(
            		        "inv_id"=>$inv,
            		        "discount"=>0,
            		        "remaining"=>0,
            		        "recieved"=>$accumulate_fee,
            		        "advance"=>($last_voucher->advance - $accumulate_fee),
            				"is_fine"=> "0",
            		        "fine" => "0",
            		        "student_id" => $contact_id,
            		        "user_id" => $user_id, 
            		        "branch_account"=>$branch,
            		        "date" =>$first_day_of_date
            				);
            			$this->db->insert('fee_submit_logs',$submit_detail);
            	        }
				    }
					//End Voucher Submission from the advance
					
				}	
		}
		redirect("voucher/index","refresh");
	}
	
	public function create_left()
	{
	    
	   // echo "<pre>";print_r($this->input->post());exit;
	   $branch=$this->user_model->getbranch();
	   if($branch==1)
        {
            $st_status=21;
        }else{
            $st_status=23;
        }
        
        
		if($this->input->post())
		{
			$date = $this->input->post("date",true);
			//echo "<pre>";print_r($date);exit;
			$branch = $this->input->post("branch",true);
			$class = $this->input->post("class",true);
			$section = $this->input->post("section",true);
			$student = $this->input->post("student",true);
			$fee = $this->input->post("fee",true);
			$add_months= $this->input->post("add_months",true);
			$tution_check= $this->input->post("tution_check",true);
			//Start Selection of student filtered from the above Inputs
            $this->db->select("promotion.id,student.disc_type,student.disc_value");
			$this->db->join("promotion","student.id=promotion.student_id");
			$this->db->where("student.status",$st_status);
			$this->db->where("student.branch",$branch);
			$this->db->where("promotion.class_id",$class);
			$this->db->where("promotion.section_id",$section);
			$this->db->where_in("promotion.student_id",$student);
			$this->db->where("promotion.is_active",'1');
			$this->db->where("promotion.is_delete",'0');
			$students = $this->db->get("student")->result_array();
	
			//End Selection of student filtered from the above Inputs

			//Get Tuition Fee and Admission Fee of the Selected Class
			$this->db->select("tution_fee,admin_fee");
			$this->db->where("is_delete",'0');
			$this->db->where("class_id",$class);
			$c_data = $this->db->get("class")->result_array()[0];

            //Get Late Fine  & Due Date to the Current or Selected Branch 
			$this->db->select("late_fine,due_date");
			$this->db->where("is_delete",'0');
			$this->db->where("id",$branch);
			$branch_data = $this->db->get("branch")->result_array()[0];


			$fee_pack = $c_data['tution_fee'];
			$admin_fee = $c_data['admin_fee'];
			$first_day_of_date=date('Y-m-d',strtotime("$date first day of this month"));
			$due_date=date('Y-m-d',strtotime("$date +".$branch_data['due_date']." days"));
			$late_fine = $branch_data['late_fine'];

    		foreach ($students as $key => $v) {
				    $accumulate_fee = 0;    //It will sum the All feeses & check the Fee should be enough to pay From Advance on Voucher Creation
					$student = $v['id'];
					$disc_type = $v['disc_type'];
					$disc_value = $v['disc_value'];
	                // Start Calculate the Discount Percentage/Rupee
					if($disc_value!=0)
					{
						if($disc_type=="percentage")
						{
							$calc = ($fee_pack * $disc_value) / 100;
							$fee_pack_final = $fee_pack - $calc;
						}else if($disc_type=="rupees")
						{
							$fee_pack_final = $fee_pack - $disc_value;
						}
					}else{
						$fee_pack_final = $fee_pack;
					}
					//End Calculate the Discount Percentage/Rupee
					$accumulate_fee += $fee_pack_final;
					
					//Get the Arrears of Student
					$result = @$this->db->select('id,amount,for_month')->from('arrears')->where('promotion_id',$v['id'])->get()->row();
					
					$last_voucher = @$this->db->where('student_id',$student)->where('status',1)->order_by('id','DESC')->get('invoice')->row();
			
    				$invoice = array(
						'branch_id' => $branch,
						"student_id"=>$student,
						"fee_pack"=>($tution_check == 'on') ? '0' : $fee_pack_final,
						"admin_fee"=>$admin_fee,
						"date"=>$first_day_of_date,
						"date_expire"=>$due_date,
						"late_fine"=>$late_fine,
				// 		IF Arrears Exist Then Include it in Voucher
						"remaining" => empty($result) ? "0" : ((strtotime($date) >= strtotime($result->for_month) && $tution_check != 'on') ? $result->amount : "0")
    				);
					$this->db->insert("invoice",$invoice);
					
					$inv = $this->db->insert_id();
					//Reset Arrears If Added to the Voucher
					if($result){
    					if(strtotime($date) >= strtotime($result->for_month) && $tution_check != 'on'){
                            $accumulate_fee +=$result->amount;
                            $this->db->where('id',$result->id);
    					    $this->db->update('arrears',array('status'=>'1','amount'=>0));
    					}
					}
					//Other Fee Added to the Voucher
					if(@!empty($fee))
					{
						foreach ($fee as $k => $d) {
							if(isset($d['name']))
							{
								$install = array(
									'invoice' => $inv,
									'amount' => $d['value'],
									'fee_id' => $k
								);
								$this->db->insert('fee_installment',$install);
								$accumulate_fee +=$d['value'];
							}
						}
					}
					//Additional Month Added to the Voucher
					if(@!empty($add_months)) {
						foreach ($add_months as $key => $select_month) {
							$fee_add_months=array(
								'invoice_id'=>$inv,
								'month'=>$select_month,
								'fee'=>$fee_pack_final
							);
							$this->db->insert('fee_add_months',$fee_add_months);
							$accumulate_fee +=$fee_pack_final;
						}
					}
					//Start Voucher Submission from the advance
					if($last_voucher && $last_voucher->advance >= $accumulate_fee){
					    $user_id = $this->user_model->userInfo("id")['id'];
					    $contact_id=$this->voucher_model->getVoucherContactNumber($inv)['id'];
			            $data = array(
            				"status"=> "1",
            				"remaining"=>0,
            				"is_auto"=>1,
            				"recieved"=>$accumulate_fee,
            				"advance"=>($last_voucher->advance - $accumulate_fee),
            				"submitted_at"=>$first_day_of_date
    			        );
        			$this->db->where("id",$inv);
        			if($this->db->update("invoice",$data)){
        			    //Entry on Fee_Submit_Log
            		    date_default_timezone_set("Asia/Karachi");
                        $datee = date('Y-m-d');
            		    $submit_detail = array(
            		        "inv_id"=>$inv,
            		        "discount"=>0,
            		        "remaining"=>0,
            		        "recieved"=>$accumulate_fee,
            		        "advance"=>($last_voucher->advance - $accumulate_fee),
            				"is_fine"=> "0",
            		        "fine" => "0",
            		        "student_id" => $contact_id,
            		        "user_id" => $user_id, 
            		        "branch_account"=>$branch,
            		        "date" =>$first_day_of_date
            				);
            			$this->db->insert('fee_submit_logs',$submit_detail);
            	        }
				    }
					//End Voucher Submission from the advance
					
				}	
		}
		redirect("voucher/index_left_student","refresh");
	}

	public function delete($id)
	{
		if(!empty($id))
		{
			$data = array(
				"is_delete"=>"1"
			);
			$this->db->where("id",$id);
			$this->db->update("invoice",$data);
		}
		redirect("voucher/listv","refresh");
	}

	public function submit()
	{
	   
	   $fee_deposit_type = $this->input->post("bank",true);
	   $encrpt = $this->input->post("encrpt",true);
	
	   $branch=$this->user_model->getbranch();
	    
		if($fee_deposit_type=="bank")
		{
		    
	               $primary_bank=$this->db->select('*')
                                   ->from('bank_def')
                                   ->where('branch',$branch)
                                   ->where('fee_primary',1)
                                   ->where('is_active',1)
                                   ->get()->row_array();
                    if(!empty($primary_bank)) 
                    {
                            $remaining=0;
                		    $advance=0;
                		    $rec_dis=0;
		                    $user_id = $this->user_model->userInfo("id")['id'];
                	    	$id = $this->input->post("id",true);
                			
                			$received = $this->input->post("recieved",true);
                			$discount = $this->input->post("discount",true);
                		    $g_total=$this->input->post("net",true);
                		    $rec_dis=$received+$discount;
                		    
                		    if($rec_dis>$g_total)
                		    {
                		       $advance=$rec_dis-$g_total;
                		       $remaining=0;
                		    }else{
                		       $remaining=$g_total-$rec_dis; 
                		       $advance=0;
                		    }
                			
                			
                			
                			$fine_chk = $this->input->post("fine_chk",true);
                			$fine = $this->input->post("fine",true);
                		
                			$submitted_att = $this->input->post("submitted_at",true);
                			$submitted_at = date("Y-m-d", strtotime($submitted_att));
                			$contact_number=$this->voucher_model->getVoucherContactNumber($id)['father_contact'];
                			$contact_id=$this->voucher_model->getVoucherContactNumber($id)['id'];
                			$child_name=$this->voucher_model->getVoucherContactNumber($id)['student_name'];
                			$class_name=$this->voucher_model->getVoucherContactNumber($id)['class_name'];
                			
                			$branch_name = @$this->db->query("SELECT `name` FROM `branch` WHERE `id`=".$this->user_model->getBranch()." AND `is_delete`='0'")->result_array()[0]['name'];
                			$invoice = $this->db->where('id',$id)->get('invoice')->row();
                $get_student_id=$this->db->select('student_id')
                                                     ->from('promotion')
                                                     ->where('id',$invoice->student_id)
                                                     ->where('is_delete',0)
                                                     ->get()->row_array()['student_id'];
             $get_all_promotion=$this->db->select('id')
                                         ->from('promotion')
                                         ->where('student_id',$get_student_id)
                                         ->where('id<=',$invoice->student_id)
                                         ->get()->result_array(); 
                			$data = array(
                				"status"=> "1",
                				"remaining"=>$remaining,
                				"discount"=>$invoice->discount + $discount, //Add Current With the pre_Recieved Discount
                				"recieved"=>$invoice->recieved + $received, //Add Current With the pre_Recieved Recieved
                				"advance"=>$advance,
                				"fee_deposit_type"=>$fee_deposit_type,
                				"is_fine" => ($fine_chk == 1 && $invoice->is_fine ==0) ? "1" : "0",
                				"fine" => ($fine_chk == 1 && $invoice->is_fine ==0) ? $invoice->fine + $fine : $invoice->fine,
                				"submitted_at"=>$submitted_at
                			);
                			$this->db->where("id",$id);
                	    	if($this->db->update("invoice",$data)){
                		    date_default_timezone_set("Asia/Karachi");
                            $date = date('Y-m-d H:i:s');
                		    //Fee Log Entry
                		    $submit_detail = array(
                		        "inv_id"=>$id,
                		        "discount"=>$discount,
                		        "remaining"=>$remaining,
                		        "recieved"=>$received,
                		        "advance"=>$advance,
                		        "is_fine"=> ($fine_chk == 1 && $invoice->is_fine ==0) ? "1" : "0",
                		        "fine" => ($fine_chk == 1 && $invoice->is_fine ==0) ? $fine : "0",
                		        "student_id" => $contact_id,
                		        "user_id" => $user_id, 
                		        "date" => $submitted_at,
                		        "fee_deposit_type_account" => $fee_deposit_type,
                		        "branch_account"=>$branch,
                		        "create_at" => $date
                				);
                			$this->db->insert('fee_submit_logs',$submit_detail);
                			$update = array(
                			    'status' => 1,
                			    'remaining' => 0
                			    );
                			//On Voucher Submission All Previous Voucher will be Submitted
                	if(!empty($get_all_promotion))
        			{
        			   foreach($get_all_promotion as $prev_ids)
        			    {
        			       
        			        $this->db->where('invoice.id <',$id);
                			$this->db->where('invoice.student_id',$prev_ids['id']);
                			$this->db->update('invoice',$update);
        			    } 
        			}		
                	//		$this->db->where('invoice.id <',$id);
                	//		$this->db->where('invoice.student_id',$invoice->student_id);
                	//		$this->db->update('invoice',$update);
                			$result= $this->db->query("SELECT * FROM student WHERE id= '$contact_id' AND is_delete = 0")->row_array();
                			
                			//Update Account
                			$this->update_account($submitted_at,$fee_deposit_type);
                			
                			//Start App Notificaiton	
                			$tokens = array();
                			$tokens[]=$result['token'];
                			$message = array("message" => "Dear Parents your child fee submited","id"=>$contact_id,"topic"=>"fee" );   
                			$this->api_model->send_notification($tokens,$message);
                			//End App Notification
                			
                			//Start SMS on Voucher
                            $message="Dear Parents,\nTuition fee of your child ".$child_name." has been received Amount:".$received."\nThank you for co-operation\nPrincipal\n".$branch_name;
                			$this->hajanasms->sendOneNumber($contact_number,$message);
                			//$this->view($encrpt);
                			//End SMS on Voucher Submission
                			 redirect("voucher/view/".$encrpt);
                             //redirect("voucher/listv/","refresh"); 
                             // redirect("voucher/doPrint1/$id");
                             }
                    }else
                    {
                        $this->session->set_flashdata('bankmsg',"Please Set Primary Bank First");
                        redirect("voucher/listv/","refresh");
                    }
		}else
		{
		   
		                    $remaining=0;
                		    $advance=0;
                		    $rec_dis=0;
		                    $user_id = $this->user_model->userInfo("id")['id'];
                	    	$id = $this->input->post("id",true);
                			
                			$received = $this->input->post("recieved",true);
                			$discount = $this->input->post("discount",true);
                		    $g_total=$this->input->post("net",true);
                		    $rec_dis=$received+$discount;
                		    
                		    if($rec_dis>$g_total)
                		    {
                		       $advance=$rec_dis-$g_total;
                		       $remaining=0;
                		    }else{
                		       $remaining=$g_total-$rec_dis; 
                		       $advance=0;
                		    }
                		    
                			$fine_chk = $this->input->post("fine_chk",true);
                			$fine = $this->input->post("fine",true);
                		
                			$submitted_att = $this->input->post("submitted_at",true);
                			$submitted_at = date("Y-m-d", strtotime($submitted_att));
                			$contact_number=$this->voucher_model->getVoucherContactNumber($id)['father_contact'];
                			$contact_id=$this->voucher_model->getVoucherContactNumber($id)['id'];
                			$child_name=$this->voucher_model->getVoucherContactNumber($id)['student_name'];
                			$class_name=$this->voucher_model->getVoucherContactNumber($id)['class_name'];
                			
                			$branch_name = @$this->db->query("SELECT `name` FROM `branch` WHERE `id`=".$this->user_model->getBranch()." AND `is_delete`='0'")->result_array()[0]['name'];
                			$invoice = $this->db->where('id',$id)->get('invoice')->row();
                
                $get_student_id=$this->db->select('student_id')
                                         ->from('promotion')
                                         ->where('id',$invoice->student_id)
                                         ->where('is_delete',0)
                                         ->get()->row_array()['student_id'];
                                         
             $get_all_promotion=$this->db->select('id')
                                         ->from('promotion')
                                         ->where('student_id',$get_student_id)
                                         ->where('id<=',$invoice->student_id)
                                         ->get()->result_array(); 
                                         
                			$data = array(
                				"status"=> "1",
                				"remaining"=>$remaining,
                				"discount"=>$invoice->discount + $discount, //Add Current With the pre_Recieved Discount
                				"recieved"=>$invoice->recieved + $received, //Add Current With the pre_Recieved Recieved
                				"advance"=>$advance,
                				"fee_deposit_type"=>$fee_deposit_type,
                				"is_fine" => ($fine_chk == 1 && $invoice->is_fine ==0) ? "1" : "0",
                				"fine" => ($fine_chk == 1 && $invoice->is_fine ==0) ? $invoice->fine + $fine : $invoice->fine,
                				"submitted_at"=>$submitted_at
                			);
                			$this->db->where("id",$id);
                	    	if($this->db->update("invoice",$data)){
                		    date_default_timezone_set("Asia/Karachi");
                            $date = date('Y-m-d H:i:s');
                		    //Fee Log Entry
                		    $submit_detail = array(
                		        "inv_id"=>$id,
                		        "discount"=>$discount,
                		        "remaining"=>$remaining,
                		        "recieved"=>$received,
                		        "advance"=>$advance,
                		        "is_fine"=> ($fine_chk == 1 && $invoice->is_fine ==0) ? "1" : "0",
                		        "fine" => ($fine_chk == 1 && $invoice->is_fine ==0) ? $fine : "0",
                		        "student_id" => $contact_id,
                		        "user_id" => $user_id, 
                		        "date" => $submitted_at,
                		        "fee_deposit_type_account" => $fee_deposit_type,
                		        "branch_account"=>$branch,
                		        "create_at" => $date
                				);
                			$this->db->insert('fee_submit_logs',$submit_detail);
                			$update = array(
                			    'status' => 1,
                			    'remaining' => 0
                			    );
                			//On Voucher Submission All Previous Voucher will be Submitted
                if(!empty($get_all_promotion))
        			{
        			   foreach($get_all_promotion as $prev_ids)
        			    {
        			       
        			        $this->db->where('invoice.id <',$id);
                			$this->db->where('invoice.student_id',$prev_ids['id']);
                			$this->db->update('invoice',$update);
        			    } 
        			}
                		//	$this->db->where('invoice.id <',$id);
                	//		$this->db->where('invoice.student_id',$invoice->student_id);
                			
                	//		$this->db->update('invoice',$update);
                			$result= $this->db->query("SELECT * FROM student WHERE id= '$contact_id' AND is_delete = 0")->row_array();
                			
                			//Update Account
                			$this->update_account($submitted_at,$fee_deposit_type);
                			
                			//Start App Notificaiton	
                			$tokens = array();
                			$tokens[]=$result['token'];
                			$message = array("message" => "Dear Parents your child fee submited","id"=>$contact_id,"topic"=>"fee" );   
                			$this->api_model->send_notification($tokens,$message);
                			//End App Notification
                			
                			//Start SMS on Voucher
                            $message="Dear Parents,\nTuition fee of your child ".$child_name." has been received Amount:".$received."\nThank you for co-operation\nPrincipal\n".$branch_name;
                			$this->hajanasms->sendOneNumber($contact_number,$message);
                		//	$this->view($encrpt);
                			//End SMS on Voucher Submission
                			 redirect("voucher/view/".$encrpt);
                            // redirect("voucher/doPrint1/$id");
                             }
		}
	    
	}
	
	public function full_submit($id)
	{
	    $branch=$this->user_model->getbranch();
	    $fee_deposit_type=$this->db->select('*')
	                              ->from('branch')
	                              ->where('id',$branch)
	                              ->get()->row_array()['fee_deposit_type'];
	                              
	   $inv_status=$this->db->select('*')
	                              ->from('invoice')
	                              ->where('id',$id)
	                              ->get()->row_array()['status'];  
	  $received=0;
	  $total_pack=0;
	                              
	   $voucher= $this->db->query("SELECT `student`.`sid`,`student`.`student_name`,`student`.`grno`,`invoice`.`remaining`,`invoice`.`id` as `invoice`,`invoice`.`status`,`invoice`.`date`,`invoice`.`date_expire`,`class`.`class_name`,`section`.`section_name` FROM `invoice` INNER JOIN `promotion` ON `promotion`.`id` = `invoice`.`student_id` INNER JOIN `student` ON `student`.`id` = `promotion`.`student_id` INNER JOIN `class` ON `promotion`.`class_id` = `class`.`class_id` INNER JOIN `section` ON `promotion`.`section_id` = `section`.`section_id` WHERE `invoice`.`id`='$id'")->row_array();                           
    if($voucher['remaining'] == 0 && $voucher['status'] == 1)
    {
        $total_pack= 0;
        
    }elseif($voucher['remaining'] > 0 && $voucher['status'] !=0)
    {
        $total_pack= $voucher['remaining'];
        
    }else{if($this->voucher_model->countTotalFee($voucher['invoice']) >= 0){
        $total_pack= ($this->voucher_model->countTotalFee($voucher['invoice']));
        
    }else{
        $total_pack= 0;
        
    }}
    $received = $total_pack;
	    $user_id = $this->user_model->userInfo("id")['id'];
	   
	                        
	    $submitted_at = date("Y-m-d");                     
	    if(!empty($fee_deposit_type))
	    {
	        if($inv_status==1)
	        {
	            $this->session->set_flashdata('bankmsg',"Voucher Already Submitted...");
                redirect("voucher/listv/","refresh");
	        }else
	        {
	       if($fee_deposit_type=="bank")
	     	{
		    $branch=$this->user_model->getbranch();
	               $primary_bank=$this->db->select('*')
                                   ->from('bank_def')
                                   ->where('branch',$branch)
                                   ->where('fee_primary',1)
                                   ->where('is_active',1)
                                   ->get()->row_array();
                    if(!empty($primary_bank)) 
                    {
                        
                			
                			
                			$contact_number=$this->voucher_model->getVoucherContactNumber($id)['father_contact'];
                			$contact_id=$this->voucher_model->getVoucherContactNumber($id)['id'];
                			$child_name=$this->voucher_model->getVoucherContactNumber($id)['student_name'];
                			$class_name=$this->voucher_model->getVoucherContactNumber($id)['class_name'];
                			
                			$branch_name = @$this->db->query("SELECT `name` FROM `branch` WHERE `id`=".$this->user_model->getBranch()." AND `is_delete`='0'")->result_array()[0]['name'];
                			$invoice = $this->db->where('id',$id)->get('invoice')->row();
             
             $get_student_id=$this->db->select('student_id')
                                                     ->from('promotion')
                                                     ->where('id',$invoice->student_id)
                                                     ->where('is_delete',0)
                                                     ->get()->row_array()['student_id'];
             $get_all_promotion=$this->db->select('id')
                                         ->from('promotion')
                                         ->where('student_id',$get_student_id)
                                         ->where('id<=',$invoice->student_id)
                                         ->get()->result_array(); 
                                         
                			$data = array(
                				"status"=> "1",
                				"remaining"=>0,
                				"discount"=>0, //Add Current With the pre_Recieved Discount
                				"recieved"=>$received, //Add Current With the pre_Recieved Recieved
                				"advance"=>0,
                				"fee_deposit_type"=>$fee_deposit_type,
                				"is_fine" => "0",
                				"fine" =>0,
                				"submitted_at"=>$submitted_at
                			);
                			$this->db->where("id",$id);
                	    	if($this->db->update("invoice",$data)){
                		    date_default_timezone_set("Asia/Karachi");
                            $date = date('Y-m-d H:i:s');
                		    //Fee Log Entry
                		    $submit_detail = array(
                		        "inv_id"=>$id,
                		        "discount"=>0,
                		        "remaining"=>0,
                		        "recieved"=>$received,
                		        "advance"=>0,
                		        "is_fine"=>"0",
                		        "fine" => "0",
                		        "student_id" => $contact_id,
                		        "user_id" => $user_id, 
                		        "date" => $submitted_at,
                		        "fee_deposit_type_account" => $fee_deposit_type,
                		        "branch_account"=>$branch,
                		        "create_at" => $date
                				);
                			$this->db->insert('fee_submit_logs',$submit_detail);
                			$update = array(
                			    'status' => 1,
                			    'remaining' => 0
                			    );
                			//On Voucher Submission All Previous Voucher will be Submitted
                			if(!empty($get_all_promotion))
        			{
        			   foreach($get_all_promotion as $prev_ids)
        			    {
        			       
        			        $this->db->where('invoice.id <',$id);
                			$this->db->where('invoice.student_id',$prev_ids['id']);
                			$this->db->update('invoice',$update);
        			    } 
        			}
                	//		$this->db->where('invoice.id <',$id);
                	//		$this->db->where('invoice.student_id',$invoice->student_id);
                	//		$this->db->update('invoice',$update);
                			$result= $this->db->query("SELECT * FROM student WHERE id= '$contact_id' AND is_delete = 0")->row_array();
                			
                			//Update Account
                			$this->update_account($submitted_at,$fee_deposit_type);
                			
                			//Start App Notificaiton	
                			$tokens = array();
                			$tokens[]=$result['token'];
                			$message = array("message" => "Dear Parents your child fee submited","id"=>$contact_id,"topic"=>"fee" );   
                			$this->api_model->send_notification($tokens,$message);
                			//End App Notification
                			
                			//Start SMS on Voucher
                            $message="Dear Parents,\nTuition fee of your child ".$child_name." has been received Amount:".$received."\nThank you for co-operation\nPrincipal\n".$branch_name;
                			$this->hajanasms->sendOneNumber($contact_number,$message);
                			//End SMS on Voucher Submission
                            redirect("voucher/listv/","refresh"); 
                             }
                    }else
                    {
                        $this->session->set_flashdata('bankmsg',"Please Set Primary Bank First");
                        redirect("voucher/listv/","refresh");
                    }
		       }else
		     {
		   
		    $user_id = $this->user_model->userInfo("id")['id'];
                	    	
                			$contact_number=$this->voucher_model->getVoucherContactNumber($id)['father_contact'];
                			$contact_id=$this->voucher_model->getVoucherContactNumber($id)['id'];
                			$child_name=$this->voucher_model->getVoucherContactNumber($id)['student_name'];
                			$class_name=$this->voucher_model->getVoucherContactNumber($id)['class_name'];
                			
                			$branch_name = @$this->db->query("SELECT `name` FROM `branch` WHERE `id`=".$this->user_model->getBranch()." AND `is_delete`='0'")->result_array()[0]['name'];
                			$invoice = $this->db->where('id',$id)->get('invoice')->row();
            
            $get_student_id=$this->db->select('student_id')
                                                     ->from('promotion')
                                                     ->where('id',$invoice->student_id)
                                                     ->where('is_delete',0)
                                                     ->get()->row_array()['student_id'];
             $get_all_promotion=$this->db->select('id')
                                         ->from('promotion')
                                         ->where('student_id',$get_student_id)
                                         ->where('id<=',$invoice->student_id)
                                         ->get()->result_array(); 
                                         
                			$data = array(
                				"status"=> "1",
                				"remaining"=>0,
                				"discount"=>0, //Add Current With the pre_Recieved Discount
                				"recieved"=>$received, //Add Current With the pre_Recieved Recieved
                				"advance"=>0,
                				"fee_deposit_type"=>$fee_deposit_type,
                				"is_fine" =>"0",
                				"fine" =>0,
                				"submitted_at"=>$submitted_at
                			);
                			$this->db->where("id",$id);
                	    	if($this->db->update("invoice",$data)){
                		    date_default_timezone_set("Asia/Karachi");
                            $date = date('Y-m-d H:i:s');
                		    //Fee Log Entry
                		    $submit_detail = array(
                		        "inv_id"=>$id,
                		        "discount"=>0,
                		        "remaining"=>0,
                		        "recieved"=>$received,
                		        "advance"=>0,
                		        "is_fine"=>"0",
                		        "fine" =>"0",
                		        "student_id" => $contact_id,
                		        "user_id" => $user_id, 
                		        "date" => $submitted_at,
                		        "fee_deposit_type_account" => $fee_deposit_type,
                		        "branch_account"=>$branch,
                		        "create_at" => $date
                				);
                			$this->db->insert('fee_submit_logs',$submit_detail);
                			$update = array(
                			    'status' => 1,
                			    'remaining' => 0
                			    );
                			//On Voucher Submission All Previous Voucher will be Submitted
                			
                if(!empty($get_all_promotion))
        			{
        			   foreach($get_all_promotion as $prev_ids)
        			    {
        			       
        			        $this->db->where('invoice.id <',$id);
                			$this->db->where('invoice.student_id',$prev_ids['id']);
                			$this->db->update('invoice',$update);
        			    } 
        			}
        			
                	//		$this->db->where('invoice.id <',$id);
                	//		$this->db->where('invoice.student_id',$invoice->student_id);
                			
                	//		$this->db->update('invoice',$update);
                			$result= $this->db->query("SELECT * FROM student WHERE id= '$contact_id' AND is_delete = 0")->row_array();
                			
                			//Update Account
                			$this->update_account($submitted_at,$fee_deposit_type);
                			
                			//Start App Notificaiton	
                			$tokens = array();
                			$tokens[]=$result['token'];
                			$message = array("message" => "Dear Parents your child fee submited","id"=>$contact_id,"topic"=>"fee" );   
                			$this->api_model->send_notification($tokens,$message);
                			//End App Notification
                			
                			//Start SMS on Voucher
                            $message="Dear Parents,\nTuition fee of your child ".$child_name." has been received Amount:".$received."\nThank you for co-operation\nPrincipal\n".$branch_name;
                			$this->hajanasms->sendOneNumber($contact_number,$message);
                			//End SMS on Voucher Submission
                		    redirect("voucher/listv/","refresh"); 
                             }
	            	}
	        }
	        
	    }else
	    {
	        $this->session->set_flashdata('bankmsg',"Please Define Fee Deposit Type In Branch...");
            redirect("voucher/listv/","refresh");
	    }
	}
	
	public function full_submit_receipt($id)
	{
	   
	    $branch=$this->user_model->getbranch();
	    $fee_deposit_type=$this->db->select('*')
	                              ->from('branch')
	                              ->where('id',$branch)
	                              ->get()->row_array()['fee_deposit_type'];
	                              
	   $inv_status=$this->db->select('*')
	                              ->from('invoice')
	                              ->where('id',$id)
	                              ->get()->row_array()['status'];  
	  $received=0;
	  $total_pack=0;
	                              
	   $voucher= $this->db->query("SELECT `student`.`sid`,`student`.`student_name`,`student`.`grno`,`invoice`.`remaining`,`invoice`.`id` as `invoice`,`invoice`.`status`,`invoice`.`date`,`invoice`.`date_expire`,`class`.`class_name`,`section`.`section_name` FROM `invoice` INNER JOIN `promotion` ON `promotion`.`id` = `invoice`.`student_id` INNER JOIN `student` ON `student`.`id` = `promotion`.`student_id` INNER JOIN `class` ON `promotion`.`class_id` = `class`.`class_id` INNER JOIN `section` ON `promotion`.`section_id` = `section`.`section_id` WHERE `invoice`.`id`='$id'")->row_array();                           
    if($voucher['remaining'] == 0 && $voucher['status'] == 1)
    {
        $total_pack= 0;
        
    }elseif($voucher['remaining'] > 0 && $voucher['status'] !=0)
    {
        $total_pack= $voucher['remaining'];
        
    }else{if($this->voucher_model->countTotalFee($voucher['invoice']) >= 0){
        $total_pack= ($this->voucher_model->countTotalFee($voucher['invoice']));
        
    }else{
        $total_pack= 0;
        
    }}
    $received = $total_pack;
	    $user_id = $this->user_model->userInfo("id")['id'];
	   
	                        
	    $submitted_at = date("Y-m-d");                     
	    if(!empty($fee_deposit_type))
	    {
	        if($inv_status==1)
	        {
	            $this->session->set_flashdata('bankmsg',"Voucher Already Submitted...");
                redirect("voucher/listv/","refresh");
	        }else
	        {
	       if($fee_deposit_type=="bank")
	     	{
		    $branch=$this->user_model->getbranch();
	               $primary_bank=$this->db->select('*')
                                   ->from('bank_def')
                                   ->where('branch',$branch)
                                   ->where('fee_primary',1)
                                   ->where('is_active',1)
                                   ->get()->row_array();
                    if(!empty($primary_bank)) 
                    {
                        
                			
                			
                			$contact_number=$this->voucher_model->getVoucherContactNumber($id)['father_contact'];
                			$contact_id=$this->voucher_model->getVoucherContactNumber($id)['id'];
                			$child_name=$this->voucher_model->getVoucherContactNumber($id)['student_name'];
                			$class_name=$this->voucher_model->getVoucherContactNumber($id)['class_name'];
                			
                			$branch_name = @$this->db->query("SELECT `name` FROM `branch` WHERE `id`=".$this->user_model->getBranch()." AND `is_delete`='0'")->result_array()[0]['name'];
                			$invoice = $this->db->where('id',$id)->get('invoice')->row();
             
             $get_student_id=$this->db->select('student_id')
                                                     ->from('promotion')
                                                     ->where('id',$invoice->student_id)
                                                     ->where('is_delete',0)
                                                     ->get()->row_array()['student_id'];
             $get_all_promotion=$this->db->select('id')
                                         ->from('promotion')
                                         ->where('student_id',$get_student_id)
                                         ->where('id<=',$invoice->student_id)
                                         ->get()->result_array(); 
                                         
                			$data = array(
                				"status"=> "1",
                				"remaining"=>0,
                				"discount"=>0, //Add Current With the pre_Recieved Discount
                				"recieved"=>$received, //Add Current With the pre_Recieved Recieved
                				"advance"=>0,
                				"fee_deposit_type"=>$fee_deposit_type,
                				"is_fine" => "0",
                				"fine" =>0,
                				"submitted_at"=>$submitted_at
                			);
                			$this->db->where("id",$id);
                	    	if($this->db->update("invoice",$data)){
                		    date_default_timezone_set("Asia/Karachi");
                            $date = date('Y-m-d H:i:s');
                		    //Fee Log Entry
                		    $submit_detail = array(
                		        "inv_id"=>$id,
                		        "discount"=>0,
                		        "remaining"=>0,
                		        "recieved"=>$received,
                		        "advance"=>0,
                		        "is_fine"=>"0",
                		        "fine" => "0",
                		        "student_id" => $contact_id,
                		        "user_id" => $user_id, 
                		        "date" => $submitted_at,
                		        "fee_deposit_type_account" => $fee_deposit_type,
                		        "branch_account"=>$branch,
                		        "create_at" => $date
                				);
                			$this->db->insert('fee_submit_logs',$submit_detail);
                			$update = array(
                			    'status' => 1,
                			    'remaining' => 0
                			    );
                			//On Voucher Submission All Previous Voucher will be Submitted
                if(!empty($get_all_promotion))
        			{
        			   foreach($get_all_promotion as $prev_ids)
        			    {
        			       
        			        $this->db->where('invoice.id <',$id);
                			$this->db->where('invoice.student_id',$prev_ids['id']);
                			$this->db->update('invoice',$update);
        			    } 
        			}
                	//		$this->db->where('invoice.id <',$id);
                	//		$this->db->where('invoice.student_id',$invoice->student_id);
                			
                	//		$this->db->update('invoice',$update);
                			$result= $this->db->query("SELECT * FROM student WHERE id= '$contact_id' AND is_delete = 0")->row_array();
                			
                			//Update Account
                			$this->update_account($submitted_at,$fee_deposit_type);
                			
                			//Start App Notificaiton	
                			$tokens = array();
                			$tokens[]=$result['token'];
                			$message = array("message" => "Dear Parents your child fee submited","id"=>$contact_id,"topic"=>"fee" );   
                			$this->api_model->send_notification($tokens,$message);
                			//End App Notification
                			
                			//Start SMS on Voucher
                            $message="Dear Parents,\nTuition fee of your child ".$child_name." has been received Amount:".$received."\nThank you for co-operation\nPrincipal\n".$branch_name;
                			$this->hajanasms->sendOneNumber($contact_number,$message);
                			//End SMS on Voucher Submission
                            redirect("voucher/doprint1/".$id,"refresh"); 
                             }
                    }else
                    {
                        $this->session->set_flashdata('bankmsg',"Please Set Primary Bank First");
                        redirect("voucher/listv/","refresh");
                    }
		       }else
		     {
		   
		    $user_id = $this->user_model->userInfo("id")['id'];
                	    	
                			$contact_number=$this->voucher_model->getVoucherContactNumber($id)['father_contact'];
                			$contact_id=$this->voucher_model->getVoucherContactNumber($id)['id'];
                			$child_name=$this->voucher_model->getVoucherContactNumber($id)['student_name'];
                			$class_name=$this->voucher_model->getVoucherContactNumber($id)['class_name'];
                			
                			$branch_name = @$this->db->query("SELECT `name` FROM `branch` WHERE `id`=".$this->user_model->getBranch()." AND `is_delete`='0'")->result_array()[0]['name'];
                			$invoice = $this->db->where('id',$id)->get('invoice')->row();
            
            $get_student_id=$this->db->select('student_id')
                                                     ->from('promotion')
                                                     ->where('id',$invoice->student_id)
                                                     ->where('is_delete',0)
                                                     ->get()->row_array()['student_id'];
             $get_all_promotion=$this->db->select('id')
                                         ->from('promotion')
                                         ->where('student_id',$get_student_id)
                                         ->where('id<=',$invoice->student_id)
                                         ->get()->result_array(); 
                                         
                			$data = array(
                				"status"=> "1",
                				"remaining"=>0,
                				"discount"=>0, //Add Current With the pre_Recieved Discount
                				"recieved"=>$received, //Add Current With the pre_Recieved Recieved
                				"advance"=>0,
                				"fee_deposit_type"=>$fee_deposit_type,
                				"is_fine" =>"0",
                				"fine" =>0,
                				"submitted_at"=>$submitted_at
                			);
                			$this->db->where("id",$id);
                	    	if($this->db->update("invoice",$data)){
                		    date_default_timezone_set("Asia/Karachi");
                            $date = date('Y-m-d H:i:s');
                		    //Fee Log Entry
                		    $submit_detail = array(
                		        "inv_id"=>$id,
                		        "discount"=>0,
                		        "remaining"=>0,
                		        "recieved"=>$received,
                		        "advance"=>0,
                		        "is_fine"=>"0",
                		        "fine" =>"0",
                		        "student_id" => $contact_id,
                		        "user_id" => $user_id, 
                		        "date" => $submitted_at,
                		        "fee_deposit_type_account" => $fee_deposit_type,
                		        "branch_account"=>$branch,
                		        "create_at" => $date
                				);
                			$this->db->insert('fee_submit_logs',$submit_detail);
                			$update = array(
                			    'status' => 1,
                			    'remaining' => 0
                			    );
                			//On Voucher Submission All Previous Voucher will be Submitted
                			if(!empty($get_all_promotion))
        			{
        			   foreach($get_all_promotion as $prev_ids)
        			    {
        			       
        			        $this->db->where('invoice.id <',$id);
                			$this->db->where('invoice.student_id',$prev_ids['id']);
                			$this->db->update('invoice',$update);
        			    } 
        			}
                		//	$this->db->where('invoice.id <',$id);
                	//		$this->db->where('invoice.student_id',$invoice->student_id);
                			
                	//		$this->db->update('invoice',$update);
                			$result= $this->db->query("SELECT * FROM student WHERE id= '$contact_id' AND is_delete = 0")->row_array();
                			
                			//Update Account
                			$this->update_account($submitted_at,$fee_deposit_type);
                			
                			//Start App Notificaiton	
                			$tokens = array();
                			$tokens[]=$result['token'];
                			$message = array("message" => "Dear Parents your child fee submited","id"=>$contact_id,"topic"=>"fee" );   
                			$this->api_model->send_notification($tokens,$message);
                			//End App Notification
                			
                			//Start SMS on Voucher
                            $message="Dear Parents,\nTuition fee of your child ".$child_name." has been received Amount:".$received."\nThank you for co-operation\nPrincipal\n".$branch_name;
                			$this->hajanasms->sendOneNumber($contact_number,$message);
                			//End SMS on Voucher Submission
                		    redirect("voucher/doprint1/".$id,"refresh"); 
                             }
	            	}
	        }
	        
	    }else
	    {
	        $this->session->set_flashdata('bankmsg',"Please Define Fee Deposit Type In Branch...");
            redirect("voucher/listv/","refresh");
	    }
	}
	
	public function update_account($submitted_at="",$fee_deposit_type="")
	{
	   $branch=$this->user_model->getbranch();
	    if(!empty($submitted_at) && !empty($fee_deposit_type))
	    {
	        $sum_amount=$this->db->select('sum(recieved) as recieved')
	                             ->from('fee_submit_logs')
	                             ->where('fee_deposit_type_account',$fee_deposit_type)
	                             ->where('left(date,10)',$submitted_at)
	                             ->where('branch_account',$branch)
	                             ->get()->row_array()['recieved'];
	   
	           if($fee_deposit_type=="cash")
	           {
	           
	               $check_voucher=$this->db->select('*')
	                                       ->from('transction')
	                                       ->where('head',6)
	                                       ->where('fee_voucher',1)
	                                       ->where('date',$submitted_at)
	                                       ->where('has_cr',1)
	                                       ->where('branch',$branch)
	                                       ->get()->row_array();
	               if(empty($check_voucher)) 
	               {
	                   $curdate= date('Y-m-d H:i:s');
	                   $branch=$this->user_model->getbranch();
	                   $t = microtime(true);
                       $micro = sprintf("%06d",($t - floor($t)) * 1000000);
                       $date = new DateTime(date('Y-m-d H:i:s.'.$micro, $t));
                       $trans_id=$date->getTimestamp();
                       $id=$this->user_model->userInfo('id')['id'];
                       $type="cash receipt";
                        $num=$this->db->query("SELECT voucher_no FROM `transction` where type='$type' and branch=$branch order by id desc limit 1 ")->row_array()['voucher_no'];
                        if($num==null)
                        {
                            $num=1;
                        } 
                        else{
                        preg_match_all('!\d+!', $num, $matches);
                        $num=$matches[0][0];
                        $num++;
                        }
                         $voucher_no="CR".$num;
                    
                       $hard_fir=array(
                        'date'=>$submitted_at,
                        'created_date'=>$curdate,
                        'type'=>"cash receipt",
                        'head' =>6,
                        'head_name' =>"Cash in hand",
                        'narration' =>"Fee Received ".$submitted_at,
                        'program' =>0,
                        'project' =>0,
                        'program_name' =>"Education",
                        'project_name' =>"School",
                        'amount' =>$sum_amount,
                        'created_by'=>$id ,
                        'paid_from'=>"Fee",
                        'branch' =>$branch,
                        'balance' =>0,
                        'after_transction'=>$sum_amount,
                        'transction_id'=>$trans_id,
                        'voucher_no'=>$voucher_no,
                        'has_cr'=>1,
                        'fee_voucher'=>1
                         );
                  
                        $this->db->insert('transction',$hard_fir);
                        
                        //Second Effect
                         $hard_sec=array(
                        'date'=>$submitted_at,
                        'created_date'=>$curdate,
                        'type'=>"cash receipt",
                        'head' =>524,
                        'head_name' =>"Tuition Fee",
                        'narration' =>"Fee Received ".$submitted_at,
                        'program' =>0,
                        'project' =>0,
                        'program_name' =>"Education",
                        'project_name' =>"School",
                        'amount' =>$sum_amount,
                        'created_by'=>$id ,
                        'paid_from'=>"Fee",
                        'branch' =>$branch,
                        'balance' =>0,
                        'after_transction'=>$sum_amount,
                        'transction_id'=>$trans_id,
                        'voucher_no'=>$voucher_no,
                        'has_cr'=>0,
                        'fee_voucher'=>1
                         );
                         $this->db->insert('transction',$hard_sec);
	               }else
	               {
	                   //Update Record
	                   $voucher_no=$check_voucher['voucher_no'];
	                   
	                   $up_data=array(
	                       'amount'=>$sum_amount
	                       );
	                       $this->db->where('head',6)
	                                ->where('voucher_no',$voucher_no)
	                                ->where('date',$submitted_at)
	                                ->where('fee_voucher',1)
	                                ->where('branch',$branch)
	                                ->update('transction',$up_data);
	                      
	                       $this->db->where('head',524)
	                                ->where('voucher_no',$voucher_no)
	                                ->where('date',$submitted_at)
	                                ->where('fee_voucher',1)
	                                ->where('branch',$branch)
	                                ->update('transction',$up_data);             
	               }
	           }else
	           {
	               //Banks
	               $branch=$this->user_model->getbranch();
	               $primary_bank=$this->db->select('*')
	                                       ->from('bank_def')
	                                       ->where('branch',$branch)
	                                       ->where('fee_primary',1)
	                                       ->where('is_active',1)
	                                       ->get()->row_array();
	                       if(!empty($primary_bank))
	                       {
	                        $account_bank=$this->db->select('*')
        	                                       ->from('account_heads')
        	                                       ->where('name',$primary_bank['b_name'])
        	                                       ->where('parent',5)
        	                                       ->where('has_child',0)
        	                                       ->get()->row_array();
        	                      if(!empty($account_bank)) 
        	                      {
        	                          $check_voucher=$this->db->select('*')
                    	                                       ->from('transction')
                    	                                       ->where('head',$account_bank['id'])
                    	                                       ->where('fee_voucher',1)
                    	                                       ->where('date',$submitted_at)
                    	                                       ->where('has_cr',1)
                    	                                       ->where('branch',$branch)
                    	                                       ->get()->row_array();  
                    	                   
                    	               if(empty($check_voucher)) 
                    	                   {
                    	                          $curdate= date('Y-m-d H:i:s');
                            	                   $branch=$this->user_model->getbranch();
                            	                   $t = microtime(true);
                                                   $micro = sprintf("%06d",($t - floor($t)) * 1000000);
                                                   $date = new DateTime(date('Y-m-d H:i:s.'.$micro, $t));
                                                   $trans_id=$date->getTimestamp();
                                                   $id=$this->user_model->userInfo('id')['id'];
                                                   $type="bank receipt";
                                                    $num=$this->db->query("SELECT voucher_no FROM `transction` where type='$type' and branch=$branch order by id desc limit 1 ")->row_array()['voucher_no'];
                                                    if($num==null)
                                                    {
                                                        $num=1;
                                                    } 
                                                    else{
                                                    preg_match_all('!\d+!', $num, $matches);
                                                    $num=$matches[0][0];
                                                    $num++;
                                                    }
                                                     $voucher_no="BR".$num;
                    	                       
                    	                       $bnk_fir=array(
                                                    'date'=>$submitted_at,
                                                    'created_date'=>$curdate,
                                                    'type'=>"bank receipt",
                                                    'head' =>$account_bank['id'],
                                                    'head_name' =>$account_bank['name'],
                                                    'narration' =>"Fee Received ".$submitted_at,
                                                    'program' =>0,
                                                    'project' =>0,
                                                    'program_name' =>"Education",
                                                    'project_name' =>"School",
                                                    'amount' =>$sum_amount,
                                                    'created_by'=>$id ,
                                                    'paid_from'=>"Fee",
                                                    'branch' =>$branch,
                                                    'balance' =>0,
                                                    'after_transction'=>0,
                                                    'transction_id'=>$trans_id,
                                                    'voucher_no'=>$voucher_no,
                                                    'chq'=>0,
                                                    'has_cr'=>1,
                                                    'fee_voucher'=>1
                                                    
                                                     );
                                             
                                                  $this->db->insert('transction',$bnk_fir); 
                                                  
                                                  $bnk_sec=array(
                                                    'date'=>$submitted_at,
                                                    'created_date'=>$curdate,
                                                    'type'=>"bank receipt",
                                                    'head' =>524,
                                                     'head_name' =>"Tuition Fee",
                                                    'narration' =>"Fee Received ".$submitted_at,
                                                    'program' =>0,
                                                    'project' =>0,
                                                    'program_name' =>"Education",
                                                    'project_name' =>"School",
                                                    'amount' =>$sum_amount,
                                                    'created_by'=>$id ,
                                                    'paid_from'=>"Fee",
                                                    'branch' =>$branch,
                                                    'balance' =>0,
                                                    'after_transction'=>0,
                                                    'transction_id'=>$trans_id,
                                                    'voucher_no'=>$voucher_no,
                                                    'chq'=>0,
                                                    'has_cr'=>0,
                                                    'fee_voucher'=>1
                                                    
                                                     );
                                             
                                                  $this->db->insert('transction',$bnk_sec); 
                    	                   }else
                    	                   {
                    	                       //Update Record
                    	                        $voucher_no=$check_voucher['voucher_no'];
	                   
                        	                   $up_data=array(
                        	                       'amount'=>$sum_amount
                        	                       );
                        	                       $this->db->where('head',$account_bank['id'])
                        	                                ->where('voucher_no',$voucher_no)
                        	                                ->where('date',$submitted_at)
                        	                                ->where('fee_voucher',1)
                        	                                ->where('branch',$branch)
                        	                                ->update('transction',$up_data);
                        	                      
                        	                       $this->db->where('head',524)
                        	                                ->where('voucher_no',$voucher_no)
                        	                                ->where('date',$submitted_at)
                        	                                ->where('fee_voucher',1)
                        	                                ->where('branch',$branch)
                        	                                ->update('transction',$up_data);
                    	                       
                    	                   }
        	                      }
        	                                     
	                       }
	                                       
	               
	           }
	    }
	}

	public function classPrint($b="",$c="",$s="",$sess="",$m="")
	{
		if (!empty($b) AND !empty($c) AND !empty($s) AND !empty($sess) AND !empty($m)) {
			$data['base_url'] = base_url();
			$branch = $this->user_model->getBranch();
			$data['branch_fine_type']=$this->db->where('id',$branch)->get('branch')->row()->fine_type;

			$is_super = $this->user_model->is_super();
			$data['students'] = [];
			$data['b_header'] = [];
			$students = $this->db->query("SELECT `student`.`id`,`promotion`.`id` as pid,`student`.`grno`,`student`.`student_name`,`student`.`father_name`,`student`.`student_contact`,`class`.`class_name`,`section`.`section_name`,`student`.disc_value FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` INNER JOIN `class` ON `promotion`.`class_id`=`class`.`class_id` INNER JOIN `section` ON `section`.`section_id`=`promotion`.`section_id` WHERE `student`.`branch`='$b' AND `promotion`.`class_id`='$c' AND `promotion`.`section_id`='$s' AND `promotion`.`session_id`='$sess'")->result_array();
			foreach ($students as $key => $value) {
				$data['students'][$key] = $value;
				$id = $value['id'];
				$pid = $value['pid'];
				if($is_super)
					$data['invoice'][$key] = @$this->db->query("SELECT * FROM `invoice` WHERE `student_id`='$pid' AND `is_delete`='0' AND LEFT(`date`,7)='$m'")->result_array()[0];
				else
					$data['invoice'][$key] = @$this->db->query("SELECT * FROM `invoice` WHERE `student_id`='$pid' AND `is_delete`='0' AND `branch_id`='$branch' AND LEFT(`date`,7)='$m'")->result_array()[0];
				$data['fee'][$key] = $this->db->query("SELECT `fee_def`.`name`,`fee_installment`.`amount` FROM `fee_installment` INNER JOIN `fee_def` ON `fee_def`.`id`=`fee_installment`.`fee_id` WHERE `fee_installment`.`invoice`='".$data['invoice'][$key]['id']."' AND `fee_installment`.`is_delete`='0'")->result_array();
				$data['add_months'][$key]=@$this->db->where('invoice_id',$data['invoice'][$key]['id'])->where('is_delete',0)->get('fee_add_months')->result_array();
				$tot = $this->db->query("SELECT sum(`amount`) as sum FROM `fee_installment` WHERE `invoice`='".$data['invoice'][$key]['id']."' AND `is_delete`='0'")->result_array()[0]['sum'];
				if(!empty($data['invoice'][$key]))
				$lastv=$this->voucher_model->getLastVoucher($data['invoice'][$key]['student_id'],$data['invoice'][$key]['id']);
				else
				$lastv=false;
				
				//arrears logic
				$data['lastadv'][$key] = 0;
				$data['lastrem'][$key] = 0;
		        if($lastv && $lastv[0]['status']==1)
		        {
				$data['lastadv'][$key] = $lastv[0]['advance'];
				$data['lastrem'][$key] = $lastv[0]['remaining']+$data['invoice'][$key]['remaining'];;			
		        }
		        
		        elseif($lastv && $lastv[0]['status']==0)
		        {
			     $data['lastadv'][$key] = 0;
				 $data['lastrem'][$key] = $this->voucher_model->countArrears($data['invoice'][$key]['id'],$data['invoice'][$key]['student_id'],0);
		        }
		        else{
		         $data['lastadv'][$key] = $data['invoice'][$key]['advance'];
			     $data['lastrem'][$key] = $data['invoice'][$key]['remaining'];
		        }
				//end arrears logic
				$data['total'][$key] = $tot + $data['invoice'][$key]['fee_pack'];
				foreach ($data['add_months'][$key] as $k => $v) {
					$data['total'][$key]+=$v['fee'];
				}
				$data['b_header'] = @$this->db->query("SELECT * FROM `branch` WHERE `id`='$b' AND `is_delete`='0'")->result_array()[0];
			}
			$this->load->view('printable/voucher_class_wise',$data);
		}else{
			redirect("home","refresh");
		}
	}

	public function sms_defaulters($class_id='',$section_id='')
	{ 
	    $b = $this->user_model->getBranch();
        $b_name = $this->db->select('name')->where('id',$b)->get('branch')->row()->name;
    //	if($class_id!='' && $section_id!='') {
			$data = [];
			//$month = date("Y-m", strtotime("first day of -1 month") );
		    $month = date("Y-m");
			$date = date("Y-m-d");
		    $this->db->select("invoice.id as invoice_id,student.father_contact,student.grno,student.student_name")
                    			->from("student")
                    			->join("promotion","promotion.student_id=student.id")
                    			->join("invoice","invoice.student_id=promotion.id")
                    			->where("student.status","0")
                    			->where("student.branch",$b)
                    			->where("promotion.is_delete","0")
                    			->where("promotion.is_active","1")
                    			->where("invoice.is_delete","0")
                    			->where("invoice.status","0")
                    			->where("LEFT(invoice.date,7)",$month)
                    			->where("invoice.date_expire<=",$date);
                    	if(!empty($class_id))
                    	{
                    	   $this->db->where("promotion.class_id",$class_id); 
                    	}
                    	
                    	if(!empty($section_id))
                    	{
                    	   $this->db->where("promotion.section_id",$section_id);
                    	}
            $students =$this->db->get()->result();
			foreach ($students as $key => $value)
			 {
				$fee=$this->voucher_model->countTotalFee($value->invoice_id);
				$message="Dear Parents,\nIt is informed you that Tution Fee of your child ".$value->student_name." is still pending. Please try to clear remaining dues as soon as possible.\nAmount: ".$fee."\nThank You\nPrincipal\n$b_name";
			    $this->hajanasms->sendOneNumber($value->father_contact,$message);
			 }
			
		$this->session->set_flashdata('msg', 'SMS is  Send');
		redirect("voucher/listV");
				
	//	}
	}
	
	public function sms_reminder($class_id='',$section_id='')
	{ 
	    $b = $this->user_model->getBranch();
        $b_name = $this->db->select('name')->where('id',$b)->get('branch')->row()->name;
	//	if($class_id!='' && $section_id!='') {
			$data = [];
			//$month = date("Y-m", strtotime("first day of -1 month") );
		    $month = date("Y-m");
			$date = date("Y-m-d");
			 $this->db->select("invoice.id as invoice_id,student.father_contact,student.grno,student.student_name")
                    			 ->from("student")
                    			 ->join("promotion","promotion.student_id=student.id")
                    			 ->join("invoice","invoice.student_id=promotion.id")
                    			 ->where("student.status","0")
                    			 ->where("student.branch",$b)
                    			 ->where("promotion.is_delete","0")
                    			 ->where("promotion.is_active","1")
                    			 ->where("invoice.is_delete","0")
                    			 ->where("invoice.status","0")
                    			 ->where("LEFT(invoice.date,7)",$month);
                    			 
                    	if(!empty($class_id))
                    	{
                    	   $this->db->where("promotion.class_id",$class_id); 
                    	}
                    	
                    	if(!empty($section_id))
                    	{
                    	   $this->db->where("promotion.section_id",$section_id);
                    	}
                    			 
              $students =$this->db->get()->result();
		
			foreach ($students as $key => $value)
			 {
				$fee=$this->voucher_model->countTotalFee($value->invoice_id);
				$message="Dear Parents,\nIt is informed you that Tution Fee of your child ".$value->student_name." is still pending. Please try to clear remaining dues as soon as possible.\nAmount: ".$fee."\nThank You\nPrincipal\n$b_name";
		        $this->hajanasms->sendOneNumber($value->father_contact,$message);
			 }
			
		$this->session->set_flashdata('msg', 'SMS is  Send');
		redirect("voucher/listV");
				
	//	}
	}
	
//===========================================fee history view============================
	public function fee_history()
	{
		$this->user_model->check_permissions("voucher/fee_history");
		$branch = $this->user_model->getBranch();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
		$data['userInfo'] = $this->userInfo;
		if($this->user_model->is_super())
		{
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
		} else {
			$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `id`='$branch' AND `is_delete`='0'")->result_array();
		}
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('voucher/History',$data);
	}
//===================================show student wise history of fee==========================
public function create_history_old22_02_2019()
{
$branch = $this->user_model->getBranch();
$data['menu'] = $this->load_model->menu();
$data['base_url'] = base_url();
$data['userInfo'] = $this->userInfo;
if($this->input->post())
{

$sid = $this->input->post("gr",true);
$branch= $this->input->post('branch');
$data['b_header'] = $this->db->query("SELECT 
                name,title,tagline,short_address,phone_no,email,logo1,logo2 
                from branch where id='$branch' AND is_delete='0'")->row_array();
$data['branch_name']=$data['b_header']['name'];
	//var_dump($grno);die();
$this->db->select("student.student_name,student.id as stid,invoice.student_id,invoice.is_auto,invoice.id,section.section_name,class.class_name,student.sid,promotion.id as pid,student.father_contact,student.father_name,student.student_contact,invoice.fee_pack,invoice.late_fine,branch.name,invoice.id,invoice.date,invoice.date_expire,branch.contact,branch.b_logo,invoice.is_admitted");
$this->db->join("promotion","invoice.student_id=promotion.id");
$this->db->join("student","student.id=promotion.student_id");
$this->db->join("branch","invoice.branch_id=branch.id");
$this->db->join("class","promotion.class_id=class.class_id");
$this->db->join("section","promotion.section_id=section.section_id");
$this->db->where("student.sid",$sid);
$this->db->where("invoice.is_delete",'0');
$this->db->where("student.branch",$branch);
$this->db->order_by("promotion.id","DESC");
$data['detail']= $this->db->get("invoice")->row_array();


$pro_id_array=$this->voucher_model->getPromotionArray($data['detail']['pid']);
//echo "<pre>";print_r($pro_id_array);exit;
$query=$this->db->query("SELECT student.student_name,fee_submit_logs.student_id as s_id,fee_submit_logs.date as f_date,fee_submit_logs.id as flog_id,invoice.status, student.father_name , student.sid,invoice.submitted_at,fee_submit_logs.inv_id,fee_submit_logs.fine as fine,fee_submit_logs.discount as discount,fee_submit_logs.advance,fee_submit_logs.recieved as recieved, invoice.id as invoice_id ,invoice.date, student.father_contact,fee_submit_logs.remaining,class_name,section_name,invoice.is_auto FROM `invoice` INNER JOIN fee_submit_logs on fee_submit_logs.inv_id= invoice.id INNER JOIN promotion on promotion.id=invoice.student_id INNER JOIN section on promotion.section_id = section.section_id INNER JOIN class on class.class_id = promotion.class_id INNER JOIN student on student.id=promotion.student_id 
                 where fee_submit_logs.student_id = '".$data['detail']['stid']."' and invoice.branch_id=$branch and invoice.is_delete=0 order by fee_submit_logs.inv_id ASC");
$data['student'] = $query->result_array();
	// echo "<pre>";print_r($data['student']);exit;
foreach ($data['student'] as $key => $value) {
if($value['remaining'] == 0 && $value['status'] == 1){$data['student'][$key]['fee_total']=(($value['recieved']+$value['discount']) - ($value['fine'] + $value['advance']));}
elseif($value['remaining'] > 0 && $value['status'] !=0){$data['student'][$key]['fee_total']=(($value['recieved']+$value['discount']+$value['remaining']) - $value['fine']);}
                      else{$data['student'][$key]['fee_total']=$this->voucher_model->countTotalFee($value['invoice_id']);}
                 }

                 $data['base_url'] =  base_url();
                 $data['userInfo'] = $this->userInfo;
                 $this->load->view('printable/Fee_history',$data);
	            }
           	}

public function create_history()
{
$branch = $this->user_model->getBranch();
$data['menu'] = $this->load_model->menu();
$data['base_url'] = base_url();
$data['userInfo'] = $this->userInfo;
if($this->input->post())
{

$sid = $this->input->post("gr",true);
$branch= $this->input->post('branch');
$data['b_header'] = $this->db->query("SELECT 
                name,title,tagline,short_address,phone_no,email,logo1,logo2 
                from branch where id='$branch' AND is_delete='0'")->row_array();
$data['branch_name']=$data['b_header']['name'];
	//var_dump($grno);die();
$this->db->select("student.student_name,student.id as stid,invoice.student_id,invoice.is_auto,invoice.id,section.section_name,class.class_name,student.sid,promotion.id as pid,student.father_contact,student.father_name,student.student_contact,invoice.fee_pack,invoice.late_fine,branch.name,invoice.id,invoice.date,invoice.date_expire,branch.contact,branch.b_logo,invoice.is_admitted");
$this->db->join("promotion","invoice.student_id=promotion.id");
$this->db->join("student","student.id=promotion.student_id");
$this->db->join("branch","invoice.branch_id=branch.id");
$this->db->join("class","promotion.class_id=class.class_id");
$this->db->join("section","promotion.section_id=section.section_id");
$this->db->where("student.sid",$sid);
$this->db->where("invoice.is_delete",'0');
$this->db->where("student.branch",$branch);
$this->db->order_by("promotion.id","DESC");
$data['detail']= $this->db->get("invoice")->row_array();

//var_dump('<pre>',$data['detail']);
//die();

$pro_id_array=$this->voucher_model->getPromotionArray($data['detail']['pid']);
//echo "<pre>";print_r($pro_id_array);exit;
$this->db->select("student.student_name,student.father_name,student.sid,student.father_contact,
                                fee_submit_logs.student_id as s_id,fee_submit_logs.date as f_date,fee_submit_logs.id as flog_id,fee_submit_logs.inv_id,
                                fee_submit_logs.fine as fine,fee_submit_logs.discount as discount,fee_submit_logs.recieved as recieved,
                                fee_submit_logs.advance,fee_submit_logs.remaining,
                                invoice.status,invoice.submitted_at,invoice.id as invoice_id,invoice.date,invoice.is_auto,
                                class_name,section_name");
               $this->db->from('invoice');
               $this->db->JOIN('fee_submit_logs','invoice.id=fee_submit_logs.inv_id','left'); 
               $this->db->JOIN('promotion','promotion.id=invoice.student_id');
               $this->db->JOIN('section','promotion.section_id = section.section_id ');
               $this->db->JOIN('class','class.class_id = promotion.class_id');
               $this->db->JOIN('student','student.id=promotion.student_id');
               $this->db->where_in('invoice.student_id',$pro_id_array);
               $this->db->where('invoice.branch_id',$branch);
               $this->db->where_in('invoice.is_delete',0);
               $this->db->order_by('invoice.id','ASC');
$data['student']=$this->db->get()->result_array(); 
	// echo "<pre>";print_r($data['student']);exit;
foreach ($data['student'] as $key => $value) {
if($value['remaining'] == 0 && $value['status'] == 1){$data['student'][$key]['fee_total']=(($value['recieved']+$value['discount']) - ($value['fine'] + $value['advance']));}
elseif($value['remaining'] > 0 && $value['status'] !=0){$data['student'][$key]['fee_total']=(($value['recieved']+$value['discount']+$value['remaining']) - $value['fine']);}
                      else{$data['student'][$key]['fee_total']=$this->voucher_model->countTotalFee($value['invoice_id']);}
                 }

                 $data['base_url'] =  base_url();
                 $data['userInfo'] = $this->userInfo;
                 $this->load->view('printable/Fee_history',$data);
	            }
}
           	
public function create_history_voucher($id)
{
$branch = $this->user_model->getBranch();
$data['menu'] = $this->load_model->menu();
$data['base_url'] = base_url();
$data['userInfo'] = $this->userInfo;
if(!empty($id))
{

$sid =$id;
$data['b_header'] = $this->db->query("SELECT 
                name,title,tagline,short_address,phone_no,email,logo1,logo2 
                from branch where id='$branch' AND is_delete='0'")->row_array();
$data['branch_name']=$data['b_header']['name'];
	//var_dump($grno);die();
$this->db->select("student.student_name,student.id as stid,invoice.student_id,invoice.is_auto,invoice.id,section.section_name,class.class_name,student.sid,promotion.id as pid,student.father_contact,student.father_name,student.student_contact,invoice.fee_pack,invoice.late_fine,branch.name,invoice.id,invoice.date,invoice.date_expire,branch.contact,branch.b_logo,invoice.is_admitted");
$this->db->join("promotion","invoice.student_id=promotion.id");
$this->db->join("student","student.id=promotion.student_id");
$this->db->join("branch","invoice.branch_id=branch.id");
$this->db->join("class","promotion.class_id=class.class_id");
$this->db->join("section","promotion.section_id=section.section_id");
$this->db->where("student.sid",$sid);
$this->db->where("invoice.is_delete",'0');
$this->db->where("student.branch",$branch);
$this->db->order_by("promotion.id","DESC");
$data['detail']= $this->db->get("invoice")->row_array();

// var_dump('<pre>',$data['detail']);
// die();
$pro_id_array=$this->voucher_model->getPromotionArray($data['detail']['pid']);
//echo "<pre>";print_r($pro_id_array);exit;

   
$this->db->select("student.student_name,student.father_name,student.sid,student.father_contact,
                                fee_submit_logs.student_id as s_id,fee_submit_logs.date as f_date,fee_submit_logs.id as flog_id,fee_submit_logs.inv_id,
                                fee_submit_logs.fine as fine,fee_submit_logs.discount as discount,fee_submit_logs.recieved as recieved,
                                fee_submit_logs.advance,fee_submit_logs.remaining,
                                invoice.status,invoice.submitted_at,invoice.id as invoice_id,invoice.date,invoice.is_auto,
                                class_name,section_name");
               $this->db->from('invoice');
               $this->db->JOIN('fee_submit_logs','invoice.id=fee_submit_logs.inv_id','left'); 
               $this->db->JOIN('promotion','promotion.id=invoice.student_id');
               $this->db->JOIN('section','promotion.section_id = section.section_id ');
               $this->db->JOIN('class','class.class_id = promotion.class_id');
               $this->db->JOIN('student','student.id=promotion.student_id');
               $this->db->where_in('invoice.student_id',$pro_id_array);
               $this->db->where('invoice.branch_id',$branch);
               $this->db->where_in('invoice.is_delete',0);
               $this->db->order_by('invoice.id','ASC');
$data['student']=$this->db->get()->result_array();           

// echo "<pre>";print_r($data['student']);exit;
foreach ($data['student'] as $key => $value) {
if($value['remaining'] == 0 && $value['status'] == 1){$data['student'][$key]['fee_total']=(($value['recieved']+$value['discount']) - ($value['fine'] + $value['advance']));}
elseif($value['remaining'] > 0 && $value['status'] !=0){$data['student'][$key]['fee_total']=(($value['recieved']+$value['discount']+$value['remaining']) - $value['fine']);}
                      else{$data['student'][$key]['fee_total']=$this->voucher_model->countTotalFee($value['invoice_id']);}
                 }

                 $data['base_url'] =  base_url();
                 $data['userInfo'] = $this->userInfo;
                 $this->load->view('printable/Fee_history_voucher',$data);
	            }
           	}
	//	}
    //}

//==============================================getBadDebtors=========================================================

	public function getBadDebtors()
	{
		$bad_debtors=$this->voucher_model->getBadDebtors();
		var_dump('<pre>',$bad_debtors);die();
	}
	
//====================================================================================================================	
//==============================================getBadDebtors Amount=========================================================

	public function getBadDebtorsAmount()
	{
		$bad_debtors_amount=$this->voucher_model->getBadDebtorsAmount();
		var_dump('<pre>',$bad_debtors_amount);die();
	}
	
//====================================================================================================================	

	public function check_count_fee()
	{
		$res=$this->voucher_model->countTotalFee("6971");
		//var_dump($res);die();
	}
//==============================================Left student fee clearance=========================================================
	
	public function left_fee_clearance()
	{
		$this->user_model->check_permissions("voucher/left_fee_clearance");
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
		$data['userInfo'] = $this->userInfo;
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('voucher/left_fee_clearance_form',$data);
	}

	public function clear_left_fee()
	{
		$sid=$this->input->post()['sid'];
// 		var_dump($sid);die;
		$branch = $this->user_model->getBranch();
		if(!empty($sid)){
			$this->db->select('student.*,invoice.status,promotion.id as pro_id')
			         ->FROM('student')
			         ->join('promotion','student.id=promotion.student_id')
			         ->join('invoice','promotion.id=invoice.student_id');
			$this->db->where('student.sid',$sid)->where('student.branch',$branch)->where('student.status!=',0)->where('invoice.status',0)->where('promotion.is_active',1)->where('promotion.is_delete',0);
			$student=$this->db->get()->row_array();
// 			echo "<pre>";print_r($student);exit;
			//var_dump($student);die;
			if(!empty($student)) {
			 //   echo "<pre>";print_r($student['pro_id']);exit;
			    $promotion_array=$this->voucher_model->getPromotionArray($student['pro_id']);
			    //echo "<pre>";print_r($promotion_array);exit;
			    $lastv=$this->db->where_in('student_id',$promotion_array)->where('is_delete',0)->order_by('id','DESC')->get('invoice')->row_array();
				//echo "<pre>";print_r($lastv);exit;
			    if(!empty($lastv)) {
					redirect('voucher/view/'.base64_encode(json_encode($lastv['id'].SALT)));
					
				}else{
				    $this->session->set_flashdata('msg', "Record Not Found !");
					redirect('voucher/left_fee_clearance');
				}
			}else{
			    $this->session->set_flashdata('msg', "Record Not Found !");
				redirect('voucher/left_fee_clearance');
			}
		}else{
		    $this->session->set_flashdata('msg', "Record Not Found !");
			redirect('voucher/left_fee_clearance');
		}
	}
	

//=====================================adjust arrears===============================================================

public function arrears_form($succuss='')
      {
		if($succuss=='success') {
			$data['success']=true;
		}else {
			$data['success']=false;
		}
		if($this->user_model->is_super())    
            $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0'")->result_array();
        else
            {$branch=$this->user_model->getbranch();
            $data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->result_array();}
        $this->user_model->check_permissions("Voucher/arrears_form");
        $data['is_super'] = $this->user_model->is_super();
        $data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
        
        //===========================================
        
        //calling views
        $this->load->view('header',$data);
        $this->load->view('sidebar',$data);
        $this->load->view('voucher/arrears_form',$data);

      }

	public function getArrearStudent()
	{
	   // echo "<pre>";print_r($this->input->post());exit;
		$branch=$this->input->post('branch',true);
		$class=$this->input->post('class',true);
		$section=$this->input->post('section',true);
		$for_date=$this->input->post('for_date',true);
		$tag_date=$this->input->post('tag_date',true);
		$arrear=$this->input->post('arrear',true);
		$data['menu'] = $this->load_model->menu();
        $data['base_url'] = base_url();
        $data['userInfo'] = $this->userInfo;
		//var_dump($grno);die();
		$this->db->where('class_id',$class);
		$this->db->where('section_id',$section);
		$this->db->delete('arrears');
		
		foreach($arrear as $key=>$value){
            $array = array(
                'promotion_id'=>$key,    
                'class_id'=>$class,    
                'section_id'=>$section,    
                'amount'=>$value,    
                'add_month'=>date('Y-m-d',strtotime($for_date)),    
                'for_month'=>date('Y-m-d',strtotime($tag_date)),    
                'status'=>($value==0) ? '1':'0',
            );
            $this->db->insert('arrears',$array);
        }
        
    	redirect('Voucher/arrears_form','refresh');
	}

//==================================================================================================================

	public function apply_arrear()
	{
		if($this->input->post()) {
			$data=$this->input->post();
			$promotion_id=$data['promotion_id'];
			//=========================================================================
			$date=date('Y-m');
            $prev_month=date('Y-m',strtotime($date."this month"));
            $this->db->select("*");
            $this->db->from('invoice');
            $this->db->where('student_id',$promotion_id);
            $this->db->where('left(date,7)',$prev_month);
            $this->db->order_by('id','DESC');
            $prev_month_voucher=$this->db->get()->row_array();
			//=========================================================================
			if($prev_month_voucher['status']==0) {
				$arrear=array(
					"remaining"=>$prev_month_voucher['remaining']+$data['arrear'],
					"status"=>1
				);
				$this->db->where('id',$prev_month_voucher['id']);
				$this->db->update('invoice',$arrear);
			}
			else{
				$arrear=array(
					"remaining"=>$prev_month_voucher['remaining']+$data['arrear'],
				);
				$this->db->where('id',$prev_month_voucher['id']);
				$this->db->update('invoice',$arrear);
			}
			redirect(base_url().'Voucher/arrears_form/success','refresh');
		}
	}
//=========================================================================================
	
	

//====================================================================================================================	

}
