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


/**
 * Voucher Class
 *
 * @package     Edusol
 * @subpackage  Fee
 * @author      Saqib Sadiq
 * @link        http://facebook.com/saqibsadiq
 */

class Voucher_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }
    
    //Calculate Voucher Total Fee to be Paid on For Due Voucher
    public function countTotalFee($id=0)
    {

        $total = 0;
        if($id!=0)
        {
            $d = $this->db->select("invoice.student_id,invoice.fee_pack,invoice.late_fine,invoice.admin_fee,invoice.is_admitted,invoice.status,invoice.date_expire")
                          ->from("invoice")
                          ->where("invoice.is_delete","0")
                          //->where("invoice.is_auto","0")
                          ->where("invoice.id",$id)
                          ->get()->row();

            $e = $this->db->select("sum(fee_installment.amount) as other_fee")->from("fee_installment")->where("fee_installment.is_delete",'0')->where("invoice",$id)->get()->row();
            $add_months = @$this->db->where('invoice_id',$id)->where('is_delete',0)->get('fee_add_months')->result_array();
            $total += $d->fee_pack;
            $total += $e->other_fee;
            $lastv = @$this->getLastVoucher($d->student_id,$id)[0];
            
            if(date("Y-m-d",strtotime($d->date_expire))<=date("Y-m-d") && $d->status==0)
            {
                if($lastv['advance']>0)
                $total = $total + ((($total-$lastv['advance']) * $d->late_fine) / 100);
                if(!empty($add_months)) {
					foreach ($add_months as $key => $value) {
                        $total+=$value['fee'];
						$total += ($value['fee'] * $d->late_fine) / 100;
					}
				}
            }
            elseif(!empty($add_months)) {
                foreach ($add_months as $key => $value) {
                    $total+=$value['fee'];
                }
            }
            if($d->is_admitted==1)
            {
                $total += $d->admin_fee;
            }
            $total = $this->countArrears($id,$d->student_id,$total);
            // echo "<pre>";print_r($total);exit;
            
            return $total;
        }
    }
    
     public function countTotalFee_history($id=0)
    {

        $total = 0;
        if($id!=0)
        {
            $d = $this->db->select("invoice.student_id,invoice.fee_pack,invoice.late_fine,invoice.admin_fee,invoice.is_admitted,invoice.status,invoice.date_expire")
                          ->from("invoice")
                          ->where("invoice.is_delete","0")
                          ->where("invoice.id",$id)
                          ->get()->row();

            $e = $this->db->select("sum(fee_installment.amount) as other_fee")->from("fee_installment")->where("fee_installment.is_delete",'0')->where("invoice",$id)->get()->row();
            $add_months = @$this->db->where('invoice_id',$id)->where('is_delete',0)->get('fee_add_months')->result_array();
            $total += $d->fee_pack;
            $total += $e->other_fee;
            $lastv = @$this->getLastVoucher($d->student_id,$id)[0];
           // return $total;
            //var_dump($total); 
          /* if(date("Y-m-d",strtotime($d->date_expire))<=date("Y-m-d") && $d->status==0)
            {
               if($lastv['advance']>0)
                $total = $total + ((($total-$lastv['advance']) * $d->late_fine) / 100);
                if(!empty($add_months)) {
					foreach ($add_months as $key => $value) {
                        $total+=$value['fee'];
						$total += ($value['fee'] * $d->late_fine) / 100;
					}
				}
            }
            
            elseif(!empty($add_months)) {
                foreach ($add_months as $key => $value) {
                    $total+=$value['fee'];
                }
            }*/
           /* if($d->is_admitted==1)
            {
                $total += $d->admin_fee;
            }*/
            $total = $this->countArrears_feehead($id,$d->student_id,$total);
            
            
             //echo "<pre>";print_r($total);
             //exit;
            return $total;
            
        }
    }

 public function total_remaining()
    {
        $branch = $this->user_model->getBranch();
        $monthly_fee = array();
        $monthly_value = array();
        //var_dump('<pre>',$yearly_month_array);die();
        $this->db->select('invoice.*');
        $this->db->from('invoice');
        $this->db->join('promotion','invoice.student_id=promotion.id');
        $this->db->join('student','student.id=promotion.student_id');
        $this->db->join('class','class.class_id=promotion.class_id');
        $this->db->join('section','section.section_id=promotion.section_id');//$this->db->where('student.status',0);
        $this->db->where('promotion.is_delete',0);
        $this->db->where('promotion.is_active',1);
        if(!$this->user_model->is_super())
        $this->db->where('invoice.branch_id',$branch);
        $this->db->where('invoice.is_delete',0);
        $this->db->where('invoice.is_auto',0);
        $this->db->where('class.is_delete',0);
        $this->db->where('section.is_delete',0);
        $monthly_fee=$this->db->get()->result_array();
        $monthly_values['total_fee']=0;
        $monthly_values['fee_recieved']=0;
        $monthly_values['fee_remaining']=0;
        $monthly_values['fine']=0;
        $monthly_values['discount']=0;
        $monthly_values['advance']=0;

            foreach ($monthly_fee as $key=>$voucher) {
            // var_dump($selected_month);die();    
            //if($selected_month=='2016-08')
            // var_dump('<pre>',$all_vouchers);
         if($voucher['remaining'] == 0 && $voucher['status'] == 1 && $voucher['recieved'] ==0){$calc_fee=0;}
         elseif($voucher['remaining'] == 0 && $voucher['status'] == 1 && $voucher['recieved'] !=0){$calc_fee=(($voucher['recieved']+$voucher['discount']) - ($voucher['fine']+$voucher['advance']));}
          elseif($voucher['remaining'] > 0 && $voucher['status'] !=0){$calc_fee=(($voucher['recieved']+$voucher['discount']+$voucher['remaining']) - $voucher['fine']);}
          else{$calc_fee=$this->voucher_model->countTotalFee($voucher['id']);}
         
            $monthly_values['total_fee']+=$calc_fee;
            $monthly_values['fee_recieved']+=$voucher['recieved'];
            if($voucher['status'] == 0){
                $monthly_values['fee_remaining']+=$calc_fee;
            }else{
                $monthly_values['fee_remaining']+=$voucher['remaining'];
            }
            $monthly_values['fine']+=$voucher['fine'];                
            $monthly_values['discount']+=$voucher['discount'];                
            $monthly_values['advance']+=$voucher['advance'];
            
            // echo "<pre>";print_r($calc_fee);exit;
        }//end of yealy vouchers foreach
        
        return $monthly_values;
    }
    
 public function countfee_pack($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT SUM(fee_pack) as total
            FROM `invoice` 
            INNER JOIN `promotion` ON `promotion`.`id` = `invoice`.`student_id`
            WHERE `invoice`.`is_delete`='0'
             AND `invoice`.`branch_id`='$branch' 
             and promotion.class_id='$id'
             and promotion.is_active=1
             and promotion.is_delete=0
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;
        //  echo "<pre>";print_r($data);exit;
         
          return $total;
    }  
    public function countactivestudent($id=0,$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
        $total = $this->db->query("SELECT count(student.id)as std
                            FROM `promotion`
                            INNER join class on class.class_id = promotion.class_id
                            INNER join section on section.section_id = promotion.section_id
                            INNER join student on student.id = promotion.student_id
                            where promotion.is_active=1
                            and promotion.is_delete=0
                            and section.is_delete=0
                            and student.is_delete=0
                            and student.status=0
                            and student.branch= '$branch'
                            and promotion.class_id= '$id'
                            and class.is_delete=0")->row()->std;
        
          return $total;
    }
    
    public function countexpected($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $data= $this->db->query("SELECT invoice.id as id,invoice.*
            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 class.class_id=$id
             and promotion.is_active=1
              and invoice.is_auto=0
             and promotion.is_delete=0
             and class.is_delete=0
             and section.is_delete=0
            and student.is_delete=0
            AND LEFT(`invoice`.`date`,7)='$month' ")->result_array();
        // echo "<pre>";print_r($data);

          foreach($data as $value) 
          {
               if($value['remaining'] == 0 && $value['status'] == 1 && $value['recieved'] ==0){$total+=0;}
                elseif($value['remaining'] == 0 && $value['status'] == 1 && $value['recieved'] !=0){$total +=(($value['recieved']+$value['discount']) - ($value['fine']+$value['advance']));}
              elseif($value['remaining'] > 0 && $value['status'] !=0){$total +=(($value['recieved']+$value['discount']+$value['remaining']) - $value['fine']);}
              else{$total +=$this->voucher_model->countTotalFee($value['id']);}
          }
          return $total;
    }  
    public function countdefult($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
       
         //var_dump($month);die;
        $data =$this->db->query("SELECT distinct `invoice`.`student_id` as inv
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`
WHERE `invoice`.`is_delete`='0' 
AND `invoice`.`branch_id`='$branch'
and  `invoice`.`status`='0' 
and `class`.`class_id`=$id
and `promotion`.`is_active`='1'
and `promotion`.`is_delete`='0'
 
AND LEFT(`invoice`.`date`,7)='$month' ");
//var_dump($data);die;

 return $data->num_rows();
    }
    public function countpartial($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
         //var_dump($month);die;
        $data =$this->db->query("SELECT distinct `invoice`.`student_id` as inv
                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`
                WHERE `invoice`.`is_delete`='0' 
                AND `invoice`.`branch_id`='$branch'
                and  `invoice`.`status`='1' 
                and  `invoice`.`remaining`>'0' 
                and `class`.`class_id`=$id
                and `promotion`.`is_active`='1'
                and `promotion`.`is_delete`='0'
                 
                AND LEFT(`invoice`.`date`,7)='$month' ");
//var_dump($data);die;

 return $data->num_rows();
    }
     public function count_amount_defult($id=0,$month='',$branch) 
    { 
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        //echo "<pre>";print_r($month);exit;
        $total=0;
        
           $data= $this->db->query("SELECT invoice.id as id 
            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  `invoice`.`status`='0' 
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            and `class`.`is_delete`='0'
            and `section`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->result_array();


        foreach($data as $value) 
      {
            $total =$total +$this->voucher_model->countTotalFee($value['id']);
      }
      return $total;
  }
     public function count_amount_partial($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $data= $this->db->query("SELECT invoice.id as id,invoice.recieved,invoice.discount,invoice.remaining,invoice.fine  
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
            and  `invoice`.`status`='1'
            and  `invoice`.`is_auto`='0' 
            and  `invoice`.`remaining`>'0' 
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->result_array();

      //echo "<pre>";print_r($month);
      foreach($data as $value) 
      {
            $total += (($value['recieved']+$value['discount']+$value['remaining']) - $value['fine']);
            // $total =$total +$this->voucher_model->countTotalFee($value['id']);
      }
      return $total;
  }
    public function count_received_partial($id=0,$month='',$branch) 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT sum(invoice.recieved) as total 
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
           and  `invoice`.`status`='1' 
           and  `invoice`.`is_auto`='0' 
          and  `invoice`.`remaining`>'0' 
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;

      
      return $total;
  }
    public function count_remaining_partial($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT sum(invoice.remaining) as total 
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
           and  `invoice`.`status`='1' 
           and  `invoice`.`is_auto`='0' 
and  `invoice`.`remaining`>'0' 
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;

      
      return $total;
  }
    public function count_fine_partial($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT sum(invoice.fine) as total 
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
           and  `invoice`.`status`='1' 
            and  `invoice`.`is_auto`='0' 
and  `invoice`.`remaining`>'0' 
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;

      
      return $total;
  }
    public function count_discount_partial($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT sum(invoice.discount) as total 
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
           and  `invoice`.`status`='1' 
           and  `invoice`.`is_auto`='0' 
and  `invoice`.`remaining`>'0' 
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;

      
      return $total;
  }

    public function re_countdefult($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
         
         
        $data =$this->db->query("SELECT distinct `invoice`.`student_id` as inv
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`
WHERE `invoice`.`is_delete`='0' 
AND `invoice`.`branch_id`='$branch' 
and invoice.status=1
and invoice.remaining=0
and class.class_id=$id
and promotion.is_active=1
and promotion.is_delete=0
AND LEFT(`invoice`.`date`,7)='$month' ");

 return $data->num_rows();
    }
     public function re_count_amount_defult($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT sum(invoice.recieved) as total 
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
            and invoice.status=1
            and invoice.is_auto=0
            and invoice.remaining=0
            and class.class_id=$id
            and promotion.is_active=1
            and promotion.is_delete=0
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;

      return $total;
  }
  public function count_fine_paid($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT sum(invoice.fine) as total 
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
            and invoice.status=1
            and invoice.is_auto=1
            and invoice.remaining=0
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;

      
      return $total;
  }
    public function count_discount_paid($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT sum(invoice.discount) as total 
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
           and invoice.status=1
           and invoice.is_auto=0
            and invoice.remaining=0 
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;

      
      return $total;
  }
  
    public function count_advance($id=0,$month='',$branch='') 
    {
        if(empty($branch))
        $branch =$this->report_model->getBranch()[0]['id'];
        else
        $branch = $branch;
        $total=0;
        
           $total= $this->db->query("SELECT sum(invoice.advance) as total 
            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`
            WHERE `invoice`.`is_delete`='0' 
            AND `invoice`.`branch_id`='$branch' 
           and invoice.status=1
            and invoice.remaining=0 
            and `class`.`class_id`=$id
            and `promotion`.`is_active`='1'
            and `promotion`.`is_delete`='0'
            AND LEFT(`invoice`.`date`,7)='$month' ")->row()->total;

      
      return $total;
  }

    
    public function getLastVoucher($pro_id,$inv_id)
    {
        //=================>getting all promotion id array of current voucher============================
            
        $student_id_actual=$this->db->select('student_id')->where('id',$pro_id)->get('promotion')->row_array()['student_id'];
        $promotion_id_assoc_array=$this->db->select('id')->where('student_id',$student_id_actual)->get('promotion')->result_array();
        if(!empty($promotion_id_assoc_array)) {
        	foreach ($promotion_id_assoc_array as $key => $value) {
	        $promotion_id_array[]=$value['id'];
	        }
        }
        else {
        	$promotion_id_array[]=$pro_id;
        }
        //var_dump($promotion_id_array);die();
        
        //=================>end of getting promotion id array logic============================
        
        return @$this->db->select('*')->where_in('invoice.student_id',$promotion_id_array)->where('invoice.id<',$inv_id)->where('invoice.is_delete',0)->order_by('invoice.id','DESC')->get('invoice')->result_array();
    }

    public function countTotalFee_WithoutArears_WithoutOtherFee($id=0)
    {
        $total = 0;
        if($id!=0)
        {
            $d = $this->db->select("invoice.student_id,invoice.fee_pack,invoice.late_fine,invoice.admin_fee,invoice.is_admitted,invoice.status,invoice.date_expire")->from("invoice")->where("invoice.is_delete","0")->where("invoice.id",$id)->get()->row();
            $total += $d->fee_pack;
            if(date("Y-m-d",strtotime($d->date_expire))<=date("Y-m-d") && $d->status==0)
            {
                $total = $total + (($total * $d->late_fine) / 100);;
            }
            if($d->is_admitted==1)
            {
                $total += $d->admin_fee;
            }
            return $total;
        }
    }

    public function countTotalFee_WithoutOtherFee($id=0)
    {
        $total = 0;
        if($id!=0)
        {
            $d = $this->db->select("invoice.student_id,invoice.fee_pack,invoice.late_fine,invoice.admin_fee,invoice.is_admitted,invoice.status,invoice.date_expire")->from("invoice")->where("invoice.is_delete","0")->where("invoice.id",$id)->get()->row();
            $total += $d->fee_pack;
            if(date("Y-m-d",strtotime($d->date_expire))<=date("Y-m-d") && $d->status==0)
            {
                $total = $total + (($total * $d->late_fine) / 100);
            }
            if($d->is_admitted==1)
            {
                $total += $d->admin_fee;
            }
            $total = $this->countArrears($id,$d->student_id,$total);
            return $total;
        }
    }

    public function getArrearsAmount($id=0,$std_id=0)
    {
        $total=0;
        $lastv = $this->db->query("SELECT `id`,`student_id`,`is_admitted`,`admin_fee`,`status`,`advance`,`remaining`,`late_fine`,`fee_pack` FROM  `invoice` WHERE `id` <>  '$id' AND  `student_id` =  '".$std_id."' AND  `id` <  '".$id."' AND is_delete='0'  ORDER BY  `id` DESC ")->row();
        if($lastv)
        {
            if($lastv->status==1)
            {
                $data['lastadv'] = $lastv->advance;
                $data['lastrem'] = $lastv->remaining;
            }else{
                $lastv_items = $this->db->select("sum(amount) as sum")->from("fee_installment")->where("invoice",$lastv->id)->where("is_delete","0")->get()->row();
                $calc_total = $lastv->fee_pack + $lastv_items->sum;
                $calc = $calc_total + (($calc_total * $lastv->late_fine) / 100);
                if($lastv->is_admitted==1) {
                    $calc+=$lastv->admin_fee;
                }
                $data['lastadv'] = 0;
                $data['lastrem'] = $calc;
            }
        $total -= $data['lastadv'];
        $total += $data['lastrem'];
        }
        return $total;
    }

    public function countArrears($id=0,$std_id=0,$total=0)
    {
        //$lastv = $this->db->query("SELECT `id`,`status`,`advance`,`remaining`,`late_fine`,`fee_pack` FROM  `invoice` WHERE  `student_id` =  '".$std_id."' AND  `id` <  '".$id."' AND is_delete='0'  ORDER BY  `id` DESC ")->result_array();
        $current = $this->db->query("SELECT * FROM  `invoice` WHERE  `id` =  '".$id."' AND is_delete='0'")->row();
        // echo "<pre>";print_r($id);
        //=================>getting all promotion id array of current voucher============================
        
        $student_id_actual=$this->db->select('student_id')->where('id',$std_id)->get('promotion')->row_array()['student_id'];
        $promotion_id_assoc_array=$this->db->select('id')->where('student_id',$student_id_actual)->get('promotion')->result_array();
        
        foreach ($promotion_id_assoc_array as $key => $value) {
	    $promotion_id_array[]=$value['id'];
	    }
        //var_dump($promotion_id_array);die();
        
        //=================>end of getting promotion id array logic============================
        
        $lastv = @$this->db->select('*')->where_in('invoice.student_id',$promotion_id_array)->where('invoice.id<',$id)->where('invoice.is_delete',0)->order_by('invoice.id','DESC')->get('invoice')->result_array();
        //echo "Hello";echo "<pre>";print_r($lastv);exit;
        $data['lastadv'] = 0;
	    $data['lastrem'] = 0;
        if(empty($lastv) && $current->status == 0){
            // echo "A";exit;
        $data['lastadv'] = $current->advance;
		$data['lastrem'] = $current->remaining;
		$total -= $data['lastadv'];
		$total += $data['lastrem'];    
        }
        elseif(empty($lastv) && $current->status == 1){
        $data['lastrem'] = ($current->remaining + $current->recieved + $current->discount) - $total;
		//echo "<pre>";print_r($data['lastrem']);exit;
		$total -= $data['lastadv'];
		$total += $data['lastrem'];    
        }
        elseif($lastv && $lastv[0]['status']==1)
        { 
	    $data['lastadv'] = $lastv[0]['advance'];
// 		$data['lastrem'] = 0;
		$data['lastrem'] = $lastv[0]['remaining']+$current->remaining;
// 		echo "<pre>";print_r($data['lastrem']);exit;
        $total -= $data['lastadv'];
		$total += $data['lastrem'];
        }
        elseif($lastv && $lastv[0]['status']==0)
        {
            
            $inv_remain = $this->db->select('remaining')->where('id',$id)->get('invoice')->row()->remaining;
            $total +=$inv_remain;
            // echo $total;exit;
	    $i=0;
	    while(isset($lastv[$i]['status']) && $lastv[$i]['status']!=1 && $current->status !=1) {
	    	//var_dump($lastv[$i]['id']);
	                $lastv_items = $this->db->select("sum(amount) as sum")->from("fee_installment")->where("invoice",$lastv[$i]['id'])->where("is_delete","0")->get()->row();
	                $calc_total = $lastv[$i]['fee_pack'] + $lastv_items->sum;
	                $calc = $calc_total;// $calc_total + (($calc_total * $lastv[$i]['late_fine']) / 100);
	               // echo $calc;exit;
	                if($lastv[$i]['is_admitted']==1){
	                  $calc += $lastv[$i]['admin_fee'];
	                }
                    $last_add_months=@$this->db->where('invoice_id',$lastv[$i]['id'])->where('is_delete',0)->get('fee_add_months')->result_array();
                    foreach ($last_add_months as $key => $value) {
                        $calc+=$value['fee'];
						//$calc += ($value['fee'] * $lastv[$i]['late_fine']) / 100;
                    }
	                
	                $data['lastadv'] = 0;
	                $data['lastrem'] += $calc;
		        $total -= $data['lastadv'];
		        $total += $calc;
		        $data['lastadv'] = $lastv[$i]['advance'];
    			$data['lastrem'] = $lastv[$i]['remaining'];
    			
    			$total -= $data['lastadv'];
    			$total += $data['lastrem'];
		        $i++;
		      //  var_dump($total);
		        //var_dump($data['lastrem']);
	        }
	        //var_dump("hello");
	        //die();
	        //last paid voucher
	    if(isset($lastv[$i]['status']) && $lastv[$i]['status']==1){
	    		//var_dump($lastv[$i]['status']);die();
		    $data['lastadv'] = $lastv[$i]['advance'];
			$data['lastrem'] = $lastv[$i]['remaining'];
			
			$total -= $data['lastadv'];
			$total += $data['lastrem'];
		}
// 		 var_dump($total);die();
		 //end last paid voucher
	        //echo "end while";die();
        }
        return $total;
    }
    
     public function countArrears_feehead($id=0,$std_id=0,$total=0)
    {
        //$lastv = $this->db->query("SELECT `id`,`status`,`advance`,`remaining`,`late_fine`,`fee_pack` FROM  `invoice` WHERE  `student_id` =  '".$std_id."' AND  `id` <  '".$id."' AND is_delete='0'  ORDER BY  `id` DESC ")->result_array();
        $current = $this->db->query("SELECT * FROM  `invoice` WHERE  `id` =  '".$id."' AND is_delete='0'")->row();
        // echo "<pre>";print_r($id);
        //=================>getting all promotion id array of current voucher============================
        
        $student_id_actual=$this->db->select('student_id')->where('id',$std_id)->get('promotion')->row_array()['student_id'];
        $promotion_id_assoc_array=$this->db->select('id')->where('student_id',$student_id_actual)->get('promotion')->result_array();
        
        foreach ($promotion_id_assoc_array as $key => $value) {
	    $promotion_id_array[]=$value['id'];
	}
        //var_dump($promotion_id_array);die();
        
        //=================>end of getting promotion id array logic============================
        
        $lastv = @$this->db->select('*')->where_in('invoice.student_id',$promotion_id_array)->where('invoice.id<',$id)->where('invoice.is_delete',0)->order_by('invoice.id','DESC')->get('invoice')->result_array();
        //echo "Hello";echo "<pre>";print_r($lastv);exit;
        $data['lastadv'] = 0;
	    $data['lastrem'] = 0;
        if(empty($lastv) && $current->status == 0){
            // echo "A";exit;
        $data['lastadv'] = $current->advance;
		$data['lastrem'] = $current->remaining;
		$total -= $data['lastadv'];
		$total += $data['lastrem'];    
        }
        elseif(empty($lastv) && $current->status == 1){
        $data['lastrem'] = ($current->remaining + $current->recieved + $current->discount) - $total;
		//echo "<pre>";print_r($data['lastrem']);exit;
		$total -= $data['lastadv'];
		$total += $data['lastrem'];    
        }
        elseif($lastv && $lastv[0]['status']==1)
        { 
	    $data['lastadv'] = 0;
// 		$data['lastrem'] = 0;
		$data['lastrem'] = $lastv[0]['remaining']+$current->remaining;
// 		echo "<pre>";print_r($data['lastrem']);exit;
        $total -= $data['lastadv'];
		$total += $data['lastrem'];
        }
        elseif($lastv && $lastv[0]['status']==0)
        {
            
            $inv_remain = $this->db->select('remaining')->where('id',$id)->get('invoice')->row()->remaining;
            $total +=$inv_remain;
            // echo $total;exit;
	    $i=0;
	    while(isset($lastv[$i]['status']) && $lastv[$i]['status']!=1 && $current->status !=1) {
	    	//var_dump($lastv[$i]['id']);
	                $lastv_items = $this->db->select("sum(amount) as sum")->from("fee_installment")->where("invoice",$lastv[$i]['id'])->where("is_delete","0")->get()->row();
	                $calc_total = $lastv[$i]['fee_pack'] + $lastv_items->sum;
	                $calc = $calc_total;// $calc_total + (($calc_total * $lastv[$i]['late_fine']) / 100);
	               // echo $calc;exit;
	                if($lastv[$i]['is_admitted']==1){
	                  $calc += $lastv[$i]['admin_fee'];
	                }
                    $last_add_months=@$this->db->where('invoice_id',$lastv[$i]['id'])->where('is_delete',0)->get('fee_add_months')->result_array();
                    foreach ($last_add_months as $key => $value) {
                        $calc+=$value['fee'];
						//$calc += ($value['fee'] * $lastv[$i]['late_fine']) / 100;
                    }
	                
	                $data['lastadv'] = 0;
	                $data['lastrem'] += $calc;
		        $total -= $data['lastadv'];
		        $total += $calc;
		        $data['lastadv'] = $lastv[$i]['advance'];
    			$data['lastrem'] = $lastv[$i]['remaining'];
    			
    			$total -= $data['lastadv'];
    			$total += $data['lastrem'];
		        $i++;
		      //  var_dump($total);
		        //var_dump($data['lastrem']);
	        }
	        //var_dump("hello");
	        //die();
	        //last paid voucher
	    if(isset($lastv[$i]['status']) && $lastv[$i]['status']==1){
	    		//var_dump($lastv[$i]['status']);die();
		    $data['lastadv'] = $lastv[$i]['advance'];
			$data['lastrem'] = $lastv[$i]['remaining'];
			
			$total -= $data['lastadv'];
			$total += $data['lastrem'];
		}
// 		 var_dump($total);die();
		 //end last paid voucher
	        //echo "end while";die();
        }
        return $total;
    }

    public function getDiscountedFee($promotion_id='',$fee_pack='')
    {
       if($promotion_id!='' && $fee_pack!='') {
            $this->db->select('student.grno,student.student_name,student.disc_type,student.disc_value');
            $this->db->join('student','promotion.student_id=student.id');
            $this->db->where('promotion.id',$promotion_id);
            $discount=$this->db->get('promotion')->row_array();
            if(!empty($discount['disc_type'])) {
            if($discount['disc_type']=="percentage")
                {
                    $disc = ($fee_pack * $discount['disc_value']) / 100;
                    $fee_pack = $fee_pack - $disc;
                }elseif($discount['disc_type']=="rupees")
                {
                    $fee_pack = $fee_pack - $discount['disc_value'];
                }
            }
            return $fee_pack;
       }
    }

//===========================================Fee History===============================
    public function fee_history($month=0,$id=0)
    {
        $mnth=date("Y-m",strtotime($month));
        //var_dump($mnth);die();
        $fromDate = date("Y-m", strtotime("-1 months",strtotime($month)));
        //var_dump($fromDate);die();
        $this->db->select("*");
        $this->db->from("invoice");
        $this->db->where("invoice.student_id",$id);
        $this->db->where("LEFT(invoice.date,7)",$fromDate);
        $previous_voucher=@$this->db->get()->result_array()[0];
        //var_dump($previous_voucher);
        if(empty($previous_voucher))
        {

               return false;
        }
        else
        {      
            if($previous_voucher['status']==1) 
            {
                if($previous_voucher['remaining']!=0)
                {
                    return $previous_voucher['remaining'];
                }
                else
                {
                    return 0;
                }
            }
           
            
            elseif($previous_voucher['status']==0) 
            {
                $fine=($previous_voucher['fee_pack']*$previous_voucher['late_fine'])/100;
                return $arrear=$previous_voucher['fee_pack']+$fine;
            }
        }
    }
//===============================other fee calculations==================================

public function total_other_fee($invoice_id=0)
    {
        $this->db->select("*");
        $this->db->from("fee_installment");
        $this->db->where("invoice",$invoice_id);
        $this->db->where("is_delete",0);
        $other_fee=$this->db->get()->result_array();
        $total_other_fee=0;
        //var_dump($other_fee);
            if(!empty($other_fee))
            {
                foreach ($other_fee as $key => $value) {
                    $total_other_fee+=$value['amount'];
                }
                return $total_other_fee;
            }
            else
            {
                return 0;
            }
    }

public function other_fee($invoice_id=0)
    {
        $this->db->select("*");
        $this->db->from("fee_installment");
        $this->db->where("invoice",$invoice_id);
        $this->db->where("is_delete",0);
        $other_fee=$this->db->get()->result_array();
        //var_dump($other_fee);
            if(!empty($other_fee))
            {
                return $other_fee;
            }
            else
            {
                return false;
            }
    }

    public function getBadDebtors()
    {
       $this->db->select('promotion.id as promotion_id,student.id as student_id,student.student_name,student.status');
       $this->db->join('promotion','promotion.student_id=student.id');
       $this->db->where('student.status!=',0);
       $this->db->where('student.branch',$this->user_model->getBranch());
       $non_active_students= $this->db->get('student')->result_array();

       foreach ($non_active_students as $key=> $selected_student) {
           $this->db->select('*');
           $this->db->where('student_id',$selected_student['promotion_id']);
           $this->db->where('is_delete',0);
           $this->db->order_by('id','DESC');
           $non_active_students[$key]['vouchers']=$this->db->get('invoice')->row_array();
       }
       

    //if u want to revert back to old query delele order_by clause and change row_array to result_array from above query

       foreach ($non_active_students as $key => $selected_student) {
           if(empty($selected_student['vouchers']))
                unset($non_active_students[$key]);
           if($this->getRemainingAmount($selected_student['vouchers']['id'])<=0)
           	unset($non_active_students[$key]);
       }

       /*foreach ($non_active_students as $key => $selected_student) {
           $total_vouchers_of_selected_student=count($selected_student['vouchers']);
           $start_deleteting=false;
           for ($i=$total_vouchers_of_selected_student-1; $i>=0 ; $i--) {
               if($selected_student['vouchers'][$i]['status']==1)
               $start_deleteting=true;
               if($start_deleteting==true)
               unset($selected_student['vouchers'][$i]);
           }
       }*/

       return $non_active_students; 

    }
    
    
    public function getBadDebtorss($s_date='0',$e_date='0')
    {
       $this->db->select('promotion.id as promotion_id,student.id as student_id,student.student_name,student.status');
       $this->db->join('promotion','promotion.student_id=student.id');
       $this->db->where('student.status!=',0);
       $this->db->where('student.branch',$this->user_model->getBranch());
       $non_active_students= $this->db->get('student')->result_array();

       foreach ($non_active_students as $key=> $selected_student) {
           $this->db->select('*');
           $this->db->where('student_id',$selected_student['promotion_id']);
           $this->db->where('is_delete',0);
           $this->db->where('date>=',$s_date);
           $this->db->where('date<=',$e_date);
           $this->db->order_by('id','DESC');
           $non_active_students[$key]['vouchers']=$this->db->get('invoice')->row_array();
       }
       

    //if u want to revert back to old query delele order_by clause and change row_array to result_array from above query

       foreach ($non_active_students as $key => $selected_student) {
           if(empty($selected_student['vouchers']))
                unset($non_active_students[$key]);
           if($this->getRemainingAmount($selected_student['vouchers']['id'])<=0)
           	unset($non_active_students[$key]);
       }

       /*foreach ($non_active_students as $key => $selected_student) {
           $total_vouchers_of_selected_student=count($selected_student['vouchers']);
           $start_deleteting=false;
           for ($i=$total_vouchers_of_selected_student-1; $i>=0 ; $i--) {
               if($selected_student['vouchers'][$i]['status']==1)
               $start_deleteting=true;
               if($start_deleteting==true)
               unset($selected_student['vouchers'][$i]);
           }
       }*/

       return $non_active_students; 

    }

    //old logic changed for multi_month vouchers
    
    public function getRemainingAmount($id='')
    {   
        $voucher=$this->db->where('id',$id)->where('is_delete',0)->get('invoice')->row_array();
        if($voucher){
        	if($voucher['status']==1)
        	    return $voucher['remaining'];
        	else{
        	    return $this->countTotalFee($id);
        	}
        }
    }
    
    public function getBadDebtorsAmount()
    {   
        $bad_debtors_amount=0;
        $BadDebtors=$this->getBadDebtors();
        //var_dump('<pre>',$BadDebtors);die;
        foreach ($BadDebtors as $selectedBadDebtors) {   
                $bad_debtors_amount+=$this->getRemainingAmount($selectedBadDebtors['vouchers']['id']);
        }
        return ceil($bad_debtors_amount);
    }

     /* public function getBadDebtorsAmount()
     {   $bad_debtors_amount=0;
         $BadDebtors=$this->getBadDebtors();
        foreach ($BadDebtors as $selectedBadDebtors) {
            $bad_debtors_amount+=$this->countTotalFee($selectedBadDebtors['vouchers']['id']);
        }
         return $bad_debtors_amount;
     }*/
    
    public function getVoucherContactNumber($id='')
    {
        if($id!='') {
            return $this->db->select('student.id,student.student_name,student.father_contact,class.class_name')
                            ->join('promotion','invoice.student_id=promotion.id')
                            ->join('student','student.id=promotion.student_id')
                            ->join('class','class.class_id=promotion.class_id')
                            ->where('invoice.id',$id)
                            ->get('invoice')->row_array();
        }
    }
    
    public function getPromotionArray($pro_id='')
    {
	//=================>getting all promotion id array of current voucher============================
            
        $student_id_actual=$this->db->select('student_id')->where('id',$pro_id)->get('promotion')->row_array()['student_id'];
        $promotion_id_assoc_array=$this->db->select('id')->where('student_id',$student_id_actual)->get('promotion')->result_array();
        if(!empty($promotion_id_assoc_array)) {
        	foreach ($promotion_id_assoc_array as $key => $value) {
	        $promotion_id_array[]=$value['id'];
	        }
        }
        else {
        	$promotion_id_array[]=$pro_id;
        }
        //var_dump($promotion_id_array);die();
        
        //=================>end of getting promotion id array logic============================
        return $promotion_id_array;
    }
  
   public function monthlyReceving()
    {
        $branch = $this->user_model->getBranch();
        $month=date('Y-m');
        $monthly_fee = array();
        $monthly_value = array();
        //var_dump('<pre>',$yearly_month_array);die();
        $this->db->select('invoice.*');
        $this->db->from('invoice');
        $this->db->join('promotion','invoice.student_id=promotion.id');
        $this->db->join('student','student.id=promotion.student_id');
        $this->db->join('class','class.class_id=promotion.class_id');
        $this->db->join('section','section.section_id=promotion.section_id');//$this->db->where('student.status',0);
        $this->db->where('promotion.is_delete',0);
        $this->db->where('promotion.is_active',1);
        $this->db->where('left(invoice.date,7)',$month);
        if(!$this->user_model->is_super())
        $this->db->where('invoice.branch_id',$branch);
        $this->db->where('invoice.is_delete',0);
       $this->db->where('invoice.fee_deposit_type !=','');
        $this->db->where('class.is_delete',0);
        $this->db->where('section.is_delete',0);
        $monthly_fee=$this->db->get()->result_array();
        $monthly_values['total_fee']=0;
        $monthly_values['fee_recieved']=0;
        $monthly_values['fee_remaining']=0;
        $monthly_values['fine']=0;
        $monthly_values['discount']=0;
        $monthly_values['advance']=0;

            foreach ($monthly_fee as $key=>$voucher) {
            // var_dump($selected_month);die();    
            //if($selected_month=='2016-08')
            // var_dump('<pre>',$all_vouchers);
         if($voucher['remaining'] == 0 && $voucher['status'] == 1 && $voucher['recieved'] ==0){$calc_fee=0;}
         elseif($voucher['remaining'] == 0 && $voucher['status'] == 1 && $voucher['recieved'] !=0){$calc_fee=(($voucher['recieved']+$voucher['discount']) - ($voucher['fine']+$voucher['advance']));}
          elseif($voucher['remaining'] > 0 && $voucher['status'] !=0){$calc_fee=(($voucher['recieved']+$voucher['discount']+$voucher['remaining']) - $voucher['fine']);}
          else{$calc_fee=$this->voucher_model->countTotalFee($voucher['id']);}
         
            $monthly_values['total_fee']+=$calc_fee;
            $monthly_values['fee_recieved']+=$voucher['recieved'];
            if($voucher['status'] == 0){
                $monthly_values['fee_remaining']+=$calc_fee;
            }else{
                $monthly_values['fee_remaining']+=$voucher['remaining'];
            }
            $monthly_values['fine']+=$voucher['fine'];                
            $monthly_values['discount']+=$voucher['discount'];                
            $monthly_values['advance']+=$voucher['advance'];
            
            // echo "<pre>";print_r($calc_fee);exit;
        }//end of yealy vouchers foreach
        
        return $monthly_values;
    }  
    public function monthlyRemaining($branch = NULL)
    {
        
        $month=date('Y-m');
        $monthly_fee = array();
        $monthly_value = array();
        //var_dump('<pre>',$yearly_month_array);die();
        $this->db->select('invoice.*');
        $this->db->from('invoice');
        $this->db->join('promotion','invoice.student_id=promotion.id');
        $this->db->join('student','student.id=promotion.student_id');
        $this->db->join('class','class.class_id=promotion.class_id');
        $this->db->join('section','section.section_id=promotion.section_id');//$this->db->where('student.status',0);
        $this->db->where('promotion.is_delete',0);
        $this->db->where('promotion.is_active',1);
        $this->db->where('left(invoice.date,7)',$month);
        if($branch){
            $this->db->where_in('invoice.branch_id',$branch);
        }
        else{
            if(!$this->user_model->is_super()){
                // $branch = $this->user_model->getAllBranches();
                $branch = $this->user_model->getBranch();
                $this->db->where_in('invoice.branch_id',$branch);
            }
            else{
                // $branch = $this->user_model->getBranch();
                $branch = $this->user_model->getAllBranches();
            }
        }
        $this->db->where('invoice.is_delete',0);
        $this->db->where('invoice.is_auto',0);
        $this->db->where('class.is_delete',0);
        $this->db->where('section.is_delete',0);
        $monthly_fee=$this->db->get()->result_array();
        $monthly_values['total_fee']=0;
        $monthly_values['fee_recieved']=0;
        $monthly_values['fee_remaining']=0;
        $monthly_values['fine']=0;
        $monthly_values['discount']=0;
        $monthly_values['advance']=0;

            foreach ($monthly_fee as $key=>$voucher) {
            // var_dump($selected_month);die();    
            //if($selected_month=='2016-08')
            // var_dump('<pre>',$all_vouchers);
         if($voucher['remaining'] == 0 && $voucher['status'] == 1 && $voucher['recieved'] ==0){$calc_fee=0;}
         elseif($voucher['remaining'] == 0 && $voucher['status'] == 1 && $voucher['recieved'] !=0){$calc_fee=(($voucher['recieved']+$voucher['discount']) - ($voucher['fine']+$voucher['advance']));}
          elseif($voucher['remaining'] > 0 && $voucher['status'] !=0){$calc_fee=(($voucher['recieved']+$voucher['discount']+$voucher['remaining']) - $voucher['fine']);}
          else{$calc_fee=$this->voucher_model->countTotalFee($voucher['id']);}
         
            $monthly_values['total_fee']+=$calc_fee;
            $monthly_values['fee_recieved']+=$voucher['recieved'];
            if($voucher['status'] == 0){
                $monthly_values['fee_remaining']+=$calc_fee;
            }else{
                $monthly_values['fee_remaining']+=$voucher['remaining'];
            }
            $monthly_values['fine']+=$voucher['fine'];                
            $monthly_values['discount']+=$voucher['discount'];                
            $monthly_values['advance']+=$voucher['advance'];
            
            // echo "<pre>";print_r($calc_fee);exit;
        }//end of yealy vouchers foreach
        
        return $monthly_values;
    }
    
    public function LastmonthlyRemaining($branch = NULL)
    {
        // $branch = $this->user_model->getBranch();
        $month=date('Y-m',strtotime("-1 month"));;
        $monthly_fee = array();
        $monthly_value = array();
        //var_dump('<pre>',$yearly_month_array);die();
        $this->db->select('invoice.*');
        $this->db->from('invoice');
        $this->db->join('promotion','invoice.student_id=promotion.id');
        $this->db->join('student','student.id=promotion.student_id');
        $this->db->join('class','class.class_id=promotion.class_id');
        $this->db->join('section','section.section_id=promotion.section_id');//$this->db->where('student.status',0);
        $this->db->where('promotion.is_delete',0);
        $this->db->where('promotion.is_active',1);
        $this->db->where('left(invoice.date,7)',$month);
        if($branch){
            $this->db->where_in('invoice.branch_id',$branch);
        }
        else{
            if(!$this->user_model->is_super()){
                $branch = $this->user_model->getAllBranches();
                $this->db->where_in('invoice.branch_id',$branch);
            }
            else{
                $branch = $this->user_model->getBranch();
                $branch = $this->user_model->getAllBranches();
            }
        }
        $this->db->where('invoice.is_delete',0);
        $this->db->where('invoice.is_auto',0);
        $this->db->where('class.is_delete',0);
        $this->db->where('section.is_delete',0);
        $monthly_fee=$this->db->get()->result_array();
        $monthly_values['total_fee']=0;
        $monthly_values['fee_recieved']=0;
        $monthly_values['fee_remaining']=0;
        $monthly_values['fine']=0;
        $monthly_values['discount']=0;
        $monthly_values['advance']=0;

            foreach ($monthly_fee as $key=>$voucher) {
            // var_dump($selected_month);die();    
            //if($selected_month=='2016-08')
            // var_dump('<pre>',$all_vouchers);
         if($voucher['remaining'] == 0 && $voucher['status'] == 1 && $voucher['recieved'] ==0){$calc_fee=0;}
         elseif($voucher['remaining'] == 0 && $voucher['status'] == 1 && $voucher['recieved'] !=0){$calc_fee=(($voucher['recieved']+$voucher['discount']) - ($voucher['fine']+$voucher['advance']));}
          elseif($voucher['remaining'] > 0 && $voucher['status'] !=0){$calc_fee=(($voucher['recieved']+$voucher['discount']+$voucher['remaining']) - $voucher['fine']);}
          else{$calc_fee=$this->voucher_model->countTotalFee($voucher['id']);}
         
            $monthly_values['total_fee']+=$calc_fee;
            $monthly_values['fee_recieved']+=$voucher['recieved'];
            if($voucher['status'] == 0){
                $monthly_values['fee_remaining']+=$calc_fee;
            }else{
                $monthly_values['fee_remaining']+=$voucher['remaining'];
            }
            $monthly_values['fine']+=$voucher['fine'];                
            $monthly_values['discount']+=$voucher['discount'];                
            $monthly_values['advance']+=$voucher['advance'];
            
            // echo "<pre>";print_r($calc_fee);exit;
        }//end of yealy vouchers foreach
        
        return $monthly_values;
    }
    

}

