<?php

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

require APPPATH . '/libraries/REST_Controller.php';

/*
 * Changes:
 * 1. This project contains .htaccess file for windows machine.
 *    Please update as per your requirements.
 *    Samples (Win/Linux): http://stackoverflow.com/questions/28525870/removing-index-php-from-url-in-codeigniter-on-mandriva
 *
 * 2. Change 'encryption_key' in application\config\config.php
 *    Link for encryption_key: http://jeffreybarke.net/tools/codeigniter-encryption-key-generator/
 * 
 * 3. Change 'jwt_key' in application\config\jwt.php
 *
 */

class iobpay extends REST_Controller
{
    /**
     * URL: http://localhost/CodeIgniter-JWT-Sample/auth/token
     * Method: GET
     */

     function __construct()
    {
        // Construct the parent class
        parent::__construct();
        $this->load->model('user_management_model');
        $this->load->helper('IOBPAY_UTILITY');
       
    }

    
    public function generateIOBPayToken_post()
    {
        $records = $this->post('records');
       

            $merchant_id = $this->config->item('merchant_id');
            $merchant_sub_id = $this->config->item('merchant_sub_id');
            $sign_key = $this->config->item('sign_key');
            $encryption_key = hash('sha256',$this->config->item('encryption_key'),true);
            $encryption_iv = $this->config->item('encryption_iv');
            $token_generation_url = $this->config->item('token_generation_url');
            $txn_initiation_url = $this->config->item('txn_initiate_url');
            $feetype = "ALL FEES";
            
            $merchantreplyurl = $this->config->item('merchant_reply_url'); # merchant reply url to be replaced here
            $totalamt = $records['total_amount'];

            $merchanttxnid = ""; 
            $user_id = $records['user_id'];
            //get User Name and User MObile no by user ID
            $user_details = $this->user_management_model->selectCustomRecords(array('name','mobile'),array('id' => $user_id),CSR_USER);  
           // print_r($user_details);
            $con_id = $records['con_id'];
            $udf1 = $records['udf1']; 
            $udf2 = count($user_details) &&  $user_details[0]['name']  ? $user_details[0]['name'] : 'NONE';
            $udf3 = count($user_details) && $user_details[0]['mobile'] ? $user_details[0]['mobile'] : 'NONE'; 
            //print_r($udf2);die();   

           //echo $encryption_key.$encryption_iv.$sign_key,$merchant_id.$merchant_sub_id.$token_generation_url.$totalamt.$feetype.$merchantreplyurl;
          
         // die();
            $decodedData = IOBPAY_UTILITY::generateToken($encryption_key,$encryption_iv,$sign_key,$merchant_id,$merchant_sub_id,$token_generation_url,$totalamt,$feetype,$merchantreplyurl);

            $tokenId = $decodedData->tokenid; //ensure to save in db
            
            if($tokenId != NULL)
            {

                     $merchanttxnid = $this->user_management_model->saveRecords(array('amount' => $totalamt,'udf1' => $udf1,'udf2' => $udf2,'udf3' => $udf3,'user_id' => $user_id,'con_id' => $con_id,'token' => $tokenId),CSR_TXN_DETAILS);

                    if($merchanttxnid)
                    { 
                       // $merchanttxnid = $merchanttxnid[0]['merchanttxnid'];

                        $txninitfinalString = IOBPAY_UTILITY::initiateTxn($encryption_key,$encryption_iv,$sign_key,$merchant_id,$merchant_sub_id,$txn_initiation_url,$tokenId,$merchanttxnid,$udf1,$udf2,$udf3,$totalamt,$feetype);

                        if($txninitfinalString)
                        {
                            $updated = $this->user_management_model->updateRecords(array('txn_ini_string' => $txninitfinalString),CSR_TXN_DETAILS,array('merchant_txn_id' => $merchanttxnid));
                            if($updated)
                            {
                                    $data['dataStatus'] = true;
                                    $data['status'] = REST_Controller::HTTP_OK;
                                    $data['records'] = array('url' => $txn_initiation_url,'txn_ini_string' => $txninitfinalString,'merchanttxnid' => $merchanttxnid);
                                    $this->response($data,REST_Controller::HTTP_OK);
                            }
                            else
                            {
                                     $log_message = "### txninit final json not updated in DB";
                                     log_message('ERROR',$log_message);
                                     $data['dataStatus'] = false;
                                     $data['status'] = REST_Controller::HTTP_NOT_MODIFIED;
                                     $data['msg'] = 'Something went wrong, Try later!';
                                     $this->response($data,REST_Controller::HTTP_OK);
                            } 
                        }
                        else
                        {
                                $log_message = "### txninit final json  error: ";
                                log_message('ERROR',$log_message);
                                $data['dataStatus'] = false;
                                $data['status'] = REST_Controller::HTTP_NOT_MODIFIED;
                                $data['msg'] = 'Something went wrong, Try later!';
                                $this->response($data,REST_Controller::HTTP_OK);
                        }
                    }
                    else
                    {
                                $log_message = "### merchanttxnid not generated ";
                                log_message('ERROR',$log_message);
                                $data['dataStatus'] = false;
                                $data['status'] = REST_Controller::HTTP_NOT_MODIFIED;
                                $data['msg'] = 'Something went wrong, Try later!';
                                $this->response($data,REST_Controller::HTTP_OK);
                    }

                    
            }
            else
            {
                                $log_message = "### Token Not generated ";
                                log_message('ERROR',$log_message);
                                $data['dataStatus'] = false;
                                $data['status'] = REST_Controller::HTTP_NOT_MODIFIED;
                                $data['msg'] = 'Something went wrong, Try later!';
                                $this->response($data,REST_Controller::HTTP_OK);
            }
        
    }


    
    public function receiveIOBPAYResponse_post()
    {
  
         log_message('ERROR',$_SERVER['HTTP_ORIGIN']);
        if($_SERVER['HTTP_ORIGIN'] == $this->config->item('referer_url'))
        {    
            $merchant_id = $this->config->item('merchant_id');
            $merchant_sub_id = $this->config->item('merchant_sub_id');
            $sign_key = $this->config->item('sign_key');
            $encryption_key = hash('sha256',$this->config->item('encryption_key'),true);
            $encryption_iv = $this->config->item('encryption_iv');

            $responsejson = $this->post('resjson');

            $log_message = '### Txn Response Received : '. $responsejson;
            log_message('ERROR',$log_message);
            $decodedVal = json_decode($responsejson);
            $retData = $decodedVal->data;
            $res = IOBPAY_UTILITY::pkcs5_unpad(openssl_decrypt ( base64_decode($retData) , 'AES-256-CBC' , $encryption_key ,OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $encryption_iv)); //php 7.1 and above
          
            $log_message = '### txninit service response after decryption: '. $res;
            log_message('ERROR',$log_message);
            
            $decodedData = json_decode($res);
            $errorcd = isset($decodedData->errorcd) ? $decodedData->errorcd : null;
           if($errorcd != NULL)
            {
                $log_message = '### Server error ! Please contact your website Administrator! Error Code : '. $errorcd;
                log_message('ERROR',$log_message);
                 
                    // $data['dataStatus'] = false;
                    // $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    // $data['msg'] = 'Server error ! Please contact your website Administrator! Error Code : '. $errorcd;
                    echo $log_message;
                    sleep(2);
                    header('Location: '.$this->config->item('failure_url'));
                    exit;
                   // $this->response($data,REST_Controller::HTTP_OK);
            }
            else
            {
                     $trackid = $decodedData->trackid;  //ensure to save in db
                     $txnstatus = $decodedData->txnstatus; //ensure to save in db
                     $merchanttxnid = $decodedData->merchanttxnid;

                     $updated = $this->user_management_model->updateRecords(array('trackid' => $trackid,'txnstatus' => $txnstatus),CSR_TXN_DETAILS,array('merchant_txn_id' => $merchanttxnid));

                     $contribution_id = $this->user_management_model->selectCustomRecords(array('con_id'),array('merchant_txn_id' => $merchanttxnid),CSR_TXN_DETAILS);

                     $temp_array = array('trackid' => $trackid,'txnstatus' => $txnstatus,'merchanttxnid' => $merchanttxnid);
                     if($trackid!=NULL)
                     {
                        if($txnstatus=="SUCCESS")
                        {
                           $temp_array['msg'] = 'Txn Successfull!';
                            // update FUNS_RECEIVED status against contribute id
                           $updated = $this->user_management_model->updateRecords(array('status' => 'FUNDS_RECEIVED'),CSR_CONTRIBUTIONS,array('id' => $contribution_id[0]['con_id']));

                            //update child
                                       $updated = $this->user_management_model->updateRecords(array('status' => 'FUNDS_RECEIVED'),CSR_CONTRIBUTION_DETAILS,array('cont_id' => $contribution_id[0]['con_id']));
                            //trigger mail           
                            $this->sendMail('SUCCESS',$merchanttxnid);           

                           header('Location: '.$this->config->item('success_url'));
                           exit;
                        }
                        else if($txnstatus=="FAILURE")
                        {
                             $temp_array['msg'] = 'Txn Failed!';
                             // $this->sendMail('FAILURE',$merchanttxnid);
                             header('Location: '.$this->config->item('failure_url'));
                             exit;
                        }
                        else if($txnstatus=="AWAITED")
                        {
                            $temp_array['msg'] = 'Txn status is awaited ! Please check after some time !';
                            header('Location: '.$this->config->item('awaited_url'));
                            exit;
                        }
                        else
                        {
                            $temp_array['msg'] = 'Txn status is unknown ! Please check after some time !';
                            header('Location: '.$this->config->item('awaited_url'));
                            exit;
                        }
                     }

                    
                    // $data['dataStatus'] = true;
                    // $data['status'] = REST_Controller::HTTP_OK;
                    // $data['records'] = $temp_array;
                    // $this->response($data,REST_Controller::HTTP_OK);
            }
        }
        else
        {
            set_status_header(REST_CONTROLLER::HTTP_UNAUTHORIZED,"Unauthorized");
            $response['status']=false;
            $response['error']="Access denied!";
            log_message('error','Access denied!');
            echo json_encode($response);
            sleep(2);
            header('Location: '.$this->config->item('failure_url'));
            exit; 
        }
    }

        public function checkTxnStatus_post()
        {
            $merchant_id = $this->config->item('merchant_id');
            $merchant_sub_id = $this->config->item('merchant_sub_id');
            $sign_key = $this->config->item('sign_key');
            $encryption_key = hash('sha256',$this->config->item('encryption_key'),true);
            $encryption_iv = $this->config->item('encryption_iv');
            $action = 'TXNSTATUS';
            $feetype = 'ALL FEES';
            $con_id = $this->post('con_id');
            $merchant_txn_id = $this->post('merchant_txn_id');
            $flag = $this->post('flag');
            $txn_details = array();

            if($flag == 'STATUS_CHECK')
            {
                $txn_details = $this->user_management_model->selectCustomRecords(array('trackid','token','amount','con_id'),array('merchant_txn_id' => $merchant_txn_id),CSR_TXN_DETAILS);
                
            }
            else if($flag == 'PDF')
            {
                //$txn_details = $this->user_management_model->selectCustomRecords(array('trackid','token','amount'),array('merchant_txn_id' => $merchant_txn_id),CSR_TXN_DETAILS);

                $this->db->SELECT('CSR_TXN_DETAILS.trackid,ROUND(CSR_TXN_DETAILS.amount,0) as amount,CSR_TXN_DETAILS.txnstatus,CSR_USER.name,CSR_USER_ORG.org_pan,DATE_FORMAT(convert_tz(CSR_TXN_DETAILS.createdon,"+00:00","+05:30"),"%d-%m-%Y") as txn_date,concat(DATE_FORMAT(convert_tz(CSR_TXN_DETAILS.createdon,"+00:00","+05:30"),"%Y%m%d"),CSR_TXN_DETAILS.merchant_txn_id) as ref_id');
                $this->db->FROM(CSR_TXN_DETAILS.' as CSR_TXN_DETAILS');
                $this->db->JOIN(CSR_USER.' as CSR_USER','CSR_TXN_DETAILS.user_id = CSR_USER.id','LEFT');
                $this->db->JOIN(CSR_USER_ORG.' as CSR_USER_ORG','CSR_USER.id = CSR_USER_ORG.user_id','LEFT');
                $this->db->WHERE('CSR_TXN_DETAILS.merchant_txn_id',$merchant_txn_id);
                $txn_details = $this->db->GET()->result_array();
                if(count($txn_details)) { $txn_details[0]['numtowords'] = $this->numtowords($txn_details[0]['amount']); }
            }

            if(count($txn_details))
            {

                if($flag == 'STATUS_CHECK')
                {
                        $totalamt = $txn_details[ (count($txn_details) - 1) ]['amount'];
                        $tokenid = $txn_details[ (count($txn_details) - 1) ]['token'];
                        $trackid = $txn_details[ (count($txn_details) - 1) ]['trackid'];
                        $con_id = $txn_details[ (count($txn_details) - 1) ]['con_id'];

                        $txn_staus = IOBPAY_UTILITY::checkTxnStatus($this->config->item('txn_status_url'),$merchant_id,$merchant_sub_id,$action,$feetype,$totalamt,$tokenid,$trackid,$sign_key,$encryption_key,$encryption_iv);
                            
                            $errorcd = isset($txn_staus->errorcd) ? $txn_staus->errorcd : null;
                           if($errorcd != NULL)
                            {
                                $log_message = '### Server error ! Please contact your website Administrator! Error Code : '. $errorcd;
                                log_message('ERROR',$log_message);
                                 
                                    $data['dataStatus'] = false;
                                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                                    $data['msg'] = 'Server error ! Please contact your website Administrator! Error Code : '. $errorcd;
                                    $this->response($data,REST_Controller::HTTP_OK);
                            }
                            else
                            {
                                     $trackid = $txn_staus->trackid;  //ensure to save in db
                                     $txnstatus = $txn_staus->txnstatus; //ensure to save in db
                                     $merchanttxnid = $txn_staus->merchanttxnid;

                                     $updated = $this->user_management_model->updateRecords(array('trackid' => $trackid,'txnstatus' => $txnstatus),CSR_TXN_DETAILS,array('merchant_txn_id' => $merchanttxnid));
                                     if($txnstatus == 'SUCCESS')
                                     {
                                        
                                        //update parent
                                       $updated = $this->user_management_model->updateRecords(array('status' => 'FUNDS_RECEIVED'),CSR_CONTRIBUTIONS,array('id' => $con_id));
                                       //update child
                                       $updated = $this->user_management_model->updateRecords(array('status' => 'FUNDS_RECEIVED'),CSR_CONTRIBUTION_DETAILS,array('cont_id' => $con_id));
                                       $this->sendMail('SUCCESS',$merchanttxnid);
                                     }
                                     else if($txnstatus == 'FAILURE')
                                     {
                                        $this->sendMail('FAILURE',$merchanttxnid);
                                     }

                             }
                            $result_array =  array('ref_id' => $trackid,'txnstatus' => $txnstatus,'amt' => $txn_staus->totalamt,'merchanttxnid' => $merchanttxnid);
                     }
                     else if($flag == 'PDF')
                     {
                        $result_array =   $txn_details;
                     }        
                            

                            $data['dataStatus'] = true;
                            $data['status'] = REST_Controller::HTTP_OK;
                            $data['records'] = $result_array;
                            $this->response($data,REST_Controller::HTTP_OK);
                    
            }
            else
            {
                    $data['dataStatus'] = true;
                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    $data['msg'] = 'No Txn details were found for requested contribute id';
                    $this->response($data,REST_Controller::HTTP_OK);
            }
        }
        public function testRedirect_get()
        {
            //sleep(2);
           // $this->load->helper('mail');

            //mail::sendMail($from,$fromDisplayName,$toWhom,$cc,$bcc,$subject,$isHTML = true,$mailContent);
            $this->sendMail('SUCCESS',88);

            //die();
            // echo 'HIdsjbkj';
            // $url = 'https://contribute.tnschools.gov.in/csr/#/contribute';
            // header('Location: '.$url);
            // exit; 

        }


        function numtowords($number)
        {
                   $no = floor($number);
                   $point = round($number - $no, 2) * 100;
                   $hundred = null;
                   $digits_1 = strlen($no);
                   $i = 0;
                   $str = array();
                   $words = array('0' => '', '1' => 'One', '2' => 'Two',
                    '3' => 'Three', '4' => 'Four', '5' => 'Five', '6' => 'Six',
                    '7' => 'Seven', '8' => 'Eight', '9' => 'Nine',
                    '10' => 'Ten', '11' => 'Eleven', '12' => 'Twelve',
                    '13' => 'Thirteen', '14' => 'Fourteen',
                    '15' => 'Fifteen', '16' => 'Sixteen', '17' => 'Seventeen',
                    '18' => 'Eighteen', '19' =>'Nineteen', '20' => 'Twenty',
                    '30' => 'Thirty', '40' => 'Forty', '50' => 'Fifty',
                    '60' => 'Sixty', '70' => 'Seventy',
                    '80' => 'Eighty', '90' => 'Ninety');
                   $digits = array('', 'Hundred', 'Thousand', 'Lakh', 'Crore');
                   while ($i < $digits_1) {
                     $divider = ($i == 2) ? 10 : 100;
                     $number = floor($no % $divider);
                     $no = floor($no / $divider);
                     $i += ($divider == 10) ? 1 : 2;
                     if ($number) {
                        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
                        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
                        $str [] = ($number < 21) ? $words[$number] .
                            " " . $digits[$counter] . $plural . " " . $hundred
                            :
                            $words[floor($number / 10) * 10]
                            . " " . $words[$number % 10] . " "
                            . $digits[$counter] . $plural . " " . $hundred;
                     } else $str[] = null;
                  }
                  $str = array_reverse($str);
                  $result = implode('', $str);
                  $points = ($point) ?
                    "." . $words[$point / 10] . " " . 
                          $words[$point = $point % 10] : '';
                  return  "Rupees ". $result . " Only";
                 
        }

        function sendMail($status,$merchanttxnid)
        {

             $mail_content = $this->user_management_model->getMailContentForOnlineTransaction($merchanttxnid);
             $mail_configs = $this->user_management_model->selectCustomRecords(array('*'),array('mail_code' => $status),CSR_MAIL_CONTENTS);
             // print_r($mail_configs);
             // print_r($mail_content);
             $fromMail = $mail_configs[0]['from_mail'];
             $display_name = $mail_configs[0]['display_name'];
             $subject = $mail_configs[0]['subject'];
             $tomail = $mail_content[0]['email'];
             $content = $mail_configs[0]['content'];
             $content = str_replace('{{user}}',$mail_content[0]['name'],$content);
             $content = str_replace('{{amount}}',$mail_content[0]['amount'],$content);
             $content = str_replace('{{txnstatus}}',$mail_content[0]['txnstatus'],$content);
             $content = str_replace('{{refid}}',$mail_content[0]['ref_id'],$content);
             $content = str_replace('{{trackid}}',$mail_content[0]['trackid'],$content);
             $this->load->helper('mymail');
             MYMAIL::sendmyMail($fromMail,$display_name, $tomail,$subject,$content);
        }
    

}