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

class ePayment extends CI_Controller {
    
    public $host = "https://api.mahkamahagung.go.id/Epayment/";
    public $kode;
    public $indexPerkara;
    public $st = 1;

    public function __construct(){
        parent::__construct();
        $this->kode = $this->db->where("id = 82")->get('sys_config')->result()[0]->value;
        if(strlen($this->kode) == 5){
            $this->kode = "0".$this->kode;   
        }
        $this->indexPerkara = $this->db->where("id = 82")->get('sys_config')->result()[0]->value;
    }    

    function cekTransaksi(){
        $start_time = microtime(TRUE);

        $fn = "cek_transaksi";

        $tmp = $this->db->select(array('trx_id','epayment_id'))->where('status_bayar = 0')->get('epayment_virtual_account');
        foreach ($tmp->result() as $row) {
            $data = array(
                'kode_satker' => $this->kode,
                'trx_id' => $row->trx_id
            );
            $data = json_encode($data);
            $return = json_decode($this->post($fn,$data));
            if($return->status == 'sukses'){
                if($return->messages->status == '1'){    
                    $this->db->update('epayment_virtual_account', array('status_bayar' => 1), array('epayment_id' => $row->epayment_id));
                }
            }
        }
        $end_time = microtime(TRUE);

        echo $end_time - $start_time;

    }

    function generate(){
		if(empty($_POST)){
			show_404();
			return;
		}
		if($this->session->userdata('is_logged_in')==FALSE){
			echo json_encode(array('st'=>0,'msg'=>'<span style="color:red;font-weight:bold">Kesalahan : </span><br/>Anda Belum Login, Silahkan Login Terlebih Dahulu.'));
			return;
		}
		
        $fn = "generate";
		$forbidden_char= array("-");
        $namape = str_replace($forbidden_char, "", $this->input->post('nama_pihak',TRUE));
        $email = str_replace($forbidden_char, "", $this->input->post('email',TRUE));
        $nominal = intval(str_replace(".","",$this->input->post('jumlah',TRUE)));
		$telepon = str_replace($forbidden_char, "", $this->input->post('telepon',TRUE));
		$jenis_biaya = intval($this->input->post('jenis_biaya',TRUE));
		$deskripsi = 'Panjar';		
		$tahapan_id = 10;
		//$tahapan_id = $this->input->post('tahapan_id',TRUE);
		
		if($jenis_biaya < 1 || $jenis_biaya > 2){
			$this->show_errmsg('Jenis Biaya tidak valid.');
			return;
		}
		
		if($jenis_biaya==1){
            $perkara_id = NULL;
            $alur_perkara_id = intval($this->input->post('alur_perkara_id',TRUE));
            $is_jurnal = NULL;
        }elseif($jenis_biaya==2){
            $perkara_id = $this->encrypt->decode(base64_decode($this->input->post('enc_perkara_id',TRUE)));
            $alur_perkara_id = intval($this->input->post('alur_perkara_id1',TRUE));
            $is_jurnal = 0;
        }
		
		if(empty($namape) || empty($alur_perkara_id) || empty($telepon)){
			$this->show_errmsg('Data belum lengkap, silakan diisi kolom yang diwajibkan.');
			return;
		}
		if($nominal <=0){
			$this->show_errmsg('Jumlah panjar tidak boleh kurang dari 0.');
			return;
		}
		if (!preg_match("/[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+.[a-zA-Z]{2,4}/", $email) && !empty($email)){
			$this->show_errmsg('Alamat email tidak valid.<br/><i>*Harap kosongkan alamat email jika memang tidak tersedia.</i>');
			return;
		}
		if($jenis_biaya > 2 || $jenis_biaya < 1){
			$this->show_errmsg('Jenis biaya tidak jelas.');
			return;
		}
		
        $no_urut = $this->db->query("SELECT COUNT(*) + 1 AS no_urut FROM epayment_virtual_account WHERE DATE(created_time) = '".date("Y-m-d")."';")->result()[0]->no_urut;
        
        $data = array(
            'kode_satker' => $this->kode,
            'namape' => $namape,
            'email' => $email,
            'nominal' => $nominal,
            'no_urut' => $no_urut,
            'telepon' => $telepon,
            'deskripsi' => $deskripsi,
        );
        $data = json_encode($data);
		
        $return = json_decode($this->post($fn,$data));
		if( json_last_error()!==JSON_ERROR_NONE ){
			//echo json_encode(array( 'st'=>0,'msg'=>'<span style="color:red;font-weight:bold">GAGAL : </span><br/>Kendala pada komunikasi data.'.$this->json_last_error_msg() ) );
			$this->show_errmsg($this->json_last_error_msg(), 'Kendala pada komunikasi data');
			return;
		}
		//var_dump($return); die();
		
        $status = $return->status;
        if($status==="sukses"){
            $data = (array) $return->messages;
            $remove = array('status','data','kode_satker');
            foreach ($remove as $key) {
                unset($data[$key]);
            }
            $add = array(
                'email' => $email,
                'telepon' => $telepon,
                'perkara_id' => $perkara_id,
                'alur_perkara_id' => $alur_perkara_id,
				'tahapan_id' => $tahapan_id,
				'jenis_biaya' => $jenis_biaya,
                'is_jurnal' => $is_jurnal,
				'created_time' => substr($return->messages->trx_id,6,19)
                );
            $data = array_merge($data,$add);
            $this->db->replace('epayment_virtual_account',$data);
			echo json_encode(array('st'=>1,'msg'=>'Pendaftaran Virtual Account Berhasil'));
			return;
        }else{
			//var_dump($return->messages);
			(!empty($return->messages))?$err_desc=$return->messages->message:$err_desc='';
			$this->show_errmsg($err_desc, 'Pendaftaran Virtual Account Gagal');
			return;
		}
    }
	
	function show_errmsg($msg, $title=''){
		if(empty($return->title)){
			echo json_encode(array('st'=>0,'msg'=>'<span style="color:red;font-weight:bold">'.$title.' </span><br/>'.$msg));
		}else{
			echo json_encode(array('st'=>0,'msg'=>'<span style="color:red;font-weight:bold">Kesalahan : </span><br/>'.$msg));
		}
		return;
	}
	
	function json_last_error_msg() {
		static $ERRORS = array(
			JSON_ERROR_NONE => 'No error',
			JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
			JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
			JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
			JSON_ERROR_SYNTAX => 'Syntax error',
			JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
		);

		$error = json_last_error();
		return isset($ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
	}
    
    function post($fn, $data){
        $url = $this->host.$fn;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','User-Agent: e-payment','Authorization:'.$this->indexPerkara));
        curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response  = curl_exec($ch);
		$retry = 0;
		$_err = curl_errno($ch);
		$_errmsg = curl_error($ch);
		while(($_err != NULL || $_err > 0 || $response === false) && $retry < 3){
			$response = curl_exec($ch);
			$_err = curl_errno($ch);
			$_errmsg = curl_error($ch);
			$retry++;
		}
		if($_err != NULL || $_err > 0 || $response === false || $_err > 0){
			$response = array(
					'status' 	=> 'error',
					'message' 	=> '$_errmsg'
				);
		}
        curl_close($ch);
        return $response;
    }
}