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

if ( ! function_exists('flutterwave_api'))
{
    function flutterwave_api($in)
    {
        $out = array();
        $out['status'] = 'Unhandled error';
        $out['result'] = -1;

        $ch = curl_init();

        /* Example : 
            OrderedMap {
                 "account_bank": "044", 
                 "account_number": "0690000040", 
                 "amount": 5500, 
                 "narration": "Akhlm Pstmn Trnsfr xx007", 
                 "currency": "NGN", 
                 "reference": "akhlm-pstmnpyt-rfxx007_PMCKDU_1", 
                 "debit_currency": "NGN" 
            } 
        */
        $reference = str_replace('.','-',$in['id'].'.'.microtime());
        $out['my_reference'] = $reference;

        // temorarily 
        //$in['bank_code'] = "044";
        //$in['account_no'] = "0690000031";
        // ---- testing 

        // Setup request to send json via POST.
        $payload = json_encode(array(
            "money_transfer_id" => $in['id'],
            "account_bank" => $in['bank_code'],
            "account_number" => $in['account_no'],
            "amount" => $in['amount'],
            "narration" => $in['narration'],
            "currency" => "NGN",
            "reference" => $reference,
            "debit_currency" => "NGN"
        ));

        curl_setopt($ch, CURLOPT_URL,"http://host.docker.internal:9086/create");
        // curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        
        // Receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $result = curl_exec($ch);
        
        curl_close ($ch);
        
        $data = json_decode($result, true);

        //var_dump( $data);
        //exit;
        /*
            {"account_bank":"044","account_number":"0690000031","amount":"123.00","narration":"Transfer from Olusesan Amey
            ses66181+1@gmail.com","currency":"NGN","reference":"120-0-97165300 1652605656","debit_currency":"NGN"} //// {"status":200,"statusText":"OK","data":{"status":"success","message":"Transfer Queued Successfully","data":{"id":345332,"account_number":"0690000031","bank_code":"044","full_name":"Forrest Green","created_at":"2022-05-15T09:07:37.000Z","currency":"NGN","debit_currency":"NGN","amount":123,"fee":10.75,"status":"NEW","reference":"120-0-97165300 1652605656","meta":null,"narration":"Transfer from Olusesan Amey
            ses66181+1@gmail.com","complete_message":"","requires_approval":0,"is_approved":1,"bank_name":"ACCESS BANK NIGERIA"}}}
        */

        // Further processing ...
        if ($data!=null && is_array($data)) {
            if (array_key_exists('status',$data) && $data['status']=='success') {
                $out['result'] = 0; // OK
                $out['status'] = 'Transfer successful';
                if (array_key_exists('message',$data) && $data['message']!='') {
                    $out['status'].= ': '.$data['message'];
                }
            } else {
                $out['result'] = -3;
                $out['status'] = 'failure';
                if (array_key_exists('status',$data) && $data['status']!='') {
                    $out['status'] = (is_array($data['status'])?implode("<br/>\n",$data['status']):$data['status']);
                }
                if (array_key_exists('message',$data) && $data['message']!='') {
                    $out['status'].= ': '.(is_array($data['message'])?implode("<br/>\n",$data['message']):$data['message']);
                }
                if (array_key_exists('details',$data) && $data['details']!='') {
                    $out['status'].= ': <pre>'.json_encode($data['details'],JSON_PRETTY_PRINT).'</pre>';
                    //$out['status'].= ': '.(is_array($data['details'])?implode("<br/>\n",$data['details']):$data['details']);
                }
                if (array_key_exists('data',$data) && is_array($data['data']) 
                        && array_key_exists('message',$data['data']) && $data['data']['message']!='') {
                    $out['status'].= ': '.$data['data']['message'];
                }
                if (array_key_exists('data',$data) && is_array($data['data']) 
                        && array_key_exists('data',$data['data']) && is_array($data['data']['data'])
                        && array_key_exists('complete_message',$data['data']['data']) && $data['data']['data']['complete_message']!='') {
                    $out['status'].= ': '.$data['data']['data']['complete_message'];
                }
            }
        } else { 
            $out['result'] = -2;
            $out['status'] = 'Invalid service response: ' . $result;
        }
        // Cannot POST /api/create

        $out['response'] = $result;

        return $out;
    }   
}

if ( ! function_exists('flutterwave_api_check'))
{
    function flutterwave_api_check($in)
    {
        $out = array();
        $out['status'] = 'Unhandled error';
        $out['result'] = -1;

        $ch = curl_init();

        $url = "http://host.docker.internal:9086/status/".$in['id'];

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        
        $result = curl_exec($curl);

        curl_close($curl);
        
        //var_dump($result);
        /*
        string(592) "{"status":200,"statusText":"OK","data":{"status":"success","message":"Transfer fetched","data":{"id":348032,"account_number":"0690000031","bank_code":"044","full_name":"Forrest Green","created_at":"2022-06-05T04:22:49.000Z","currency":"NGN","debit_currency":"NGN","amount":123,"fee":10.75,"status":"FAILED","reference":"120-0-37263200 1654402969","meta":null,"narration":"Transfer from Olusesan Amey
        ses66181+1@gmail.com","approver":null,"complete_message":"DISBURSE FAILED: Insufficient funds in customer balance","requires_approval":0,"is_approved":1,"bank_name":"ACCESS BANK NIGERIA"}}}"
        */
        
        $data = json_decode($result, true);

        // Further processing ...
        if ($data!=null && is_array($data)) {
            if (array_key_exists('status',$data) && $data['status']=='200') {
                if (array_key_exists('data',$data) && is_array($data['data'])) {
                    $raw = $data['data'];
                    if (array_key_exists('status',$raw) && $raw['status']=='success') {
                        $out['result'] = 0; // OK
                        $out['status'] = $raw['message'];
                        if (array_key_exists('data',$raw) && is_array($raw['data'])) {
                            $out['status'].= ': '.$raw['data']['complete_message'];
                        } else {
                            $out['status'].= ': No transfer data found -> ' . json_encode($raw);
                        }
                    } else {
                        $out['result'] = -5;
                        $out['status'] = 'Flutterwave response failure: ' . json_encode($raw);
                    }
                } else {
                    $out['result'] = -4;
                    $out['status'] = 'Missing flutterwave response: ' . $result;
                }
            } else {
                // Error response
                $out['result'] = -3;
                if (array_key_exists('status',$data)) {
                    $out['status'] = $data['status'];
                } else {
                    $out['status'] = 'Missing starus response: ' . $result;
                }
            }
        } else { 
            $out['result'] = -2;
            $out['status'] = 'Invalid service response: ' . $result;
        }

        return $out;
    }
}
