<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Redemption extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('msgmodel');
        $this->load->model('cmerchantmodel');
        $this->load->model('cunitsmodel');
        $this->load->model('auditmodel');
        $this->load->model('mappingsmodel');
        $this->load->model('progressmodel');
        $this->load->model('dbmodel');
        $this->load->helper('string');
        $this->load->library('form_validation');
    }

    function fetchCustomers()
    {
        $merchants = array();
        $customer = $this->dbmodel->get('customers', array('record_state' => 0));
        foreach ($customer->result_array() as $cust) {
            $merchants[] = array(
                'client_id' => $cust['client_extid'],
                'name' => $cust['name'],
            );
        }
        echo json_encode(array('result' => 'ok', 'data' => $merchants));
    }

    function fetchPartners()
    {
        $clientid = $this->input->get('client_id');
        $merchants = array();

        $cs = $this->dbmodel->get('customers', array('record_state' => 0, 'client_extid' => $clientid))->row();

        if (!empty($clientid)) {
            $customer = $this->dbmodel->get('redemption_mappings', array('record_state' => 0, 'client_id' => $cs->id));
            foreach ($customer->result_array() as $cust) {
                $partners = $this->cmerchantmodel->get(array('record_state' => 0, 'dmo_id' => $cust['dmo_id']));
                foreach ($partners->result_array() as $row) {
                    $merchants[] = array(
                        'dmo_id'  => $row['dmo_id'],
                        'type'  => $row['type'],
                        'name'  => $row['name']
                    );
                }
            }
            echo json_encode(array('result' => 'ok', 'data' => $merchants));
        } else
            echo json_encode(array('result' => 'fail', 'data' => $merchants));
    }

    function redeem()
    {
        $this->form_validation->set_rules('dmo_id', 'Partner Code', 'required');
        $this->form_validation->set_rules('contact_phone', 'Phone', 'required');
        $this->form_validation->set_rules('amount', 'Amount', 'required');
        $this->form_validation->set_rules('customer', 'Customer', 'required');

        $dmo_id = $this->input->post('dmo_id');
        $customer = $this->input->post('customer');
        if ($dmo_id == "vend_airtime")
            $this->form_validation->set_rules('operator', 'operator', 'required');

        if ($dmo_id == "kplc_tokens" || $dmo_id == "kplc_postpay")
            $this->form_validation->set_rules('account', 'Account / Meter number', 'required');

        $username = $this->session->userdata('username');

        if ($this->form_validation->run() == FALSE || empty($username)) {
            $this->session->set_flashdata('tempdata', "Sorry there is an error on  your data. Please fix the issues addressed and try again.<br>" . validation_errors());
        } else {
            $customer = $this->dbmodel->get('customers', array('record_state' => 0, 'client_extid' => $customer))->row();
            $token = base64_encode($customer->client_extid .":". $customer->consumer_secret .":". $customer->consumer_key );

            $curl_post_data = array(
                'amount' => $this->input->post('amount'),
                'client_id' =>   $this->input->post('customer'),
                'operator' =>  $this->input->post('operator'),
                'account_no' =>  $this->input->post('account'),
                'meter_no ' =>  $this->input->post('account'),
                'phone_no' =>  $this->input->post('contact_phone'),
                'dmo_id' =>   $this->input->post('dmo_id')
            );

            $data_string = ""; // json_encode($curl_post_data); 
            foreach ($curl_post_data as $title => $value) {
                $data_string .= $title . "=" . $value . "&";
            }
            $data_string = rtrim($data_string, "&");

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, base_url() . "redemption_api/buy_card");
            curl_setopt(
                $curl,
                CURLOPT_HTTPHEADER,
                array(
                    'Content-Type: application/x-www-form-urlencoded',
                    "cache-control: no-cache",
                    "Authorization: Bearer ". $token
                )
            );
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
            $jsonstr = curl_exec($curl); 

            if ($jsonstr === false) {
                $this->auditmodel->insert("Error generating voucher : " . $jsonstr, 0, "Redemption API", $jsonstr);
                $this->session->set_flashdata('tempdata', "Failed to generate voucher " + curl_error($curl));
            } else {
                $json = json_decode($jsonstr); 
                //{"code":"woocommerce_rest_cannot_create","message":"Sorry, you are not allowed to create resources.","data":{"status":401}} 
                if(isset($json->code)){
                    if($json->data->status==200)
                        $this->session->set_flashdata('tempdata', "Generation ok sys response: " . $jsonstr);
                    else
                        $this->session->set_flashdata('tempdata', "Sorry generation failed sys response: " . $jsonstr);
                } else {
                    if ($json->result == "ok")
                        $this->session->set_flashdata('tempdata', "Generation ok sys response: " . $jsonstr);
                    else
                        $this->session->set_flashdata('tempdata', "Sorry generation failed sys response: " . $jsonstr);
                }
            }
        }
        //redirect(APP_BASE . "generate_vouchers");
    }
}
