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

class Fee extends CI_Controller {

	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('User_model');
		$this->load->model("Voucher_model",'VM');
		//$this->load->model("PersonalExpense_model","PE");
	}

	
public  function array_flatten($array) { 
  if (!is_array($array)) { 
    return false; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $result = array_merge($result, array_flatten($value)); 
    } else { 
      $result = array_merge($result, array($key => $value));
    } 
  } 
  return $result; 
}
    public function invoice()
    {
        
		$branch = $this->User_model->getBranch();
		$data['branch'] = $this->db->query("SELECT * FROM `branch` WHERE `is_delete`='0' AND `id`='$branch'")->result_array();
		$student_id = $this->User_model->userInfo()["student_id"];
		$user_img=@$this->db->select('img,img1,img2,img3,img4')
	                              ->from('student')
	                              ->where('id',$student_id)
	                              ->get()->row_array();
	   //echo "<pre>";print_r($user_img);exit;
	   $data['user_img']=$user_img;
		//echo "<pre>";print_r($student_id);exit;	 
		$promotion_ids = $this->db->query("SELECT promotion.id FROM `promotion` WHERE student_id = $student_id")->result_array();
		$promotion_id = array();
            foreach($promotion_ids as $array) {
                foreach($array as $v) {
                    $promotion_id[] = $v;
                }
            }
		//$promotion_id = explode(",",$promotion_ids);
      	//echo "<pre>";print_r($promotion_id);exit;	 
        $data['invoices'] = $this->VM->get_cadet_invoice($branch, $promotion_id);
        	// echo "<pre>";    
        	// var_dump( $data['invoices']);die();
        	// echo "</pre>"; 
		$data['userInfo'] =  $this->User_model->userInfo("first_name,last_name,username");
        $data['main'] = "fee/voucher_list";
	    $this->load->view('includes/main', $data);
    }    

  
  	public function view($p)
	{
		if(!empty($p))
		{
			$branch = $this->user_model->getBranch();
			$data['base_url'] = base_url();
			$data['userInfo'] = $this->user_model->userInfo();
			$student_id = $this->User_model->userInfo()['student_id'];
		    $user_img=@$this->db->select('img,img1,img2,img3,img4')
	                              ->from('student')
	                              ->where('id',$student_id)
	                              ->get()->row_array();
	   //echo "<pre>";print_r($user_img);exit;
		
	   $data['user_img']=$user_img;
			
// 			$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$p' AND `is_delete`='0'")->result_array()[0];
// 			$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 as p_no,`student`.`id`,`student_name`,`father_name`,`father_contact` FROM `student` INNER JOIN `promotion` ON `promotion`.`student_id`=`student`.`id` WHERE `promotion`.`id`='".$invoice['student_id']."'")->result_array()[0];
// 			$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();

// 			$data['fee_heads'] = $this->VM->invoiceViewArrayAgainstFeeHeads_byinvoice_updated($invoice['student_id'],$invoice['id']);

// 			$data['invoice'] = $invoice;



            $data['invoice']=$invoice = $this->db->query("SELECT * FROM `invoice` WHERE `id`='$p' AND `is_delete`='0'")->result_array()[0];

			$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 as p_no,`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];
			$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->VM->getLastVoucher($invoice['student_id'],$invoice['id']);
 			//echo "<pre>";print_r($lastv[0]);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->VM->countArrears($invoice['id'],$invoice['student_id'],0,$invoice['remaining']);
		         if($data['lastrem'] < 0){
		             $data['lastadv'] = abs($data['lastrem']);
	             }else{
		             $data['lastadv'] = @$this->db->select("sum(advance) as advance")->from("invoice")->where("student_id",$invoice['student_id'])->where('id',$lastv[0]['id'])->where("is_delete","0")->get()->row()->advance;
	             }

		        }
		        else{
    				$data['lastrem'] = $invoice['remaining'];
				}

			//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'];
				}
			}
			
			$this->load->view('includes/header',$data);
			$this->load->view('includes/sidebar',$data);
			$this->load->view('fee/view',$data);
		}else {
			$data['main'] = "fee/voucher_list";
	        $this->load->view('includes/main', $data);
		}
	}
	

   	public function doPrint($id)
	{
		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`.`cadet_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`")->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['total'] =  $invoice['fee_pack'];
			$data['invoice'] = $invoice;
			$this->load->view('printable/voucher',$data);
		}else{
			redirect("home","refresh");
		}
	}




}

/* End of file Fee.php */
/* Location: ./application/controllers/Fee.php */