<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Transaction extends Admin_Controller {
    function __construct() {
        parent::__construct();
    }
     public function searchtransaction()
{
    $this->session->set_userdata('top_menu', 'Reports');
    $this->session->set_userdata('sub_menu', 'transaction/searchtransaction');

    $data['title'] = 'Search Expense';

    // Load dropdown data
    $data['payment_modes'] = $this->payment_methods_model->select();
    $data['classlist']     = $this->class_model->get();

    // Default currency
    $data['currency_symbols'] = $this->customlib->getSchoolCurrencyFormat();

    if ($this->input->server('REQUEST_METHOD') == "POST") {

        $search = $this->input->post('search');

        if ($search == "search_filter") {

            // 🔒 VALIDATION RULES
            $this->form_validation->set_rules('levelfrom', 'Level From', 'required');
            $this->form_validation->set_rules('levelto', 'Level To', 'required');
            $this->form_validation->set_rules('payment_mode', 'Payment_mode', 'required');
            $this->form_validation->set_rules('levelto', 'Level To', 'callback_check_level_range');


            if ($this->form_validation->run() == TRUE) {

                // ✅ GET FORM VALUES
                $payment_mode = $this->input->post('payment_mode');
                $level_from   = $this->input->post('levelfrom');
                $level_to     = $this->input->post('levelto');

                $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')));

                // Title
                $data['exp_title'] = 'Transaction From ' . $this->input->post('date_from') . ' To ' . $this->input->post('date_to');

                if (!empty($payment_mode)) {
                    $data['exp_title'] .= ' with Payment Mode ' . $payment_mode;
                    $data['currency_symbols'] = $payment_mode;
                }

                // 📊 FETCH DATA
                $data['expenseList'] = $this->expense_model->search($payment_mode, $date_from, $date_to);
                $data['incomeList']  = $this->income_model->search($payment_mode, $date_from, $date_to);
                $data['feeList']     = $this->studentfeemaster_model
                    ->getFeeBetweenDateCurrency($date_from, $date_to, $payment_mode, $level_from, $level_to);

                // Retain form values
                $data['date_from2']    = $date_from;
                $data['date_to2']      = $date_to;
                $data['levelfrom2']    = $level_from;
                $data['levelto2']      = $level_to;
                $data['payment_mode2'] = $payment_mode;
            }
        }
    }

    // 🔁 LOAD VIEW ONCE
    $this->load->view('layout/header', $data);
    $this->load->view('admin/transaction/searchtransaction', $data);
    $this->load->view('layout/footer', $data);
}
public function check_level_range($levelto)
{
    $levelfrom = $this->input->post('levelfrom');

    if ($levelto < $levelfrom) {
        $this->form_validation->set_message('check_level_range', 'Level To must be greater than or equal to Level From');
        return FALSE;
    }
    return TRUE;
}


    public function searchfeessummary()
{
    $this->session->set_userdata('top_menu', 'Reports');
    $this->session->set_userdata('sub_menu', 'transaction/searchfeessummary');

    $data['title'] = 'Search Fees Summary';

    // Dropdown data
    $data['classlist'] = $this->class_model->get();

    if ($this->input->server('REQUEST_METHOD') == "POST") {

        $search = $this->input->post('search');
        $data['report_type'] = $this->input->post('report_type') ?? 'summary';

        if ($search == "search_filter") {

            //VALIDATION RULES
            $this->form_validation->set_rules('levelfrom', 'Level From', 'required');
            $this->form_validation->set_rules('levelto', 'Level To', 'required');
            $this->form_validation->set_rules('levelto', 'Level To', 'callback_check_level_range');

            if ($this->form_validation->run() == TRUE) {

                //et values
                $level_from = $this->input->post('levelfrom');
                $level_to   = $this->input->post('levelto');

                $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')));

                // Title
                $data['exp_title'] = 'Total Invoices From ' . $this->input->post('date_from') .
                                     " To " . $this->input->post('date_to');

                //Fetch filtered data WITH LEVELS
                $data['expenseList'] = $this->expense_model->search($date_from, $date_to);
                $data['incomeList']  = $this->income_model->search($date_from, $date_to);
                $data['feeList']     = $this->studentfeemaster_model
                                            ->feesSummary($date_from, $date_to, $level_from, $level_to);

                // Retain form values
                $data['date_from2'] = $date_from;
                $data['date_to2']   = $date_to;
                $data['levelfrom2'] = $level_from;
                $data['levelto2']   = $level_to;
            }
        }
    }

    //Load view once
    $this->load->view('layout/header', $data);
    $this->load->view('admin/transaction/feessummary', $data);
    $this->load->view('layout/footer', $data);
}

    function studentacademicreport() {
        if (!$this->rbac->hasPrivilege('balance_fees_report', 'can_view')) {
            access_denied();
        }
        $this->session->set_userdata('top_menu', 'Fees Collection');
        $this->session->set_userdata('sub_menu', 'transaction/studentacademicreport');
        $data['title'] = 'student fee';
        $data['title'] = 'student fee';
        $class = $this->class_model->get();
        $data['classlist'] = $class;

        if ($this->input->server('REQUEST_METHOD') == "GET") {
            $this->load->view('layout/header', $data);
            $this->load->view('admin/transaction/studentAcademicReport', $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');
				
            if ($this->form_validation->run() == FALSE) {
                $this->load->view('layout/header', $data);
                $this->load->view('admin/transaction/studentAcademicReport', $data);
                $this->load->view('layout/footer', $data);
            } else {
                $class_id = $this->input->post('class_id');
                $section_id = $this->input->post('section_id');
                $feetype = $this->input->post('feetype');
                $feetype_arr = $this->input->post('feetype_arr');
                $student_Array = array();
                $studentlist = $this->student_model->searchByClassSection($class_id, $section_id);
                if (!empty($studentlist)) {
                    foreach ($studentlist as $key => $eachstudent) {
                        $obj = new stdClass();
                        $obj->name = $eachstudent['firstname'] . " " . $eachstudent['lastname'];
                        $obj->class = $eachstudent['class'];
                        $obj->section = $eachstudent['section'];
                        $obj->admission_no = $eachstudent['admission_no'];
                        $obj->roll_no = $eachstudent['roll_no'];
                        $obj->father_name = $eachstudent['father_name'];
                        $obj->student_session_id = $eachstudent['student_session_id'];
                        $student_session_id = $eachstudent['student_session_id'];						

                        //$student_total_fees = $this->studentfeemaster_model->getStudentFees($student_session_id,$date_from, $date_to);
                       $student_total_fees = $this->studentfeemaster_model->getStudentFeeswithDatesBetween($student_session_id,$date_from, $date_to);
					   
					   $feeList = $this->studentfeemaster_model->getFeeBetweenDate($date_from, $date_to);
					   $data['feeList'] = $feeList;

                        if (!empty($feeList)) {
							
                        if (!empty($student_total_fees)) {
                            $totalfee = 0;
                            $deposit = 0;
                            $discount = 0;
                            $balance = 0;
                            $fine = 0;
                            $fee_converted = 0;
                            $fee_paid = 0;

                            foreach ($student_total_fees as $student_total_fees_key => $student_total_fees_value) {

                                if (!empty($student_total_fees_value->fees)) {
                                    foreach ($student_total_fees_value->fees as $each_fee_key => $each_fee_value) {
                                        $totalfee = $totalfee + $each_fee_value->amount;

                                        $amount_detail = json_decode($each_fee_value->amount_detail);
										

                                        if (is_object($amount_detail)) {
                                            foreach ($amount_detail as $amount_detail_key => $amount_detail_value) {

                                                $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;

                                                $payment_mode = $amount_detail_value->payment_mode;
                                                $amount = $amount_detail_value->amount;
                                               
                                                $currency_symbol = $this->customlib->getSchoolCurrencyFormat();
                                                    if($payment_mode==$currency_symbol){
                                                                                                                
                                                            $this->db->select('*');
                                                            $this->db->from('bank_rates');
                                                            $this->db->where('home_currency',$payment_mode);
                                                            $query1 = $this->db->get();
                                                            $row1_rate = $query1->row();
                                                            
                                                            $home_rate = $row1_rate->home_rate;
                                                            
                                                            $fee_converted = $home_rate*$amount;
                                                            
                                                    }
                                                else{
                                                    
                                                            $this->db->select('*');
                                                            $this->db->from('bank_rates');
                                                            $this->db->where('foreign_currency',$payment_mode);
                                                            $query3 = $this->db->get();
                                                            $row1_rate2 = $query3->row();
                                                            
                                                            $foreign_currency_row1 = $row1_rate2->foreign_currency;
                                                            $foreign_rate = $row1_rate2->foreign_rate;
                                                            
                                                            $fee_converted = ($amount/$foreign_rate)*1;	
                                                            
                                                }														
                                                
                                                $deposit = $deposit +$fee_converted;
                                                $fine = $fine + $amount_detail_value->amount_fine;
                                                $discount = $discount + $amount_detail_value->amount_discount;

                                            }
                                        }
                                    }
                                }
                            }

                            $obj->totalfee = $totalfee;
                            $obj->payment_mode = $payment_mode;
                            $obj->deposit = $deposit;
                            $obj->fine = $fine;
                            $obj->discount = $discount;
                            $obj->balance = $totalfee - ($deposit + $discount);
                        } 
						else {
						

						
                            $obj->totalfee = "N/A";
                            $obj->payment_mode = "N/A";
                            $obj->deposit = "N/A";
                            $obj->fine = "N/A";
                            $obj->balance = "N/A";
                            $obj->discount = "N/A";
                        }
                        $student_Array[] = $obj;
						}
                    }
                }


                $data['student_due_fee'] = $student_Array;
				$data['date_from2'] = $date_from2;
				$data['date_to2'] = $date_to;
                // exit();
                $data['class_id'] = $class_id;
                $data['section_id'] = $section_id;
                $data['feetype'] = $feetype;
                $data['feetype_arr'] = $feetype_arr;
                $this->load->view('layout/header', $data);
                $this->load->view('admin/transaction/studentAcademicReport', $data);
                $this->load->view('layout/footer', $data);
            }
        }
    }   
	
	function printBalanceFeesByGroup() {
        if (!$this->rbac->hasPrivilege('balance_fees_report', 'can_view')) {
            access_denied();
        }
		        $setting_result = $this->setting_model->get();
                $data['settinglist'] = $setting_result;
				
        $data['title'] = 'student fee';
        $data['title'] = 'student fee';
        $class = $this->class_model->get();
        $data['classlist'] = $class;	
			
			$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')));

                $class_id = $this->input->post('class_id');
                $section_id = $this->input->post('section_id');
                $feetype = $this->input->post('feetype');
                $feetype_arr = $this->input->post('feetype_arr');
                $student_Array = array();
                $studentlist = $this->student_model->searchByClassSection($class_id, $section_id);
                if (!empty($studentlist)) {
                    foreach ($studentlist as $key => $eachstudent) {
                        $obj = new stdClass();
                        $obj->name = $eachstudent['firstname'] . " " . $eachstudent['lastname'];
                        $obj->class = $eachstudent['class'];
                        $obj->section = $eachstudent['section'];
                        $obj->admission_no = $eachstudent['admission_no'];
                        $obj->roll_no = $eachstudent['roll_no'];
                        $obj->father_name = $eachstudent['father_name'];
                        $obj->student_session_id = $eachstudent['student_session_id'];
                        $student_session_id = $eachstudent['student_session_id'];						

                        //$student_total_fees = $this->studentfeemaster_model->getStudentFees($student_session_id,$date_from, $date_to);
                       $student_total_fees = $this->studentfeemaster_model->getStudentFeeswithDatesBetween($student_session_id,$date_from, $date_to);
					   
					   $feeList = $this->studentfeemaster_model->getFeeBetweenDate($date_from, $date_to);
					   $data['feeList'] = $feeList;

                        if (!empty($feeList)) {
							
                        if (!empty($student_total_fees)) {
                            $totalfee = 0;
                            $deposit = 0;
                            $discount = 0;
                            $balance = 0;
                            $fine = 0;
                            foreach ($student_total_fees as $student_total_fees_key => $student_total_fees_value) {


                                if (!empty($student_total_fees_value->fees)) {
                                    foreach ($student_total_fees_value->fees as $each_fee_key => $each_fee_value) {
                                        $totalfee = $totalfee + $each_fee_value->amount;

                                        $amount_detail = json_decode($each_fee_value->amount_detail);
										
                                        if (is_object($amount_detail)) {
                                            foreach ($amount_detail as $amount_detail_key => $amount_detail_value) {
                                                $deposit = $deposit + $amount_detail_value->amount;
                                                $fine = $fine + $amount_detail_value->amount_fine;
                                                $discount = $discount + $amount_detail_value->amount_discount;
                                            }
                                        }
                                    }
                                }
                            }

                            $obj->totalfee = $totalfee;
                            $obj->payment_mode = "N/A";
                            $obj->deposit = $deposit;
                            $obj->fine = $fine;
                            $obj->discount = $discount;
                            $obj->balance = $totalfee - ($deposit + $discount);
                        } 
						else {
						

						
                            $obj->totalfee = "N/A";
                            $obj->payment_mode = "N/A";
                            $obj->deposit = "N/A";
                            $obj->fine = "N/A";
                            $obj->balance = "N/A";
                            $obj->discount = "N/A";
                        }
                        $student_Array[] = $obj;
						}
                    }
                }


                $data['student_due_fee'] = $student_Array;
				$data['date_from2'] = $date_from;
				$data['date_to2'] = $date_to;
                // exit();
                $data['class_id'] = $class_id;
                $data['section_id'] = $section_id;
                $data['feetype'] = $feetype;
                $data['feetype_arr'] = $feetype_arr;
				
                $this->load->view('print/printBalanceFeesByGroup', $data);
            }
			
    function printTransactions() {


		               $setting_result = $this->setting_model->get();
        $data['settinglist'] = $setting_result;
        
        $data['title'] = 'Search Expense';

        $data['exp_title'] = 'Transaction From ' . $this->input->post('date_from') . " To " . $this->input->post('date_to');
        $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')));
        $expenseList = $this->expense_model->search("", $date_from, $date_to);
        $incomeList = $this->income_model->search("", $date_from, $date_to);
        $feeList = $this->studentfeemaster_model->feesSummary($date_from, $date_to);
        $data['expenseList'] = $expenseList;
        $data['incomeList'] = $incomeList;
        $data['feeList'] = $feeList;
        $data['date_from2'] = $date_from;
        $data['date_to2'] = $date_to;

            $this->load->view('print/printTransactionSum', $data);
    }	
    
   public function printTransactionzz() {
    // Set menu context
    $this->session->set_userdata('top_menu', 'Reports');
    $this->session->set_userdata('sub_menu', 'transaction/searchtransaction');

    // Load settings and payment modes
    $setting_result = $this->setting_model->get();
    $data['settinglist'] = $setting_result;

    // Get the form data
    $payment_mode = $this->input->post('payment_mode');  // Get the selected payment method
    $date_from = date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date_from')));  // Convert date_from
    $date_to = date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date_to')));  // Convert date_to
    $level_from = $this->input->post('levelfrom');
    $level_to = $this->input->post('levelto');
    // Fetchfiltered fee data
   $data['feeList'] = $this->studentfeemaster_model->getFeeBetweenDateCurrency($date_from, $date_to, $payment_mode, $level_from, $level_to);

    // Construct the title based on the provided filters
    $data['exp_title'] = 'Transaction From ' . $this->input->post('date_from') . " To " . $this->input->post('date_to') . "With Payment Meethod" . $this->input->post('payment_mode');

    // Fetch currency symbol
    if (!empty($payment_mode)) {
        $this->db->select('payment_methods');
        $this->db->from('payment_methods');
        $this->db->where('payment_methods', $payment_mode);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            $data['currency_symbols'] = $query->row()->payment_methods;
        } else {
            $data['currency_symbols'] = $this->customlib->getSchoolCurrencyFormat(); // Default to school currency format
        }
    } else {
        $data['currency_symbols'] = $this->customlib->getSchoolCurrencyFormat();
    }

    // Pass filtered data to the view
   
    $data['date_from2'] = $date_from;  // Set the date_from value to retain in the form
    $data['date_to2'] = $date_to;
    $data['levelfrom2'] = $level_from;  // Set the date_from value to retain in the form
    $data['levelto2'] = $level_to;  // Set the date_to value to retain in the form
    $data['payment_mode2'] = $payment_mode;  // Set the selected payment_method to retain in the form

    // Load the print view
    $this->load->view('print/printFeesCollection', $data);
}

    function printTransaction() {


        $setting_result = $this->setting_model->get();
        $data['settinglist'] = $setting_result;
        
        $data['title'] = 'Search Expense';

        $data['exp_title'] = 'Transaction From ' . $this->input->post('date_from') . " To " . $this->input->post('date_to');
        $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')));
        $expenseList = $this->expense_model->search("", $date_from, $date_to);
        $incomeList = $this->income_model->search("", $date_from, $date_to);
        $feeList = $this->studentfeemaster_model->feesSummary($date_from, $date_to);
        $data['expenseList'] = $expenseList;
        $data['incomeList'] = $incomeList;
        $data['feeList'] = $feeList;
        $data['date_from2'] = $date_from;
        $data['date_to2'] = $date_to;

    $this->load->view('print/printTransactionD', $data);
}		


}

?>