<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Studentfee extends Admin_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('smsgateway');
        $this->load->library('mailsmsconf');
    }

    function index() {
        if (!$this->rbac->hasPrivilege('collect_fees', 'can_view')) {
            access_denied();
        }
        $this->session->set_userdata('top_menu', 'Billing Management');
        $this->session->set_userdata('sub_menu', 'studentfee/index');
        $data['title'] = 'Learner Bills';
        $class = $this->class_model->get();
        $data['classlist'] = $class;
        $this->load->view('layout/header', $data);
        $this->load->view('studentfee/studentfeeSearch', $data);
        $this->load->view('layout/footer', $data);
    }

    function pdf() {
        $this->load->helper('pdf_helper');
    }

    function search() {
        if (!$this->rbac->hasPrivilege('collect_fees', 'can_view')) {
            access_denied();
        }
        $data['title'] = 'Learner Search';
        $class = $this->class_model->get();
        $data['classlist'] = $class;
        $button = $this->input->post('search');
        if ($this->input->server('REQUEST_METHOD') == "GET") {
            $this->load->view('layout/header', $data);
            $this->load->view('studentfee/studentfeeSearch', $data);
            $this->load->view('layout/footer', $data);
        } else {
            $class = $this->input->post('class_id');
            $section = $this->input->post('section_id');
            $search = $this->input->post('search');
            $search_text = $this->input->post('search_text');
            if (isset($search)) {
                if ($search == 'search_filter') {
                    $this->form_validation->set_rules('class_id', 'Class', 'trim|required|xss_clean');
                    if ($this->form_validation->run() == FALSE) {
                        
                    } else {
                        $resultlist = $this->student_model->searchByClassSection($class, $section);
                        $data['resultlist'] = $resultlist;
                    }
                } else if ($search == 'search_full') {
                    $resultlist = $this->student_model->searchFullText($search_text);
                    $data['resultlist'] = $resultlist;
                }
                $this->load->view('layout/header', $data);
                $this->load->view('studentfee/studentfeeSearch', $data);
                $this->load->view('layout/footer', $data);
            }
        }
    }

    function feesearch() {
        if (!$this->rbac->hasPrivilege('search_due_fees', 'can_view')) {
            access_denied();
        }

        $this->session->set_userdata('top_menu', 'Billing Management');
        $this->session->set_userdata('sub_menu', 'studentfee/feesearch');
        $data['title'] = 'Learner Bills';
        $class = $this->class_model->get();
        $data['classlist'] = $class;
        $feesessiongroup = $this->feesessiongroup_model->getFeesByGroup();

        $data['feesessiongrouplist'] = $feesessiongroup;
        $this->form_validation->set_rules('feegroup_id', 'Fee Group', 'trim|required|xss_clean');

        $this->form_validation->set_rules('class_id', 'Class', 'trim|required|xss_clean');
        $this->form_validation->set_rules('section_id', 'Section', 'trim|required|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('layout/header', $data);
            $this->load->view('studentfee/studentSearchFee', $data);
            $this->load->view('layout/footer', $data);
        } else {
            $data['student_due_fee'] = array();
            $feegroup_id = $this->input->post('feegroup_id');
            $feegroup = explode("-", $feegroup_id);
            $feegroup_id = $feegroup[0];
            $fee_groups_feetype_id = $feegroup[1];
            $class_id = $this->input->post('class_id');
            $section_id = $this->input->post('section_id');
            $student_due_fee = $this->studentfee_model->getDueStudentFees($feegroup_id, $fee_groups_feetype_id, $class_id, $section_id);
            if (!empty($student_due_fee)) {
                foreach ($student_due_fee as $student_due_fee_key => $student_due_fee_value) {
                    $amt_due = $student_due_fee_value['amount'];
                    $student_due_fee[$student_due_fee_key]['amount_discount'] = 0;
                    $student_due_fee[$student_due_fee_key]['amount_fine'] = 0;
                    $a = json_decode($student_due_fee_value['amount_detail']);
                    if (!empty($a)) {
                        $amount = 0;
                        $amount_discount = 0;
                        $amount_fine = 0;

                        foreach ($a as $a_key => $a_value) {
                            $amount = $amount + $a_value->amount;
                            $amount_discount = $amount_discount + $a_value->amount_discount;
                            $amount_fine = $amount_fine + $a_value->amount_fine;
                        }
                        if ($amt_due <= $amount) {
                            unset($student_due_fee[$student_due_fee_key]);
                        } else {

                            $student_due_fee[$student_due_fee_key]['amount_detail'] = $amount;
                            $student_due_fee[$student_due_fee_key]['amount_discount'] = $amount_discount;
                            $student_due_fee[$student_due_fee_key]['amount_fine'] = $amount_fine;
                        }
                    }
                }
            }


            $data['student_due_fee'] = $student_due_fee;
            $this->load->view('layout/header', $data);
            $this->load->view('studentfee/studentSearchFee', $data);
            $this->load->view('layout/footer', $data);
        }
    }

    function reportbyname() {
        if (!$this->rbac->hasPrivilege('fees_statement', 'can_view')) {
            access_denied();
        }
        $this->session->set_userdata('top_menu', 'Billing Management');
        $this->session->set_userdata('sub_menu', 'studentfee/reportbyname');
        $data['title'] = 'Learner Bills';
        $data['title'] = 'Learner Bills';
        $class = $this->class_model->get();
        $data['classlist'] = $class;
        if ($this->input->server('REQUEST_METHOD') == "GET") {
            $this->load->view('layout/header', $data);
            $this->load->view('studentfee/reportByName', $data);
            $this->load->view('layout/footer', $data);
        } else {
			$date_from = date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date_from')));
			$date_to = date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date_to')));
            $this->form_validation->set_rules('section_id', 'Section', 'trim|required|xss_clean');
            $this->form_validation->set_rules('class_id', 'Class', 'trim|required|xss_clean');
            $this->form_validation->set_rules('student_id', 'Student', 'trim|required|xss_clean');
            if ($this->form_validation->run() == FALSE) {
                $this->load->view('layout/header', $data);
                $this->load->view('studentfee/reportByName', $data);
                $this->load->view('layout/footer', $data);
            } else {
                $data['student_due_fee'] = array();
                $class_id = $this->input->post('class_id');
                $section_id = $this->input->post('section_id');
                $student_id = $this->input->post('student_id');
                $student = $this->student_model->get($student_id);
                $data['student'] = $student;
				
                $student_due_fee = $this->studentfeemaster_model->getStudentFees($student['student_session_id']);
                $student_discount_fee = $this->feediscount_model->getStudentFeesDiscount($student['student_session_id']);
				$feeList = $this->studentfeemaster_model->getFeeBetweenDate($date_from, $date_to);
				$data['feeList'] = $feeList;

                $data['student_discount_fee'] = $student_discount_fee;
                $data['student_due_fee'] = $student_due_fee;
                $data['class_id'] = $class_id;
                $data['section_id'] = $section_id;
                $data['student_id'] = $student_id;
				
				
				
                $category = $this->category_model->get();
                $data['categorylist'] = $category;
				
				
                $this->load->view('layout/header', $data);
                $this->load->view('studentfee/reportByName', $data);
                $this->load->view('layout/footer', $data);
            }
        }
    }

    function reportbyclass() {
        $data['title'] = 'Learner Bills';
        $data['title'] = 'Learner Bills';
        $class = $this->class_model->get();
        $data['classlist'] = $class;
        if ($this->input->server('REQUEST_METHOD') == "GET") {
            $this->load->view('layout/header', $data);
            $this->load->view('studentfee/reportByClass', $data);
            $this->load->view('layout/footer', $data);
        } else {
            $student_fees_array = array();
            $class_id = $this->input->post('class_id');
            $section_id = $this->input->post('section_id');
            $student_result = $this->student_model->searchByClassSection($class_id, $section_id);
            $data['student_due_fee'] = array();
            if (!empty($student_result)) {
                foreach ($student_result as $key => $student) {
                    $student_array = array();
                    $student_array['student_detail'] = $student;
                    $student_session_id = $student['student_session_id'];
                    $student_id = $student['id'];
                    $student_due_fee = $this->studentfee_model->getDueFeeBystudentSection($class_id, $section_id, $student_session_id);
                    $student_array['fee_detail'] = $student_due_fee;
                    $student_fees_array[$student['id']] = $student_array;
                }
            }
            $data['class_id'] = $class_id;
            $data['section_id'] = $section_id;
            $data['student_fees_array'] = $student_fees_array;
            $this->load->view('layout/header', $data);
            $this->load->view('studentfee/reportByClass', $data);
            $this->load->view('layout/footer', $data);
        }
    }

    function view($id) {
        if (!$this->rbac->hasPrivilege('collect_fees', 'can_view')) {
            access_denied();
        }
        $data['title'] = 'Learner Bill List';
        $studentfee = $this->studentfee_model->get($id);
        $data['studentfee'] = $studentfee;
        $this->load->view('layout/header', $data);
        $this->load->view('studentfee/studentfeeShow', $data);
        $this->load->view('layout/footer', $data);
    }

    function deleteFee() {
        if (!$this->rbac->hasPrivilege('collect_fees', 'can_delete')) {
            access_denied();
        }
        $invoice_id = $this->input->post('main_invoice');
        $sub_invoice = $this->input->post('sub_invoice');
        if (!empty($invoice_id)) {
            $this->studentfee_model->remove($invoice_id, $sub_invoice);
        }
        $array = array('status' => 'success', 'result' => 'success');
        echo json_encode($array);
    }

    function deleteStudentDiscount() {

        $discount_id = $this->input->post('discount_id');
        if (!empty($discount_id)) {
            $data = array('id' => $discount_id, 'status' => 'assigned', 'payment_id' => "");
            $this->feediscount_model->updateStudentDiscount($data);
        }
        $array = array('status' => 'success', 'result' => 'success');
        echo json_encode($array);
    }

    function addfee($id) {
        if (!$this->rbac->hasPrivilege('collect_fees', 'can_add')) {
            access_denied();
        }
        $data['title'] = 'Learner Detail';
        $student = $this->student_model->get($id);
        $data['student'] = $student;
		
		$data['payment_methods']=$this->payment_methods_model->select(); 

        $student_due_fee = $this->studentfeemaster_model->getStudentFees($student['student_session_id']);
        $student_discount_fee = $this->feediscount_model->getStudentFeesDiscount($student['student_session_id']);

        $data['student_discount_fee'] = $student_discount_fee;
        $data['student_due_fee'] = $student_due_fee;
        $category = $this->category_model->get();
        $data['categorylist'] = $category;
        $class_section = $this->student_model->getClassSection($student["class_id"]);
        $data["class_section"] = $class_section;
         $session = $this->setting_model->getCurrentSession();
        
        $studentlistbysection = $this->student_model->getStudentClassSection($student["class_id"],$session);
        $data["studentlistbysection"] = $studentlistbysection;
        $this->load->view('layout/header', $data);
        $this->load->view('studentfee/studentAddfee', $data);
        $this->load->view('layout/footer', $data);
    }

    function deleteTransportFee() {
        $id = $this->input->post('feeid');
        $this->studenttransportfee_model->remove($id);
        $array = array('status' => 'success', 'result' => 'success');
        echo json_encode($array);
    }

    function delete($id) {
        $data['title'] = 'Learner Bill List';
        $this->studentfee_model->remove($id);
        redirect('studentfee/index');
    }

    function create() {
        if (!$this->rbac->hasPrivilege('collect_fees', 'can_view')) {
            access_denied();
        }
        $data['title'] = 'Add Learner Bill';
        $this->form_validation->set_rules('category', 'Category', 'trim|required|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('layout/header', $data);
            $this->load->view('studentfee/studentfeeCreate', $data);
            $this->load->view('layout/footer', $data);
        } else {
            $data = array(
                'category' => $this->input->post('category'),
            );
            $this->studentfee_model->add($data);
            $this->session->set_flashdata('msg', '<div studentfee="alert alert-success text-center">Employee added to ssuccessfully</div>');
            redirect('studentfee/index');
        }
    }

    function edit($id) {
        if (!$this->rbac->hasPrivilege('collect_fees', 'can_edit')) {
            access_denied();
        }
        $data['title'] = 'Edit Learner Bill';
        $data['id'] = $id;
        $studentfee = $this->studentfee_model->get($id);
        $data['studentfee'] = $studentfee;
        $this->form_validation->set_rules('category', 'category', 'trim|required|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('layout/header', $data);
            $this->load->view('studentfee/studentfeeEdit', $data);
            $this->load->view('layout/footer', $data);
        } else {
            $data = array(
                'id' => $id,
                'category' => $this->input->post('category'),
            );
            $this->studentfee_model->add($data);
            $this->session->set_flashdata('msg', '<div studentfee="alert alert-success text-center">Employee updated successfully</div>');
            redirect('studentfee/index');
        }
    }

    function addstudentfee() {

        $this->form_validation->set_rules('student_fees_master_id', 'Fee Master', 'required|trim|xss_clean');
        $this->form_validation->set_rules('fee_groups_feetype_id', 'Student', 'required|trim|xss_clean');
        //$this->form_validation->set_rules('amount', 'Amount', 'required|trim|xss_clean|callback_check_deposit');
        $this->form_validation->set_rules('amount', 'Amount', 'required|trim|xss_clean');
        $this->form_validation->set_rules('amount_discount', 'Discount', 'required|trim|xss_clean');
        $this->form_validation->set_rules('amount_fine', 'Fine', 'required|trim|xss_clean');
        $this->form_validation->set_rules('payment_mode', 'Payment Mode', 'required|trim|xss_clean');
				
				//CODE FOR GENERATING RECEIPT NUMBERS AND INSERTING THEM TO THE DATABASE
				$value2='';
				//Query to fetch last inserted invoice number
				$this->db->select('receipt');
				$this->db->from('student_fees_deposite');
				$query1 = $this->db->get();
				$result1 = $query1->num_rows();    // CODE FOR COUNTING NUMBER OF ROWS IN TOTAL
				//$get_result = $query1->row();		//CODE FOR PULLING THE RECEIPT NUMBERS
				
				if($result1 > 0) {
					
						$value2 =$result1;
						//$value2 = substr($value2, 10, 13);//separating numeric part
						$value2 = $value2 + 1;//Incrementing numeric part
						$value2 = "REC" . sprintf('%04s', $value2);//concatenating incremented value
						$value = $value2; 						
				} 
				else {
					$value2 = "REC0001";
					$value = $value2;
									
				}
							
				$receipt_no = $value;
		
        if ($this->form_validation->run() == false) {
            $data = array(
                'amount' => form_error('amount'),
                'student_fees_master_id' => form_error('student_fees_master_id'),
                'fee_groups_feetype_id' => form_error('fee_groups_feetype_id'),
                'amount_discount' => form_error('amount_discount'),
                'amount_fine' => form_error('amount_fine'),
                'payment_mode' => form_error('payment_mode'),
            );
            $array = array('status' => 'fail', 'error' => $data);
            echo json_encode($array);
        } else {
            $collected_by = " Collected By: " . $this->customlib->getAdminSessionUserName();
            $student_fees_discount_id = $this->input->post('student_fees_discount_id');
			
			
				$payment_mode = $this->input->post('payment_mode');
				//Query to fetch last inserted invoice number
				$this->db->select('*');
				$this->db->from('bank_rates');
				$query1 = $this->db->get();
				$result1 = $query1->row();

				$home_currency = $result1->home_currency;
				$foreign_currency = $result1->foreign_currency;
				
				if($payment_mode == $home_currency){


				$this->db->select('*');
				$this->db->from('bank_rates');
				$this->db->where('home_currency',$payment_mode);
				$query1 = $this->db->get();
				$row1_rate = $query1->row();
				
		       // $sql = "SELECT bank_rates.id as bank_rate_id,bank_rates.foreign_currency,bank_rates.home_currency,bank_rates.foreign_rate,bank_rates.home_rate  where foreign_rate =".$payment_mode." order by bank_rate_id asc";
		
		       // $query = $this->db->query($sql); $row1_rate = $query->result();
				
				$home_currency_row1 = $row1_rate->home_currency;
				$home_rate = $row1_rate->home_rate;
				
				$converted_amt = $home_rate*1;
				
				
					$json_array = array(
						'amount' => $converted_amt,
						'date' => date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date'))),
						'amount_discount' => $this->input->post('amount_discount'),
						'amount_fine' => $this->input->post('amount_fine'),
						'description' => $this->input->post('description') . $collected_by,
						'payment_mode' => $this->input->post('payment_mode')
					);
					$data = array(
						'student_fees_master_id' => $this->input->post('student_fees_master_id'),
						'fee_groups_feetype_id' => $this->input->post('fee_groups_feetype_id'),
						'amount_detail' => $json_array,
						'receipt' => $receipt_no
					);

					$send_to = $this->input->post('guardian_phone');
					$email = $this->input->post('guardian_email');

					$student_detail = $this->studentfeemaster_model->getStudentDetailByStudentSession($this->input->post('student_fees_master_id'));
			   
					$inserted_id = $this->studentfeemaster_model->fee_deposit($data, $send_to, $student_fees_discount_id);

					$sender_details = array('invoice' => $inserted_id, 'contact_no' => $send_to, 'email' => $email,'notification_to'=>array('parent_app_key'=>$student_detail->parent_app_key));
					$this->mailsmsconf->mailsms('fee_submission', $sender_details);

					$array = array('status' => 'success', 'error' => '');
					echo json_encode($array);				
				
					
				}
				else{

		      //  $sql2 = "SELECT bank_rates.id as bank_rate_id,bank_rates.foreign_currency,bank_rates.home_currency,bank_rates.foreign_rate,bank_rates.home_rate  where foreign_rate =".$payment_mode." order by bank_rate_id asc";
		
		        //$query2 = $this->db->query($sql2);$row1_rate2 = $query2->result();
				$this->db->select('*');
				$this->db->from('bank_rates');
				$this->db->where('foreign_rate',$payment_mode);
				$query1 = $this->db->get();
				$row1_rate2 = $query1->row();
				
				$foreign_currency_row1 = $row1_rate2->foreign_currency;
				$foreign_rate = $row1_rate2->foreign_rate;
				
				$converted_amt = ($amount/$foreign_rate)*1;	
				
				$json_array = array(
					'amount' => $converted_amt,
					'date' => date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date'))),
					'amount_discount' => $this->input->post('amount_discount'),
					'amount_fine' => $this->input->post('amount_fine'),
					'description' => $this->input->post('description') . $collected_by,
					'payment_mode' => $this->input->post('payment_mode')
				);
				$data = array(
					'student_fees_master_id' => $this->input->post('student_fees_master_id'),
					'fee_groups_feetype_id' => $this->input->post('fee_groups_feetype_id'),
					'amount_detail' => $json_array,
					'receipt' => $receipt_no
				);

				$send_to = $this->input->post('guardian_phone');
				$email = $this->input->post('guardian_email');

				$student_detail = $this->studentfeemaster_model->getStudentDetailByStudentSession($this->input->post('student_fees_master_id'));
		   
				$inserted_id = $this->studentfeemaster_model->fee_deposit($data, $send_to, $student_fees_discount_id);

				$sender_details = array('invoice' => $inserted_id, 'contact_no' => $send_to, 'email' => $email,'notification_to'=>array('parent_app_key'=>$student_detail->parent_app_key));
				$this->mailsmsconf->mailsms('fee_submission', $sender_details);

				$array = array('status' => 'success', 'error' => '');
				echo json_encode($array);
				
			}			
			
        }
    }
   
}

?>