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

class Lnmo extends CI_Controller{
    /*
    | -----------------------------------------------------
    | PRODUCT NAME: 	INILABS SCHOOL MANAGEMENT SYSTEM
    | -----------------------------------------------------
    | AUTHOR:			INILABS TEAM
    | -----------------------------------------------------
    | EMAIL:			info@inilabs.net
    | -----------------------------------------------------
    | COPYRIGHT:		RESERVED BY INILABS IT
    | -----------------------------------------------------
    | WEBSITE:			http://inilabs.net
    | -----------------------------------------------------
    */

    public $table = 'mpesa';

    function __construct () {
        parent::__construct();
        $this->load->database(); 
        $this->load->model("mpesa_m"); 
        $this->load->model('wallet_m');
        $this->load->model('wallettransactions_m'); 
        $this->load->model('student_m');  
        $this->load->model("setting_m");   
        $this->load->model('invoice_m'); 
        $this->load->model('payment_m');
        $this->load->model('studentrelation_m');
        $this->load->model("globalpayment_m");
        $this->load->model("payment_settings_m"); 
        $this->load->library('mpesa_lib'); 
        $this->load->library('sms/sms_panel'); 
        $this->load->library('sms/skooly_init');     

        $api_config = [];
        $get_configs = $this->payment_settings_m->get_order_by_config();
        foreach ($get_configs as $key => $get_key) {
            $api_config[$get_key->config_key] = $get_key->value;
        }       
      
        $status = (int) $api_config['mpesa_status'] ===1;
        $this->mpesa_lib->init(
            array(
                'env'              => $status ? 'live' : 'sandbox',
                'type'             => 4,
                'headoffice'       => $status ? (int) $api_config['mpesa_shortcode'] : 174379,
				'shortcode'        => $status ? (int) $api_config['mpesa_shortcode'] : 174379,
                'key'              => $status ? $api_config['mpesa_key'] : 'wCuX3EjXyc8nhqnbl1vzokfgRJ90eGJt',
                'secret'           => $status ? $api_config['mpesa_secret'] : 'atQhh2GlMyQckT3W',
                'passkey'          => $status ? $api_config['mpesa_password'] : 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919','username'         => 'username',
                'validation_url'   => site_url('lnmo/validate'),
                'confirmation_url' => site_url('lnmo/confirm'),
                'callback_url'     => site_url('lnmo/reconcile'),
                'timeout_url'      => site_url('lnmo/timeout'),
            )
        );

		// header('Access-Control-Allow-Origin: *');       
    }
    
    public function confirm()
    {

        $callbackJSONData = file_get_contents('php://input');
        $callbackData = json_decode($callbackJSONData); 

        try {
            $this->saveRequestToTxt($callbackData);

            $transID = $callbackData->TransID;
            $transTime = $callbackData->TransTime;
            $transAmount = $callbackData->TransAmount;
            $billRefNumber = $callbackData->BillRefNumber;
            $MSISDN = $callbackData->MSISDN;
            $firstName = $callbackData->FirstName;

            $date = DateTime::createFromFormat('YmdHis', $transTime);
            $timestamp = $date->format('Y-m-d h:i:s');
            $array = array(
                'referenceNO' => getTrx(),
                'TransID' => $transID,
                'TransAmount' => $transAmount,
                'BillRefNumber' => $billRefNumber,
                'phone' => $MSISDN,
                'TransTime' => $timestamp,
                'guardian' => $firstName,
                'status' => 1
            );

            $res = $this->mpesa_m->insert_data($array);

            if (strpos($billRefNumber, 'sms') !== false) {
                if(get_setting('auto_recharge') == 1 && $_SERVER['HTTP_HOST'] === get_setting('allowed_url')){
                    $comment = 'add credit via M-PESA recharge with REF: '.$transID;
                    $creditValue = !empty(get_setting('sms_credit_value')) ? get_setting('sms_credit_value') : 0.6;
                    
                    $credits = round($transAmount / $creditValue);
                    $this->sms_panel->updateCredits($billRefNumber, $credits, 'add', $comment);
            
                    echo json_encode(['status' => 'success', 'message' => 'Process completed']);
                }
                
            } else {
                if(allowTransaction()){
                    $studentInfo = $this->student_m->getStudentByAdm($billRefNumber);
                    if(customCompute($studentInfo)){
                        $walletData = $this->wallet_m->getWallet(array('studentID' => $studentInfo[0]->studentID));
                        $studentID =  $studentInfo[0]->studentID;
                        $schoolyearID = $studentInfo[0]->srschoolyearID;
                        
                        if (!$walletData) {
                            $newWalletData = array(
                                'studentID' => $studentInfo[0]->studentID,
                                'balance' => 0,
                                'create_date' => date("Y-m-d H:i:s")
                            );
                            $this->wallet_m->insert_wallet($newWalletData);
                        }
                
                        $walletData = $this->wallet_m->getWallet(array('studentID' => $studentInfo[0]->studentID));
                
                        if ($walletData) {
                            $walletID = $walletData->id;
                            $walletBalance = round(floatval($walletData->balance) + floatval($transAmount));
                
                            $data = array(
                                'balance' => $walletBalance,
                                'modify_date' => date("Y-m-d H:i:s")
                            );
        
                            $this->wallet_m->update_wallet($data, $walletID);
                
                            $updatedWalletData = $this->wallet_m->getWallet(array('studentID' => $studentInfo[0]->studentID));
                
                            $transactionData = array(
                                'studentID' => (int) $studentInfo[0]->studentID,
                                'amount' => $transAmount,
                                'post_balance' => round(floatval($updatedWalletData->balance)),
                                'trx_type' => 'credit',
                                'walletID' => (int) $walletID,
                                'referenceNO' => getTrx(),
                                'payment_type' => 'MPESA',
                                'details' => "Wallet recharge via M-PESA",
                                'create_date' => date("Y-m-d H:i:s")
                            );
        
                            if ($this->db->insert('wallet_transactions', $transactionData)) {
        
                                $walletID = $walletData->id;
                            
                                processStudentPayment($studentInfo[0]->studentID, $walletBalance, 'Wallet');
                            
                                update_fee_balance([$studentInfo[0]->studentID], $schoolyearID);
                                
                                $student = $this->studentrelation_m->general_get_single_student(array('srstudentID' => $studentInfo[0]->studentID), TRUE);
                                SmsService::walletMpesaCredit($student, 3, [], $transAmount); 
                            }        
                            
                        }
                    }
                    
                }                
        
                // if ($amount > 0) {
                //     $balance = $amount;
                // }
            }
        } catch (Exception $ex) {
            error_log($ex->getMessage());
            log_message('error', 'Failed to insert payment: ' . $ex->getMessage());
        }        

        return true;
    }

    public function saveRequestToTxt($request)
    {
        $requestData = is_array($request) || is_object($request) ? print_r($request, true) : $request;
    
        $filePath = FCPATH . 'logs/requests_' . date('Y-m-d') . '.txt';
    
        file_put_contents($filePath, "[" . date('Y-m-d H:i:s') . "]\n" . $requestData . "\n\n", FILE_APPEND);
    }

    public function validate()
    {
        // $callbackJSONData = file_get_contents('php://input');
        // $callbackData = json_decode($callbackJSONData);
        // $transactionType = $callbackData->TransactionType;
        // $transID = $callbackData->TransID;
        // $transTime = $callbackData->TransTime;
        // $transAmount = $callbackData->TransAmount;
        // $businessShortCode = $callbackData->BusinessShortCode;
        // $billRefNumber = $callbackData->BillRefNumber;
        // $invoiceNumber = $callbackData->InvoiceNumber;
        // $orgAccountBalance = $callbackData->OrgAccountBalance;
        // $thirdPartyTransID = $callbackData->ThirdPartyTransID;
        // $MSISDN = $callbackData->MSISDN;
        // $firstName = $callbackData->FirstName;
        // $middleName = $callbackData->MiddleName;
        // $lastName = $callbackData->LastName;

        $array = array(
            'referenceNO' => getTrx(),
            'mpesa_request' => 'Test',
            'mpesa_receipt' => 'test',
            'amount' => 30,
            'status' => 1,
            'payment_type' => 'validate',
            'invoice_no' => '20',
            'phone' => '0714110898',
            'create_date' => date("Y-m-d H:i:s")
        );

        $mpesa_log = $this->mpesa_m->insert_data($array);

        return true;
    }
    
    public function register()
    {    
        $res = $this->mpesa_lib->register();
        dd($res);
        return $res;
    }    

    public function initialize($phone, $amount, $account){
        $response = $this->mpesa_lib->send($phone, round($amount), $account);

        return $response;
    }

}