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

class Wallet extends Admin_Controller {
/*
| -----------------------------------------------------
| PRODUCT NAME: 	INILABS SCHOOL MANAGEMENT SYSTEM
| -----------------------------------------------------
| AUTHOR:			INILABS TEAM
| -----------------------------------------------------
| EMAIL:			info@inilabs.net
| -----------------------------------------------------
| COPYRIGHT:		RESERVED BY INILABS IT
| -----------------------------------------------------
| WEBSITE:			http://inilabs.net
| -----------------------------------------------------
*/
	function __construct() {
        parent::__construct();
        $this->load->model('student_m');
        $this->load->model('wallet_m');
        $this->load->model('wallettransactions_m');
        $this->load->model('studentrelation_m');
        $this->load->model("setting_m");
        $this->load->model("grade_m");
        $language = $this->session->userdata('lang');
		$this->lang->load('wallet', $language);

    }

    public function index() { 
        
        $this->data['headerassets'] = array(
            'css' => array(
                'assets/datepicker/datepicker.css',
            ),
            'js' => array(
                'assets/datepicker/datepicker.js',
            )
        );

        $filter = array(
            // 'wallet_transactions.create_date>=' => date('Y-m-d 00:00:00'),
            // 'wallet_transactions.create_date<=' => date('Y-m-d 23:59:59'),
        );
        
        if ($_GET) {
            if($this->input->get('start_date') || $this->input->get('end_date')){
                $filter['wallet_transactions.create_date>='] = $this->input->get('start_date') . ' ' . '00:00:00';
                $filter['wallet_transactions.create_date<='] = $this->input->get('end_date') . ' ' . '23:59:59';
            }

            if ($this->input->get('paymentMethod')) {
                $filter['wallet_transactions.payment_type'] = $this->input->get('paymentMethod');
            }
        
            if ($this->input->get('transactionType')) {
                $filter['wallet_transactions.trx_type'] = $this->input->get('transactionType');
            }
        }        

        $this->data["logs"] = $this->wallettransactions_m->getData($filter);
        $this->data['chartData'] = $this->pieChart();
        $this->data['columnData'] = $this->columnChart();
        $this->data['get_all_holidays'] = $this->getHolidaysSession();
		$this->data["subview"] = "wallet/log";
		$this->load->view('_layout_main', $this->data);
	}

    public function columnChart(){
        $columnData = [];
        $today = strtotime("today");
        
        for ($i = 0; $i < 7; $i++) {
            $date = strtotime("-$i days", $today);
            $day = date('Y-m-d', $date);
            $columnData[$day] = 0;
        }
        
        foreach ($this->data['logs'] as $log) {
            $dateTimestamp = strtotime($log->create_date);
            
            if ($dateTimestamp >= $today - 6 * 24 * 60 * 60 && $dateTimestamp <= $today + 24 * 60 * 60) {
                $day = date('Y-m-d', $dateTimestamp);
        
                $columnData[$day] += (int) $log->amount;
            }
        }

        ksort($columnData);
        return $columnData;
    }    

    public function pieChart(){
        $paymentMethodTypes = [];
        foreach ($this->data["logs"] as $log) {
            $paymentType = $log->payment_type;
            if (!isset($paymentMethodTypes[$paymentType])) {
                $paymentMethodTypes[$paymentType] = 0;
            }
            $paymentMethodTypes[$paymentType]++;
        }

        $pieChartData = [];
        foreach ($paymentMethodTypes as $paymentType => $count) {
            $pieChartData[] = [
                'paymentType' => $paymentType,
                'count' => $count
            ];
        }

        return $pieChartData;

    }

    public function view(){

        $this->data['headerassets'] = array(
            'css' => array(
                'assets/custom-scrollbar/jquery.mCustomScrollbar.css'
            ),
            'js' => array(
                'assets/custom-scrollbar/jquery.mCustomScrollbar.concat.min.js'
            )
        ); 
        $schoolyearID = $this->session->userdata('defaultschoolyearID');
        $id = htmlentities(escapeString($this->uri->segment(3)));

        $this->data["logs"] = $this->wallettransactions_m->getTrx($id);
        $this->data["wallet"] = $this->wallet_m->getBalance(array('studentID' => $id));
        $this->data["last_transaction"] = $this->wallettransactions_m->getLastTrx($id);
        $this->data['total_invoices'] = $this->wallettransactions_m->totalInvoices($id);
        $this->data['sales_balance'] = getStudentProductSaleBalance(array('schoolyearID'=>$schoolyearID, 'studentID'=> $id));
        $this->data['student'] = $this->studentrelation_m->get_single_student(array('srstudentID' => $id, 'srschoolyearID' => $schoolyearID));
        $this->data["subview"] = "wallet/index";
        $this->load->view('_layout_main', $this->data);
    }

    
    public function deposit() {
        try {
            if(allowTransaction()){
                $schoolyearID = $this->session->userdata('defaultschoolyearID');
                $amount = $this->input->post('amount');
                $studentID = $this->input->post('studentID');
                $paymentMethod = $this->input->post('paymentMethod');
    
                // Validate input
                if (empty($amount) || !is_numeric($amount)) {
                    $this->session->set_flashdata('error', 'Please enter a valid deposit amount.');
                    redirect($_SERVER['HTTP_REFERER']);
                    return;
                }
    
                $amount = floatval($amount);
                
                // Validate that amount is positive
                if ($amount <= 0) {
                    $this->session->set_flashdata('error', 'Deposit amount must be greater than zero.');
                    redirect($_SERVER['HTTP_REFERER']);
                    return;
                }
    
                // Check if amount has more than 2 decimal places
                if (round($amount, 2) != $amount) {
                    $this->session->set_flashdata('error', 'Deposit amount can only have up to 2 decimal places.');
                    redirect($_SERVER['HTTP_REFERER']);
                    return;
                }
    
                // Validate payment method
                if (empty($paymentMethod)) {
                    $this->session->set_flashdata('error', 'Please select a payment method.');
                    redirect($_SERVER['HTTP_REFERER']);
                    return;
                }
    
                // Validate student exists
                $studentExists = $this->studentrelation_m->get_single_student(array('srstudentID' => $studentID, 'srschoolyearID' => $schoolyearID));
                if (!$studentExists) {
                    $this->session->set_flashdata('error', 'Student not found.');
                    redirect($_SERVER['HTTP_REFERER']);
                    return;
                }
    
                $existingWalletQuery = $this->db->get_where('wallets', array('studentID' => $studentID));
                
                if (!$existingWalletQuery->num_rows() > 0) {
                    // Create wallet with zero balance if it doesn't exist
                    $newWalletData = array(
                        'studentID' => $studentID,
                        'balance' => 0,
                        'create_date' => date("Y-m-d H:i:s")
                    );
                    $this->db->insert('wallets', $newWalletData);
                    $walletData = (object)['balance' => 0, 'id' => $this->db->insert_id()];
                } else {
                    $walletData = $this->wallet_m->getWallet(array('studentID' => $studentID));
                }
    
                $walletID = $walletData->id;
                $newBalance = round(floatval($walletData->balance) + $amount, 2);
                
                // Start transaction for data consistency
                $this->db->trans_start();
                
                $data = array(
                    'balance' => $newBalance,
                    'modify_date' => date("Y-m-d H:i:s")
                );
    
                $this->wallet_m->update_wallet($data, $walletID);
            
                // Get user name and role
                $userName = $this->session->userdata('name');
                $userType = $this->usertype_m->get_single_usertype(array('usertypeID' => $this->session->userdata('usertypeID')))->usertype;
                
                $transactionData = array(
                    'studentID' => (int) $studentID,
                    'amount' => $amount,
                    'post_balance' => $newBalance,
                    'trx_type' => 'credit',
                    'trx_action' => 'Deposit',
                    'trx_action_type' => 'Manual',
                    'walletID' => (int) $walletID,
                    'payment_type' => ucfirst($paymentMethod),
                    'schoolyearID' => $schoolyearID,
                    'referenceNO' => getTrx(),
                    'details' => "Wallet Deposit of KES " . number_format($amount, 2) . " via " . ucfirst($paymentMethod) . " by $userName ($userType)",
                    'create_date' => date("Y-m-d H:i:s")
                );
                
                $this->db->insert('wallet_transactions', $transactionData);
                
                // Complete transaction
                $this->db->trans_complete();
                
                if ($this->db->trans_status() === FALSE) {
                    $this->session->set_flashdata('error', 'Transaction failed. Please try again.');
                    redirect($_SERVER['HTTP_REFERER']);
                    return;
                }
    
                $studentInfo = $this->studentrelation_m->get_single_student(array('srstudentID' => $studentID, 'srschoolyearID' => $schoolyearID), TRUE);
    
                if(update_fee_balance([$studentID], $schoolyearID)){
                    SmsService::walletDeposit($studentInfo, 3, $this->data, $amount);     
        
                    // Process auto payments if applicable
                    processStudentPayment($studentID, $newBalance, $paymentMethod);
                }
    
                $this->session->set_flashdata('success', 'Deposit processed successfully. KES ' . number_format($amount, 2) . ' has been added to the wallet.');
                redirect(base_url("wallet/view/".$studentID));
            } else {
                $this->session->set_flashdata('error', 'Your SMS balance is low. Kindly recharge.');
                redirect($_SERVER['HTTP_REFERER']);
            }
           
        } catch(Exception $e) {
            error_log('Deposit Error: ' . $e->getMessage());
            $this->session->set_flashdata('error', 'An unexpected error occurred. Please try again.');
            redirect($_SERVER['HTTP_REFERER']);
        }       
    }

    public function withdraw() {
        if(allowTransaction()){
            $amount = $this->input->post('amount');
            $studentID = $this->input->post('studentID');
            $schoolyearID = $this->session->userdata('defaultschoolyearID');
    
            // Validate input
            if (empty($amount) || !is_numeric($amount)) {
                $this->session->set_flashdata('error', 'Please enter a valid withdrawal amount.');
                redirect($_SERVER['HTTP_REFERER']);
                return;
            }
    
            $amount = floatval($amount);
            
            // Validate that amount is positive
            if ($amount <= 0) {
                $this->session->set_flashdata('error', 'Withdrawal amount must be greater than zero.');
                redirect($_SERVER['HTTP_REFERER']);
                return;
            }
    
            // Check if amount has more than 2 decimal places
            if (round($amount, 2) != $amount) {
                $this->session->set_flashdata('error', 'Withdrawal amount can only have up to 2 decimal places.');
                redirect($_SERVER['HTTP_REFERER']);
                return;
            }
    
            $existingWalletQuery = $this->db->get_where('wallets', array('studentID' => $studentID));
            
            if (!$existingWalletQuery->num_rows() > 0) {
                // Create wallet with zero balance if it doesn't exist
                $newWalletData = array(
                    'studentID' => $studentID,
                    'balance' => 0,
                    'create_date' => date("Y-m-d H:i:s")
                );
                $this->db->insert('wallets', $newWalletData);
                $walletData = (object)['balance' => 0, 'id' => $this->db->insert_id()];
            } else {
                $walletData = $this->wallet_m->getWallet(array('studentID' => $studentID));
            }
    
            // Validate that withdrawal amount doesn't exceed current balance
            if ($amount > floatval($walletData->balance)) {
                $formattedBalance = number_format($walletData->balance, 2);
                $this->session->set_flashdata('error', "Insufficient balance. You cannot withdraw more than your current balance of KES $formattedBalance");
                redirect($_SERVER['HTTP_REFERER']);
                return;
            }
    
            $walletID = $walletData->id;
            $newBalance = round(floatval($walletData->balance) - $amount, 2);
            
            $data = array(
                'balance' => $newBalance,
                'modify_date' => date("Y-m-d H:i:s")
            );
    
            // Start transaction for data consistency
            $this->db->trans_start();
            
            $this->wallet_m->update_wallet($data, $walletID);
        
            // Get user name and role
            $userName = $this->session->userdata('name');
            $userType = $this->usertype_m->get_single_usertype(array('usertypeID' => $this->session->userdata('usertypeID')))->usertype;
    
            $transactionData = array(
                'studentID' => (int) $studentID,
                'amount' => $amount,
                'post_balance' => $newBalance,
                'trx_type' => 'debit',
                'trx_action' => 'Withdraw',
                'trx_action_type' => 'Manual',
                'walletID' => (int) $walletID,
                'payment_type' => 'Withdrawal',
                'schoolyearID' => $schoolyearID,
                'referenceNO' => getTrx(),
                'details' => "Wallet Withdrawal of KES " . number_format($amount, 2) . " by $userName ($userType)",
                'create_date' => date("Y-m-d H:i:s")
            );
            
            $this->db->insert('wallet_transactions', $transactionData);
            
            // Complete transaction
            $this->db->trans_complete();
            
            if ($this->db->trans_status() === FALSE) {
                $this->session->set_flashdata('error', 'Transaction failed. Please try again.');
                redirect($_SERVER['HTTP_REFERER']);
                return;
            }
    
            $studentInfo = $this->studentrelation_m->get_single_student(array('srstudentID' => $studentID, 'srschoolyearID' => $schoolyearID), TRUE);
    
            update_fee_balance([$studentID],$schoolyearID);
            SmsService::walletWithdraw($studentInfo, 3, $this->data, $amount);      
            $this->session->set_flashdata('success', 'Withdrawal processed successfully. KES ' . number_format($amount, 2) . ' has been deducted from your wallet.');
            redirect(base_url("wallet/view/".$studentID));          
        }else{
            $this->session->set_flashdata('error', 'Your SMS balance is low. Kindly recharge.');
            redirect($_SERVER['HTTP_REFERER']);    
        }
    }
    public function createWallets() {
        
        $students = $this->db->get('student')->result_array();       
        
        foreach ($students as $student) {
            
            $existingWallet = $this->wallet_m->getWallet(array('studentID' => $student['studentID']));
            
            if (empty($existingWallet)) {
              
                $newWalletData = array(
                    'studentID' => $student['studentID'],
                    'balance' => 0,
                    'create_date' => date("Y-m-d H:i:s")
                );
                $this->db->insert('wallets', $newWalletData);
            } else {
                continue;
            }
            
        }
        echo 'done';
        
    }
}