<?php

class Creditscan extends Admin_Controller
{
    function __construct()
    {
        parent::__construct();

        $this->load->model("student_m");
        $this->load->model("parents_m");
        $this->load->model("sattendance_m");
        $this->load->model("tattendance_m");
        $this->load->model('uattendance_m');
        $this->load->model("teacher_m");
        $this->load->model("grade_m");
        $this->load->model("classes_m");
        $this->load->model("user_m");
        $this->load->model("usertype_m");
        $this->load->model("setting_m");
        $this->load->model('studentrelation_m');
        $this->load->model('leaveapplication_m');

        $this->load->model('frontend_setting_m');
        $this->load->helper('frontenddata');
        $this->load->model('lunch_m');
        $this->load->model('invoice_m');
        $this->load->model('wallet_m');
        $this->load->library('sms/skooly_init');

        $language = $this->session->userdata('lang');
        $this->lang->load('creditscan', $language);
    }


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

        $this->data['date'] = date("d-m-Y");
        $this->data['holidays'] =  $this->getHolidaysSession();
        $this->data['getWeekendDays'] =  $this->getWeekendDaysSession();

        $this->data["subview"] = "wallet/scan";
        $this->load->view('_layout_main', $this->data);
    }

    public function process(){
        if(allowTransaction()){
            try{

                $amount = $this->input->post('amount');
                $paymentMethod = $this->input->post('paymentMethod');
                $qr_token = $this->input->post('qr_token');
                $student = $this->verify_attendance($qr_token);
                $remarks = $this->input->post('remarks');
    
                $this->deposit($amount, $student->srstudentID, $paymentMethod, $remarks);
                $walletData = $this->wallet_m->getWallet(array('studentID' => $student->srstudentID));
    
                echo json_encode(array(
                    "status" => "success",
                    "name" => $student->srname,
                    "class" => $student->srclasses,
                    "section" => $student->srsection,
                    "registerNO" => $student->srregisterNO,
                    "studentID" => $student->srstudentID,
                    "walletBalance" => $walletData->balance
                ));
            } catch(\Exception $e){
                echo json_encode(array(
                    "status" => 'error',
                    "message" => $e->getMessage(),
                ));
            }      
        }else{
            echo json_encode(array(
                "status" => 'error',
                "message" => 'Your SMS balance is low. Kindly recharge.',
            ));
        }
    }
    
    public function deposit($amount, $studentID, $paymentMethod, $remarks){   
        $schoolyearID = $this->session->userdata('defaultschoolyearID');

        $existingWalletQuery = $this->db->get_where('wallets', array('studentID' => $studentID));
        
        if (!$existingWalletQuery->num_rows() > 0) {
            $newWalletData = array(
                'studentID' => $studentID,
                'balance' => 0,
                'create_date' => date("Y-m-d H:i:s")
            );
            $this->db->insert('wallets', $newWalletData);
        }
        $walletData = $this->wallet_m->getWallet(array('studentID' => $studentID));
        $walletID = $walletData->id;
        $walletBalance = round(floatval($walletData->balance) + floatval($amount));
    
        $data = array(
            'balance' => $walletBalance,
            'modify_date' => date("Y-m-d H:i:s")
        );

        $this->wallet_m->update_wallet($data, $walletID);

        
        $username = $this->session->userdata('username');
        $transactionData = array(
            'studentID' => (int) $studentID,
            'amount' => $amount,
            'post_balance' => $walletBalance,
            'trx_type' => 'credit',
            'walletID' => (int) $walletID,
            'referenceNO' => getTrx(),
            'payment_type' => $paymentMethod,
            'details' => "Credit scan by $username",
            'create_date' => date("Y-m-d H:i:s")

        );
        if ($this->db->insert('wallet_transactions', $transactionData)) {
            $studentInfo = $this->studentrelation_m->get_single_student(array('srstudentID' => $studentID), TRUE);
            
            SmsService::scanCredit($studentInfo, 3, $this->data, $amount);

            processStudentPayment($studentID, $walletBalance, $paymentMethod);
            
            update_fee_balance([$studentID],$schoolyearID);
        }
        
    }

    public function verify_attendance($qr_token)
    {

        $data = array();
        $user = array();
        $where = array();
        $qr_data = explode("-",$qr_token);
        $schoolyearID = $this->session->userdata('defaultschoolyearID');

        if(count($qr_data) < 2){
            echo 0;
            exit;
        }

        $user = $this->student_m->get_select_student('*',array(
            'qr_token' => $qr_token
        ))[0];

        $student = $this->studentrelation_m->get_single_studentrelation(array('srstudentID' => $user->studentID, 'srschoolyearID' => $schoolyearID));

        return $student;
    }

}