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

class Cibil extends CI_Controller {
	// Session Authoriesed
	public function __construct() {
		parent::__construct();
		
		$admin = $this->session->userdata('admin');
		$column['id'] = $admin['id'];
		$table = 'tbl_user';
		
	    // loading common model
	    $this->load->model('Common_model');
		$result = $this->Common_model->Result($column,$table);
		if($result['password'] == $admin['password']){
		    $login = true;
		} else {
		    $login = false;
		}
		
		if (empty($admin) || $login==false) {
			$this->session->set_flashdata('msg','Your Session Has Been Expired');
			redirect(base_url().'master/login/index');
		}
	}

	public function index()
	{
        // loading form validation
        $this->load->library('form_validation');
        
        // loading common model
        $this->load->model('Common_model');
        
        $column['id'] = 1;
        $table = 'tbl_settings';
        // get common data
        $data['data'] = $this->Common_model->Result($column,$table);
        
        $table = 'tbl_career';
        // get common data
        $data['career'] = $this->Common_model->Results($table);
        
        // get page name
        $page = 'Cibil';
        $data['page'] = $page;
        
     
       	$this->load->view('master/cibil/index',$data);
	}
	
	
	public function view($txnid)
	{
	    
	    
	    
	    
	    $this->db->where('txnid', $txnid);
        $this->db->limit(1);
        $dx = $this->db->get('tbl_cibil')->row();
        
        
      
   
        if(!isset($dx->status) || $dx->status==0){
            $this->session->set_flashdata('error', 'Invalid TxnId.');
            redirect(base_url().'master/cibil');
        }
        
        $data['cibil'] =$dx;
        
        // loading form validation
        $this->load->library('form_validation');
        
        // loading common model
        $this->load->model('Common_model');
        
        $column['id'] = 1;
        $table = 'tbl_settings';
        // get common data
        $data['data'] = $this->Common_model->Result($column,$table);
        
   
        // get page name
        $page = 'Cibil';
        $data['page'] = $page;
     
       	$this->load->view('master/cibil/view',$data);
	}
	
	
	public function getCibil(){
	    
        $xuid1='admin'; 
        $mrp=59;
                
        $query = $this->db->query("SELECT * FROM passbook order by id DESC");
        $row = $query->row();
        if($row){
           $w2= $row->balance;
        } else {
            $w2= 0;
        }
        
        if($w2 < $mrp){
            $this->session->set_flashdata('error', 'Contact to Administrator');
            redirect(base_url().'master/cibil');exit;
        }
        
        
        $this->db->where('txnid',$_POST['txnid']);
        $this->db->limit(1);
        $dx = $this->db->get('tbl_cibil')->row();
   
        if($dx->status){
            $this->session->set_flashdata('error', 'Invalid TxnId.');
            redirect(base_url().'master/cibil');exit;
        }

        $url = 'https://cyrusrecharge.in/api/total-kyc.aspx';
        
        $payload = [
            "merchantId" => "AP443406",
            "merchantKey"=> "6C3263189A",
            "full_name"       => $_POST['name'],
            "dob"       => $_POST['dob'],
            "address"       => $_POST['address'],
            "pincode"       => $_POST['pincode'],
            "mobile"     => $_POST['mobile'],
            "pan"        => $_POST['pan'],
            "type"       => "CIBIL_REPORT_SCORE",
            "txnid"      => $_POST['txnid'] // make this unique per request
        ];
        
     
    
    
        $ch = curl_init($url);
        
        $jsonData = json_encode($payload);
        
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $jsonData,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Accept: application/json',
                'Content-Length: ' . strlen($jsonData)
            ],
            // Optional but recommended
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        
        $response = curl_exec($ch);
        
        
        $data1=json_decode($response,true);
        
        
       
        
        if ($response === false) {
            $err = curl_error($ch);
            curl_close($ch);
            // handle error
            echo "cURL error: {$err}\n";
            exit;
        }
        //`user_id`, `name`, `mobile`, `pan`, `response`, `txnid`, `status`, `addon`
        $xdata = [
            "user_id"    => $_SESSION['admin']['id'],
            "full_name"       => $_POST['name'],
            "mobile"     => $_POST['mobile'],
            "pan"        => $_POST['pan'],
            "dob"        => $_POST['dob'],
            "address"        => $_POST['address'],
            "pincode"        => $_POST['pincode'],
            "txnid"      => $_POST['txnid'] ,
            "response"      => $response
        ];
        $this->db->insert('tbl_cibil',$xdata);
        
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // try to decode JSON response
        $data = json_decode($response, true);
        
        if($data['status']=='SUCCESS'){
            
            $datas91=[
                'uid'=>$xuid1,
                'note'=>'Cibil Report for '.$_POST['pan'],
                'type'=>'DR',
                'pre'=>$w2+0,
                'amount'=>$mrp,
                'balance'=>$w2-$mrp,
                'addon'=>date('Y-m-d H:i:s')
            ];
            
            $this->db->insert('passbook', $datas91);
            
            
            $this->db->where('txnid',$_POST['txnid']);
            $this->db->update('tbl_cibil',['status'=>1]);
            
            if(isset($data1['cibilReport']['data']['cCRResponse']['cIRReportDataLst'][0]['error']['errorDesc'])){
                
                $this->db->where('txnid',$_POST['txnid']);
                $this->db->update('tbl_cibil',['message'=>'No Cibil Score Found']);
            
            
                $this->session->set_flashdata('error', $data1['cibilReport']['data']['cCRResponse']['cIRReportDataLst'][0]['error']['errorDesc']);
                redirect(base_url().'master/cibil');
            
            }
            
            
            $this->session->set_flashdata('success', 'Cibil Check Success');
            redirect(base_url().'master/cibil/view/'.$_POST['txnid']);
        } else {
            $this->session->set_flashdata('error', 'Invalid TxnId.');
            redirect(base_url().'master/cibil');
        }
        
        
       

    }
    
    
    public function cibilList()
	{
        // loading form validation
        $this->load->library('form_validation');
        
        // loading common model
        $this->load->model('Common_model');
        
        $column['id'] = 1;
        $table = 'tbl_settings';
        // get common data
        $data['data'] = $this->Common_model->Result($column,$table);
        
       	if($_SESSION['admin']['id']!=1){
    	    $this->db->where('user_id',$_SESSION['admin']['id']);
        }
       	
        $data['coupon'] =$this->db->get('tbl_cibil')->result_array();
        
        $data['page'] = 'Cibil';
        
     
       	$this->load->view('master/cibil/list',$data);
	}

}

?>