<?php
defined('BASEPATH') OR exit('No direct script access allowed');
define('TRIPAY_MODE', 'DEV');
define('TRIPAY_CH_DEV', 'https://tripay.co.id/api-sandbox/merchant/payment-channel');
define('TRIPAY_INT_DEV', 'https://tripay.co.id/api-sandbox/payment/instruction?');
define('TRIPAY_CR_DEV', 'https://tripay.co.id/api-sandbox/transaction/create');
define('TRIPAY_CH_PRO', 'https://tripay.co.id/api/merchant/payment-channel');
define('TRIPAY_INT_PRO', 'https://tripay.co.id/api/payment/instruction?');
define('TRIPAY_CR_PRO', 'https://tripay.co.id/api/transaction/create');

class Payment_model extends CI_Model {
    private function cek_total_keranjang() {
        $total = 0;
        $usrid = $this -> session -> ci_usrid;
        $cek   = $this -> db -> get_where('transaksi_detail', ['id_user' => $usrid, 'id_transaksi' => 0]) -> result();

        foreach($cek as $item) {
            $total += $item -> harga * $item -> jml;
        }

        return $total;
    }

    private function cek_jenis_keranjang($jenis) {
        $usrid  = $this -> session -> ci_usrid;
        return  $this -> db -> get_where('transaksi_detail', ['id_user' => $usrid, 'jenis' => $jenis, 'id_transaksi' => 0]) -> num_rows();
    }
    
    private function get($url) {
        $curl   = curl_init();
        $apiKey = app('tripay_apikey');        
        
        curl_setopt_array($curl, array(
            CURLOPT_FRESH_CONNECT  => true,
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => false,
            CURLOPT_HTTPHEADER     => ['Authorization: Bearer '.$apiKey],
            CURLOPT_FAILONERROR    => false,
            CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4
        ));
        
        $response = curl_exec($curl);
        $response = json_decode($response);
        $error    = curl_error($curl);
        
        curl_close($curl);

        return $error ? null : $response;
    }
    
    public function set_payment() {
        $tripay  = [];
        $cisa    = [];
        $manual  = [];
        $usrid   = $this -> session -> ci_usrid;
        $url     = TRIPAY_MODE == 'DEV' ? TRIPAY_CH_DEV : TRIPAY_CH_PRO;
        $get     = $this -> get($url);
        $bank    = $this -> db -> get('bank') -> result();
        $saldo   = $this -> db -> get('saldo', ['usrid' => $usrid, 'status' => 1]) -> result();
        $saldo   = $saldo ? $saldo : [(object)['id' => 0, 'usrid' => $usrid, 'saldo' => 0]];

        if($get AND $get -> success == 1) {
            foreach($get -> data as $item) {
                $fee    = $item -> group == 'Virtual Account' || $item -> group == 'Convenience Store' ? $item -> fee_customer -> flat : $item -> fee_customer -> percent / 100; 
                $fee_type =  $item -> group == 'Virtual Account' || $item -> group == 'Convenience Store' ? 'flat' : 'percent' ; 
                $item -> group = $item -> group  == 'Convenience Store' ? 'Gerai Retail' : $item -> group;
                $item -> group = $item -> group  == 'E-Wallet' ? 'Dompet Digital' : $item -> group;
                
                $tripay[] = (object) [
                    'code'     => $item -> code,
                    'group'    => $item -> group,
                    'gateway'  => 'Tripay',
                    'verify'   => 'Otomatis',
                    'name'     => $item -> name,
                    'saldo'    => 0,
                    'fee'      => $fee,
                    'fee_type' => $fee_type,
                    'icon'     => $item -> icon_url,
                    'norek'    => null,
                    'atasnama' => null,
                ];
            }
        }

        if($bank) {
            foreach($bank as $item) {
                $manual[] = (object) [
                    'code'     => $item -> kode,
                    'group'    => 'Transfer Bank',
                    'verify'   => 'Manual',
                    'gateway'  => 'Transfer Manual',
                    'name'     => 'Transfer' . ' ' . $item -> nama,
                    'saldo'    => 0,
                    'fee'      => $item -> fee,
                    'fee_type' => 'flat',
                    'icon'     => base_url('upload/bank/') . $item -> icon,
                    'norek'    => $item -> norek,
                    'atasnama' => $item -> atasnama,
                ];
            }
        }

        if($saldo) {
            foreach($saldo as $item) {
                $this -> db -> order_by('id', 'ASC');
                $riwayat = $this -> db -> get('saldo_riwayat', ['usrid' => $usrid, 'status' => 1]) -> row();
                $riwayat = $riwayat  ? $riwayat : new stdClass();
                $item -> saldo = isset($riwayat -> saldo_akhir) && $riwayat -> saldo_akhir == $item -> saldo ? $item -> saldo : 0;
                
                $cisa[]  = (object) [
                    'code'     => 'CISA',
                    'group'    => 'Saldo',
                    'verify'   => 'Otomatis',
                    'gateway'  => 'Saldo',
                    'name'     => 'Saldo ' . app('app_name'),
                    'saldo'    => $item -> saldo,
                    'fee'      => 0,
                    'fee_type' => 'flat',
                    'icon'     => base_url('assets/img/dompet.png'),
                    'norek'    => null,
                    'atasnama' => null,
                ];
            }
        }
        
        return array_merge($cisa, $manual, $tripay);

    }

    public function get_payment($semua = true, $total = true) {
        $data  = $this -> set_payment();
        $total = $total ? $this -> cek_total_keranjang() : 50000;
        $new   = [];

        $minmax = (object) [
            'transfer_bank' => (object) [
                'min' => 10000,
                'max' => 5000000
            ],
            'saldo' => (object) [
                'min' => 0,
                'max' => 10000000
            ],
            'virtual_account' => (object) [
                'min' => 10000,
                'max' => 5000000
            ],
            'gerai_retail' => (object) [
                'min' => 5000,
                'max' => 2500000
            ],
            'dompet_digital' => (object) [
                'min' => 5000,
                'max' => 5000000
            ],
        ];

        if($semua) {
            return $data;

        } else {
            foreach($data as $item) {
                $title = strtolower(str_replace(' ', '_', $item -> group));
                $min   = $minmax -> $title -> min;
                $max   = $minmax -> $title -> max;

                if($total >= $min && $total <= $max) {
                    $new[$title][] = $item;
                }
            }
    
            return $new;
        }
    }

    public function create_transaction($payload) {        
        $curl         = curl_init();
        $payload      = (object) $payload;
        $apiKey       = app('tripay_apikey');
        $privateKey   = app('tripay_privatekey');
        $merchantCode = app('tripay_merchant');
        $merchantRef  = $payload -> trxcode;
        $total        = $payload -> total;
        $endpoint     = TRIPAY_MODE == 'DEV' ? TRIPAY_CR_DEV : TRIPAY_CR_PRO;;

        $data = [
            'method'         => $payload -> metode,
            'amount'         => $total,
            'merchant_ref'   => $merchantRef,
            'customer_name'  => $payload -> nama,
            'customer_email' => $payload -> email,
            'customer_phone' => $payload -> nohp,
            'order_items'    => $payload -> cart,
            'expired_time'   => $payload -> kadaluarsa, 
            'signature'      => hash_hmac('sha256', $merchantCode.$merchantRef.$total, $privateKey)
        ];

        curl_setopt_array($curl, [
            CURLOPT_FRESH_CONNECT  => true,
            CURLOPT_URL            => $endpoint,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => false,
            CURLOPT_HTTPHEADER     => ['Authorization: Bearer '.$apiKey],
            CURLOPT_FAILONERROR    => false,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => http_build_query($data),
            CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4
        ]);
        
        $response = curl_exec($curl);
        $error    = curl_error($curl);          
        $response = json_decode($response);    
  
        curl_close($curl);
            
        return empty($error) && $response -> success ? $response -> data : $error;

    }

    public function detail_transaction() {
        $payload = ['reference'	=> 'DEV-T2307099976FAZQJ'];
        $url     = 'https://tripay.co.id/api-sandbox/transaction/detail?'.http_build_query($payload);
        $get     = $this -> get($url);

        return $get -> data;
    }

    public function intruksi($kode, $pay_code, $total) {
        $payload = [
            'code'       => $kode,
            'amount'     => format_uang($total),
            'pay_code'   => $pay_code,
            'allow_html' => 1
        ];
        $endpoint = TRIPAY_MODE == 'DEV' ? TRIPAY_INT_DEV : TRIPAY_INT_PRO;
        $url      = $endpoint.http_build_query($payload);
        $get      = $this -> get($url);

        return $get && $get -> success ? $get -> data : null;
    }
}

// Payment model
// Kode ini dibuat oleh codelingker