<?php
defined('BASEPATH') or exit('Sorry request could not be completed');
require APPPATH . 'libraries/REST_Controller.php';
class Mobile_interface extends REST_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('auditmodel');
        $this->load->model('msgmodel');
        $this->load->model('targetsmodel');
        $this->load->model('usersmodel');
        $this->load->model('templatemodel');
        $this->load->model('earnsmodel');
        $this->load->model('earnhistorymodel');
        $this->load->model('cmerchantmodel');
        $this->load->model('countiesmodel');
        $this->load->model('cunitsmodel');
        $this->load->model('redeemsmodel');
        $this->load->model('distributorsmodel');
        $this->load->model('outletsmodel');
        $this->load->model('productsmodel');
        $this->load->model('currentaccmodel');
        $this->load->model('redemptionmodel');
        $this->load->model('categoriesmodel');
        $this->load->model('tokenmodel');
        $this->load->library('form_validation');
    }

    private function unauthorized($message, $optional = 200)
    {
        $this->auditmodel->insert($message, 1, "USSD USER");
        return json_encode(array('result' => 'fail', 'message' => $message));
    }

    private function oauth($phoneno, $password, $utype)
    {
        $result = $this->usersmodel->get(array('UserCode' => $phoneno, 'recordstate' => 0));
        if ($result->num_rows() > 0) {
            $row = $result->row();
            $dbPassword = $row->Password;
            if (password_verify($password, $dbPassword)) {
                if ($row->UserEnabled == 1) {
                    $token = do_hash(uniqid($row->UserCode . '$$@#FRW$%YHRTEW748@fh!()_+ETERT^%$^&*0dhaa!`', true));
                    $this->tokenmodel->insert($token, $row->UserCode);
                    $this->auditmodel->insert("App user Logged into the sytem VIA USSD", 1, $row->UserCode . " : " . $row->Firstname . " " .  $row->Secondname);

                    $mtoken = array();
                    $mtoken['result'] = "success";
                    $mtoken['account_type'] = $row->Usertype;
                    $mtoken['username'] = $phoneno;
                    $mtoken['fname'] = $row->Firstname;
                    return json_encode($mtoken);
                } else
                    return $this->unauthorized('Failed to log in : User account disabled.');
            } else
                return $this->unauthorized('Failed to log in : Wrong PIN was entered.');
        } else
            return $this->unauthorized('Failed to log in : Wrong PIN was entered.');
    }

    // User based Api
    public function change_password($phoneno, $pin)
    {
        $newpassword = password_hash($pin, PASSWORD_BCRYPT);
        $this->usersmodel->update(array('Password' => $newpassword), array('UserCode' => $phoneno));
        $this->auditmodel->insert("App user changed Pin VIA USSD", 1, $phoneno);

        return json_encode(array('result' => 'success', 'message' => 'Pin changed'));
    }

    private function check_balance($phoneno, $utype)
    {
        $users = $this->usersmodel->get(array('UserCode' => $phoneno, 'recordstate' => 0));
        if ($users->num_rows() > 0) {
            $user = $users->row();
            $customer =  $user->CUST_CD;
            $minimum_redeemable = 0;

            $mins = $this->redeemsmodel->get(array('item' => 'Minimum Redeemable', 'record_state' => 0));
            if ($mins->num_rows() > 0) {
                $minimum_redeemable = $mins->row()->value;
            }

            $kes = 1;
            $kshs = $this->redeemsmodel->get(array('item' => 'Redemption Rate KSH',  'record_state' => 0));
            if ($kshs->num_rows() > 0) {
                $kes = $kshs->row()->value;
            }

            $balances =  $this->currentaccmodel->get(array('record_state' => 0, 'islocked' => 0, 'CUST_CD' => $customer));

            $expiry = "";
            $mainbalance = 0;
            if ($balances->num_rows() > 0) {
                $mainbalance = $balances->row()->totals;
                $expiry =  $balances->row()->redeemexpiry;
            }

            $m = array(
                'points' => $mainbalance,
                'pointsksh' => $mainbalance * $kes,
                'expiry' => $expiry,
                'minimum_redeemable' => $minimum_redeemable
            );


            $this->auditmodel->insert("App user checked for balance Pin VIA USSD", 1, $phoneno);
            return json_encode(array('result' => 'success', 'data' => $m));
        } else
            return $this->unauthorized("User does not exist.");
    }

    public function redeem($phoneno, $amount, $distributor)
    {
        $users = $this->usersmodel->get(array('UserCode' => $phoneno, 'recordstate' => 0));
        $distributors = $this->cmerchantmodel->get(array('merchantcode' => $distributor, 'record_state' => 0, 'isexternal' => 0));

        if ($users->num_rows() > 0 && $distributors->num_rows() > 0) {
            $user = $users->row();
            $retailer = $this->outletsmodel->get(array('CUST_CD' => $user->CUST_CD, 'record_state' => 0));

            $balance = 0;
            $expiry = "";
            $minimum_redeemable = 0;
            $redeemval = 0;
            $customer = $user->CUST_CD;
            $outlet_row =  $retailer->row();

            $mins = $this->redeemsmodel->get(array('item' => 'Minimum Redeemable', 'record_state' => 0));
            if ($mins->num_rows() > 0) {
                $minimum_redeemable = $mins->row()->value;
            }

            $kshs = $this->redeemsmodel->get(array('item' => 'Redemption Rate KSH', 'record_state' => 0));
            if ($kshs->num_rows() > 0) {
                $redeemval = $kshs->row()->value;
            }

            $balances =  $this->currentaccmodel->get(array('record_state' => 0, 'CUST_CD' => $user->CUST_CD));

            if ($balances->num_rows() > 0) {
                $balance = $balances->row()->totals;
                $expiry = $balances->row()->redeemexpiry;
            }

            //start redemption process
            if ($balance > $minimum_redeemable) {
                // empty($expiry) || $expiry==0  -- this will mark if there is no expiry.
                if (empty($expiry) || $expiry == 0 || (int) strtotime($expiry) > (int) strtotime(date('Y-m-d H:i:s'))) {
                    // ensure amount is divisible by count.
                    $actualvalue = $amount / $redeemval;

                    if ($actualvalue <= $balance && $actualvalue >= $minimum_redeemable) {
                        $dist =  $distributors->row();
                        $remainder = $balance - $actualvalue;

                        $expiryMonths = "";
                        $redemptionParams = $this->redeemsmodel->get(array('item' => 'Expiry', 'record_state' => 0));
                        if ($redemptionParams->num_rows() > 0) {
                            $param = $redemptionParams->row();
                            $expiryMonths = $param->value;
                        }

                        $this->load->helper('string');
                        $mcode = strtoupper(random_string('alnum', 7));

                        $accObj = array(
                            'CUST_CD' => $customer,
                            'total' => $remainder,
                            'comments' => 'Balance after redeeming ' . number_format($actualvalue, 3)  . ' points worth KSH ' . $amount . ' with code: ' . $mcode,
                            'redeemexpiry' => date('Y-m-d H:i:s', strtotime('+' . (int) $expiryMonths . ' month')),
                            'lastredemption' => date('Y-m-d H:i:s'),
                            'redemptionrate' => $redeemval,
                            'islocked' => 0
                        );

                        if (empty($expiryMonths) || $expiryMonths == 0) {
                            $accObj['redeemexpiry'] = NULL;
                        }

                        $this->currentaccmodel->update(array('record_state' => 900), array('CUST_CD' => $customer, 'islocked' => 0, 'record_state' => 0));
                        $this->currentaccmodel->insert($accObj);

                        $acccObj = array(
                            'CUST_CD' => $customer,
                            'DIST_CD' => $distributor,
                            'total' => $amount,
                            'CODE' => $mcode,
                            'productcode' => '',
                            'noofunits' => $actualvalue,
                            'redeemed' => ''
                        );

                        $this->redemptionmodel->insert($acccObj);

                        $mbal = array(
                            "result" => "success",
                            'balance' => $remainder,
                            'redeemed_units' => round($actualvalue, 2),
                            'redeemed_points_value' => round($amount, 2),
                            'code' => $mcode
                        );

                        //Do your redemption communication here.
                        $msg = '<p>Congratulations! redemption successfull.</p>
                                <p>Redemption Code <b>' . $mcode . '</b></p>
                                <p>Redeem KSH ' . round($amount, 2)  . ' worth of products.</p>
                                <br>';
                        //<p>Balance is '. number_format($remainder) .'</p>

                        $this->auditmodel->insert("App user redeemed VIA USSD " .  "Redemption Code: " . $mcode . ". Redeem " . $actualvalue  . " points worth KSH " . number_format($amount, 2) . ".", 1, $user->phone);

                        if (!empty($user->email))
                            @$this->msgmodel->insert_comm($user->email, "email", $msg, APP_NAME . " - Redemption", $user->Firstname, $user->UserCode);
                        if (!empty($user->phone))
                            @$this->msgmodel->insert_comm($user->phone, "sms", "Redemption Code: " . $mcode . ". Congratulations! Redeem KSH " .  $amount  . " worth of products.", APP_NAME . " - Redemption", $user->Firstname, $user->UserCode);

                        //distributor message
                        $msg = '<p>' . $outlet_row->CUST_NAME . ' with phone number ' . $phoneno . ' redemption successfull. A customer has redeeemed with the following :</p>
                                        <p>Redemption Code <b>' . $mcode . '</b></p>
                                        <p>Redeemed KSH ' .  $amount  . ' worth of products </p>
                                        <br>';

                        if ($distributors->num_rows() > 0) {
                            if (!empty($dist->description))
                                @$this->msgmodel->insert_comm($dist->description, "email", $msg, APP_NAME . " - Redemption", $dist->name, $user->UserCode);

                            if (!empty($dist->type))
                                @$this->msgmodel->insert_comm($dist->type, "sms", $outlet_row->CUST_NAME . " with phone number " . $phoneno . " has redeemed KSH " .  $amount . ". Redemption Code: " . $mcode, APP_NAME . " - Redemption", $dist->name, $user->UserCode);
                        }

                        return json_encode($mbal);
                    } else {
                        return $this->unauthorized("Sorry you have insufficient balance.", 200);
                    }
                } else
                    return $this->unauthorized("Expiry date for your earnings has been reached.", 200);
            } else
                return $this->unauthorized("Sorry you haven't reached the minimum redeemable amount.", 200);
        } else
            return $this->unauthorized("Redemption partner code entered is not valid.", 200);
    }

    private function egift($dmoid, $amount)
    {
        $curl_post_data = array(
            'client_id' =>  client_id,
            'client_secret' =>  client_secret,
            'grant_type' =>  grant_type,
            'scope' =>  scope
        );

        $data_string = "";
        foreach ($curl_post_data as $item => $value) {
            $data_string .= $item . "=" . $value . "&";
        }

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, token_url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, rtrim($data_string, "&"));
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt(
            $curl,
            CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/x-www-form-urlencoded',
                "cache-control: no-cache",
            )
        );

        $curl_response = curl_exec($curl);
        if ($curl_response === false)
            echo   curl_error($curl);
        else {
            $resp = json_decode($curl_response);
            $token = $resp->access_token;
            return $this->buyCard($token, $dmoid, $amount);
        }
        curl_close($curl);
    }

    private function buyCard($token, $dmoid, $amount)
    {
        $curl_post_data = array(
            'dmo_id' =>  $dmoid,
            'amount' =>  $amount,
            'delivery_type' =>  'api',
            'delivery_data_rname' =>  '',
            'delivery_data_rmail' => '',
            'delivery_data_msg' => 'Your Redemption is Successful',
            'delivery_data_smail' => 'mzawadi@giift.com',
            'delivery_data_sname' => 'MZAWADI',
            'state' => 'MZAWADI_INTERNAL_ORDER_ID'
        );

        $data_string = "";
        foreach ($curl_post_data as $item => $value) {
            $data_string .= $item . "=" . $value . "&";
        }

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

        $resp = curl_exec($curl);
        curl_close($curl);
        return $resp;
    }

    public function redeemCrossIndustry($phoneno, $amount, $distributor)
    {
        $users = $this->usersmodel->get(array('UserCode' => $phoneno, 'recordstate' => 0));
        $distributors = $this->cmerchantmodel->get(array('merchantcode' => $distributor, 'record_state' => 0, 'ussd_state' => 1));

        if ($users->num_rows() > 0 && $distributors->num_rows() > 0) {
            $user = $users->row();
            $retailer = $this->outletsmodel->get(array('CUST_CD' => $user->CUST_CD, 'record_state' => 0));

            $balance = 0;
            $expiry = "";
            $minimum_redeemable = 0;
            $redeemval = 0;
            $customer = $user->CUST_CD;
            $outlet_row =  $retailer->row();

            $mins = $this->redeemsmodel->get(array('item' => 'Minimum Redeemable', 'record_state' => 0));
            if ($mins->num_rows() > 0) {
                $minimum_redeemable = $mins->row()->value;
            }

            $kshs = $this->redeemsmodel->get(array('item' => 'Redemption Rate KSH', 'record_state' => 0));
            if ($kshs->num_rows() > 0) {
                $redeemval = $kshs->row()->value;
            }

            $balances =  $this->currentaccmodel->get(array('record_state' => 0, 'CUST_CD' => $user->CUST_CD));

            if ($balances->num_rows() > 0) {
                $balance = $balances->row()->totals;
                $expiry = $balances->row()->redeemexpiry;
            }

            //start redemption process
            if ($balance >= $minimum_redeemable) {
                // empty($expiry) || $expiry==0  -- this will mark if there is no expiry.
                if (empty($expiry) || $expiry == 0 || (int) strtotime($expiry) > (int) strtotime(date('Y-m-d H:i:s'))) {

                    // ensure amount is divisible by count.
                    $actualvalue = $amount / $redeemval;

                    if ($actualvalue <= $balance && $actualvalue >= $minimum_redeemable) {
                        $remainder = $balance - $actualvalue;

                        $expiryMonths = "";
                        $redemptionParams = $this->redeemsmodel->get(array('item' => 'Expiry', 'record_state' => 0));
                        if ($redemptionParams->num_rows() > 0) {
                            $param = $redemptionParams->row();
                            $expiryMonths = $param->value;
                        }

                        $resp = $this->egift($distributor, $amount);

                        $encresp = json_decode($resp);
                        if (!isset($encresp->error)) {

                            //{
                            // "orderId":"1575455460VGwua",
                            //"state":"MZAWADI_INTERNAL_ORDER_ID",
                            //"cards":[
                            //{"id":"1575455460Y2ZDP",
                            //"dmo_id":"1481011677rFway",
                            //"user":null,
                            //"status":"135024633118xiinl",
                            //"status_name":"usable",
                            //"fields":{
                            //"value":250,
                            //"number":"0602107102747621",
                            //"expiration":"2020-06-04"
                            //},"created_at":1575455460,
                            //"updated_at":1575455460}
                            //]
                            //} 

                            $mcode = $encresp->cards[0]->fields->number;
                            $expiry = $encresp->cards[0]->fields->expiration;

                            $accObj = array(
                                'CUST_CD' => $customer,
                                'total' => $remainder,
                                'comments' => 'Balance after redeeming ' . number_format($actualvalue, 3)  . ' points worth KSH ' . $amount . ' with voucher code: ' . $mcode,
                                'redeemexpiry' => date('Y-m-d H:i:s', strtotime('+' . (int) $expiryMonths . ' month')),
                                'lastredemption' => date('Y-m-d H:i:s'),
                                'redemptionrate' => $redeemval,
                                'islocked' => 0
                            );

                            if (empty($expiryMonths) || $expiryMonths == 0) {
                                $accObj['redeemexpiry'] = NULL;
                            }

                            $this->currentaccmodel->update(array('record_state' => 900), array('CUST_CD' => $customer, 'islocked' => 0, 'record_state' => 0));
                            $this->currentaccmodel->insert($accObj);

                            $acccObj = array(
                                'CUST_CD' => $customer,
                                'DIST_CD' => $distributor,
                                'total' => $amount,
                                'CODE' => $mcode,
                                'productcode' => '',
                                'noofunits' => $actualvalue,
                                'redeemed' => ''
                            );

                            $this->redemptionmodel->insert($acccObj);

                            $mbal = array(
                                "result" => "success",
                                'balance' => $remainder,
                                'redeemed_units' => round($actualvalue, 2),
                                'redeemed_points_value' => round($amount, 2),
                                'code' => $mcode
                            );

                            //Do your redemption communication here.
                            $msg = '<p>Congratulations, ' . $distributors->row()->name . ' voucher acquired.</p>
                                    <p>Voucher Code <b>' . $mcode . '</b> worth KSH ' . $amount  . '.</p>
                                    <p>Voucher Expiry <b>' . $expiry . '</b> </p>
                                    <br>';

                            $this->auditmodel->insert("App user redeemed VIA USSD **External redemption " .  "Voucher Code: " . $mcode . ". Redeem " . $actualvalue  . " points worth KSH " . number_format($amount, 2) . ".", 1, $user->phone, $resp);

                            if (!empty($user->email))
                                @$this->msgmodel->insert_comm($user->email, "email", $msg, APP_NAME . " - Voucher", $user->Firstname, $user->UserCode);
                            if (!empty($user->phone))
                                @$this->msgmodel->insert_comm($user->phone, "sms", "Congratulations " . $distributors->row()->name . " voucher acquired Voucher code " .  $mcode  . ". Voucher expiry " . $expiry, APP_NAME . " - Redemption", $user->Firstname, $user->UserCode);

                            return json_encode($mbal);
                        } else {
                            $error = $encresp->error_description;
                            $this->auditmodel->insert("App user tried to redeem VIA USSD **External redemption: server response" . $resp, 0, $user->phone, $resp);
                            return $this->unauthorized("Failed to redeem." . $error, 200);
                        }
                    } else {
                        $this->auditmodel->insert("App user tried to redeem VIA USSD **External redemption insufficient balance", 0, $user->phone);
                        return $this->unauthorized("Sorry you have insufficient balance.", 200);
                    }
                } else {
                    $this->auditmodel->insert("App user tried to redeem VIA USSD **External redemption points have expired", 0, $user->phone);
                    return $this->unauthorized("Expiry date for your earnings has been reached.", 200);
                }
            } else {
                $this->auditmodel->insert("App user tried to redeem VIA USSD **External redemption, minimum redeemable amount has not been met", 0, $user->phone);
                return $this->unauthorized("Sorry you haven't reached the minimum redeemable amount i.e. " . $minimum_redeemable . " points", 200);
            }
        } else {
            $this->auditmodel->insert("App user tried to redeem VIA USSD **External redemption redemption partner does not exist", 0, $user->phone);
            return $this->unauthorized("Redemption partner code entered is not valid.", 200);
        }
    }

    public function reset_password($phoneno)
    {
        $pin = $this->generatePass();
        $newpassword = password_hash($pin, PASSWORD_BCRYPT);
        $this->usersmodel->update(array('Password' => $newpassword), array('UserCode' => $phoneno));
        $this->auditmodel->insert("App user reset Pin VIA USSD, new pin sent on sms.", 1, $phoneno);
        @$this->msgmodel->insert_comm($phoneno, "sms", "Your pin has been reset, your new pin is " . $pin, "Pin reset", "", $phoneno);
        return json_encode(array('result' => 'success', 'message' => 'Pin changed'));
    }

    private function generatePass()
    {
        $word = "";
        $pick = '123456789';
        $length = 4;
        while (strlen($word) < $length) {
            $word .= substr($pick, mt_rand() % (strlen($pick)), 1);
        }
        return $word;
    }

    function generateCode()
    {
        $code = "D001";
        $outlets = $this->db->query("select * from outlets order by id desc limit 1");
        if ($outlets->num_rows() > 0) {
            $row = $outlets->row();
            $code = $row->id;
            $cd = str_replace("D", "", $code);
            $cd = (int) $cd + 1;
            $code = "D" . str_pad($cd, 3, "0", STR_PAD_LEFT);

            $ml = $this->outletsmodel->get(array('CUST_CD', $code));
            if ($ml->num_rows() > 0)
                $this->generateCode();
        }
        return $code;
    }

    function enroll_retailer($phone, $bsnname, $fname, $sname, $loc, $region, $county, $distcode, $custcode)
    {
        $bsnname = ucfirst(strtolower($bsnname));
        $fname = ucfirst(strtolower($fname));
        $sname = ucfirst(strtolower($sname));
        $adding = "retailer";
        $action = "";
        $custcode = $this->generateCode();

        if (empty($bsnname) || empty($fname) || empty($sname) || empty($phone) || empty($loc)) {
            return $this->unauthorized("Required fields are missing ", 400);
        } else {
            //validation OK

            $phonenos = $this->outletsmodel->get(array('CUST_PHONE' => $phone, 'record_state' => 0));
            $usersphonenos = $this->usersmodel->get(array('UserCode' => $phone, 'recordstate' => 0));

            if (($phonenos->num_rows() > 0 || $usersphonenos->num_rows() > 0) && empty($action)) {
                $this->auditmodel->insert("Tried to add an " . $adding . " in the sytem.  " . $adding . " code already exists (" . $phone  . ")", 0, "", json_encode($this->input->post()));
                return $this->unauthorized("Failed to register phone number already exists.", 400);
            } else {
                //$mterritory = $this->input->post('territory');
                //$mregion = $this->input->post('region');
                //$territories = $this->regionsmodel->get(array('region' => $mterritory, 'recordstate' => 0));
                //$regions = $this->territorymodel->get(array('territory' => $mregion, 'recordstate' => 0));
                $all = $this->outletsmodel->get();
                /*if (!empty($custcode))
                    $code = $custcode;
                else*/
                $code = $this->generateCode();
                $outlet = array(
                    'CUST_CD' => $code,
                    'DIST_CD' => ucfirst($adding),
                    'CUST_NAME' => $bsnname,
                    'CUST_PHONE' =>  $phone,
                    'email' =>  '',
                    'LONGITUDE' => '0',
                    'LATITUDE' => '0',
                    'CUST_STATUS' => 1,
                    'TERRITORY' => $region, //this will hold region
                    'ROUTE' => $county,   //this will hold territory
                    'AREA' => ucfirst($loc),
                    'contactfname' =>  $fname,
                    'contactsname' =>  $sname,
                    'BE_CUST_CD' => $distcode,
                    'OBOS' => '',
                    'CHANNEL' => '',
                    'SUBCHANNEL' => '',
                    'SEGMENT' => ''
                );
                $this->auditmodel->insert("Added a new " . $adding . " in the system (" . $code . "-" . $fname . " " . $sname . ")", 1, "", json_encode($outlet));
                $added = $this->outletsmodel->insert($outlet);
                if ($added > 0) {
                    $this->save_user($outlet, $adding);
                    return json_encode(array('result' => 'ok', 'status' => 'Retailer added'), 200);
                } else
                    return $this->unauthorized('Sorry could not add installer details. Please try again.', 400);
            }
        }
    }

    private function save_user($outlet, $usertype = 'Retailer', $addedby = 'upload user')
    {
        $cust_cd = $outlet['CUST_CD'];
        $dist_cd = $outlet['DIST_CD'];
        $owner_firstname = $outlet['contactfname'];
        $owner_secondname = $outlet['contactsname'];
        $owner_phone = $outlet['CUST_PHONE'];
        $owner_email = $outlet['email'];

        $password = $this->generatePass();
        $upassword =  password_hash($password, PASSWORD_BCRYPT);

        $u = $this->usersmodel->get(array('recordstate' => 0, 'UserCode' => $owner_phone));
        if ($u->num_rows() > 0) {
            $this->auditmodel->insert("Tried to register APP user details who already exists: Phone: " . $owner_phone . " name : " . $owner_firstname . $owner_secondname, 0, $addedby, json_encode($outlet));
            return;
        }

        $user = array(
            'recordstate' => 0,
            'CreationUser' => $this->session->userdata('username'),
            'CreationDate' => date('Y-m-d H:i:s'),
            'ApproveComment' => "Outlet User Created",
            'ApproveDate' => date('Y-m-d H:i:s'),
            'Firstname' => $owner_firstname,
            'Secondname' => $owner_secondname,
            'Surname' => '',
            'email' => $owner_email,
            'Password' => $upassword,
            'phone' => $owner_phone,
            'UserType' => ucfirst($usertype),
            'UserCode' => $owner_phone,
            'UserEnabled' => 1,
            'BusinessID' => 1,
            'LastLoginTime' => date('Y-m-d H:i:s'),
            'region' => '',
            'route' => '',
            'CUST_CD' => $cust_cd
        );

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

        $result = $this->usersmodel->insertObj($user);

        if ($result > 0) {
            $msg = '<p>Your account has been created on ' . APP_NAME . '.</p>
                                <p>Dial ' . APP_USSD . ' to check your balance and redeem.</p>
                                <p>Use the following:</p>
                                <table border="0" cellpadding="0" cellspacing="0">
                                <tr><td>PIN: ' . $password . '</td></tr></tbody>
                                </table><br>';

            $sms = $owner_firstname . ", thank you for registering into the " . APP_NAME . ".Your account has been created, PIN:  " . $password . ".Dial " . APP_USSD . " to redeem.";


            if (!empty($owner_email))
                $this->msgmodel->insert_comm($owner_email, "email", $msg, APP_NAME . ", account Created", $owner_firstname, $addedby);

            if (!empty($owner_phone))
                $this->msgmodel->insert_comm($owner_phone, "sms", $sms, APP_NAME . ", account Created", $owner_firstname, $addedby);

            $this->auditmodel->insert("Added APP user details: Email: " . $owner_email . " name : " . $owner_firstname . $owner_secondname, $result, $addedby, json_encode($outlet));
        } else {
            $this->auditmodel->insert("Tried to register APP user details: Email: " . $owner_email . " name : " . $owner_firstname . $owner_secondname, $result, $addedby, json_encode($outlet));
        }
    }


    public function deduct_amount($phoneno, $amount, $activity, $distributor, $ref)
    {
        $redeemval = 0;
        $users = $this->usersmodel->get(array('UserCode' => $phoneno, 'recordstate' => 0));
        $kshs = $this->redeemsmodel->get(array('item' => 'Redemption Rate KSH', 'record_state' => 0));

        if ($kshs->num_rows() > 0) {
            $redeemval = $kshs->row()->value;
        }

        if ($users->num_rows() > 0) {
            $user = $users->row();
            $customer = $user->CUST_CD;
            // ensure amount is divisible by count.
            $actualvalue = $amount / $redeemval;

            $balances =  $this->currentaccmodel->get(array('record_state' => 0, 'CUST_CD' => $user->CUST_CD));
            if ($balances->num_rows() > 0) {
                $balance = $balances->row()->totals;
                $expiry = $balances->row()->redeemexpiry;
            }

            $remainder = $balance - $actualvalue;

            $expiryMonths = "";
            $redemptionParams = $this->redeemsmodel->get(array('item' => 'Expiry', 'record_state' => 0));
            if ($redemptionParams->num_rows() > 0) {
                $param = $redemptionParams->row();
                $expiryMonths = $param->value;
            }

            $accObj = array(
                'CUST_CD' => $customer,
                'total' => $remainder,
                'comments' => 'Balance after redeeming ' . number_format($actualvalue, 3)  . ' points worth KSH ' . $amount . ' for : ' . $activity,
                'redeemexpiry' => date('Y-m-d H:i:s', strtotime('+' . (int) $expiryMonths . ' month')),
                'lastredemption' => date('Y-m-d H:i:s'),
                'redemptionrate' => $redeemval,
                'islocked' => 0
            );

            if (empty($expiryMonths) || $expiryMonths == 0) {
                $accObj['redeemexpiry'] = NULL;
            }

            $this->currentaccmodel->update(array('record_state' => 900), array('CUST_CD' => $customer, 'islocked' => 0, 'record_state' => 0));
            $this->currentaccmodel->insert($accObj);

            $acccObj = array(
                'CUST_CD' => $customer,
                'DIST_CD' => $distributor,
                'total' => $amount,
                'CODE' => $ref,
                'productcode' => '',
                'noofunits' => $actualvalue,
                'redeemed' => ''
            );

            $this->redemptionmodel->insert($acccObj);

            $mbal = array(
                "result" => "success",
                'balance' => $remainder,
                'redeemed_units' => round($actualvalue, 2),
                'redeemed_points_value' => round($amount, 2),
                'code' => $ref
            );
            /*
            //Do your redemption communication here.
            $msg = '<p>Congratulations! redemption successfull.</p>
                    <p>Redemption Code <b>' . $ref . '</b></p>
                    <p>Redeem KSH ' . round($amount, 2)  . ' worth of products.</p>
                    <br>';
            //<p>Balance is '. number_format($remainder) .'</p>
*/
            $this->auditmodel->insert("App user redeemed VIA USSD " .  "Redemption Code: " . $ref . ". Redeem " . $actualvalue  . " points worth KSH " . number_format($amount, 2) . ". on " . $activity, 1, $user->phone);
            /*
            if (!empty($user->email))
                @$this->msgmodel->insert_comm($user->email, "email", $msg, APP_NAME . " - Redemption", $user->Firstname, $user->UserCode);
            if (!empty($user->phone))
                @$this->msgmodel->insert_comm($user->phone, "sms", "Redemption Code: " . $mcode . ". Congratulations! Redeem KSH " .  $amount  . " worth of products.", APP_NAME . " - Redemption", $user->Firstname, $user->UserCode);
            */
        }
    }

    private function execute($url, $data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    private function send_credit($credit, $mobile, $operator)
    {
        /*
    username: zawadi
     password: 2020
     API Key: UAAh4YxE5TZs62b5VugvSawW1XH5mRngQWIk2GScurQ
     web: vendiplus.com
     API: vendiplus.com:8585
     /login
     REQ:
     {"username": "username","password":"password"}
    */
        //login
        $url = 'https://vendingpointea.com:2053/v3/login';
        $data = array('username' => 'mzawadi', 'password' => 'Tally2020#');
        $response = $this->execute($url, $data);
        $obj = json_decode($response);
        if ($obj->status == 0) {
            if (($obj->balance / 100) >  5 && ($obj->balance / 100) >  $credit) {
                $url = 'https://vendingpointea.com:2053/v3/airtimebuypinless';
                $data = array("username" => "mzawadi", "operator" => $operator, "amount" => $credit, "mobileno" => "$mobile", "key" => $obj->key);
                $response = $this->execute($url, $data);
                $this->auditmodel->insert("Credit issued >> " . $mobile . " Amount " . $credit . " Operator " . $operator . " Account Balance " . ($obj->balance / 100), 1, "Service", $response);
                $obj = json_decode($response);
                $b = $obj->transaction;
                if ($b->status == 1) {
                    $this->deduct_amount($mobile, $credit, $operator . " airtime", "Airtime", $b->transactionId);
                    @$this->msgmodel->insert_comm($mobile, "sms", "You have redeemed KSH " .  $credit  . " " . $operator . " airtime. You will receive a Topup sms soon.", "Airtime", "", "AIRTIME");
                }
            }
        }
        return $obj;
    }

    private function kplc_bill($account, $amount, $mobile)
    {
        //login
        $url = 'https://vendingpointea.com:2053/v3/login';
        $data = array('username' => 'mzawadi', 'password' => 'Tally2020#');
        $response = $this->execute($url, $data);
        $obj = json_decode($response);
        $k = array();
        if ($obj->status == 0) {
            $key = $obj->key;
            if (($obj->balance / 100) >  $amount) {
                $url = 'https://vendingpointea.com:2053/v3/verify';
                $data = array("username" => "mzawadi", "meter" => "$account", "key" => $key);
                $response = $this->execute($url, $data);
                $this->auditmodel->insert("Verified account details >> " . $mobile . " Account " . $account . " topay " . $amount . " Account Balance " . ($obj->balance / 100), 1, "Service", $response);
                $obj = json_decode($response);

                //do pay now
                if ($obj->status == 0) {
                    $customer = $obj->customerName;

                    $url = 'https://vendingpointea.com:2053/v3/vend';
                    $data = array("username" => "mzawadi", "meter" => "$account", "amount" => $amount, "key" => $key, "customerName" => $customer);

                    $response = $this->execute($url, $data);
                    $this->auditmodel->insert("Purchased Tokens account details >> Customer " . $customer . " Phone " . $mobile . " Account " . $account . " topay " . $amount, 1, "Service", $response);
                    $obj = json_decode($response);
                    $ref = "";
                    $operator = "";
                    if ($obj->status == 1) {
                        $msg = $obj->msg;
                        if (empty($msg)) {
                            $o = $obj->transaction;
                            $ref = $o->ref;
                            $operator = "KPLC tokens";
                            $this->deduct_amount($mobile, $amount, $operator, "KPLC", $ref);
                            @$this->msgmodel->insert_comm($mobile, "sms", "You have redeemed KSH " .  $amount  . " on KPLC tokens.You will receive KPLC sms once it reflects.", "KPLC Tokens", $customer, "KPLC");

                            $k = json_encode(array('result' => 'ok', 'data' => 'Transaction is pending. Wait for KPLC SMS for tokens.'));
                        } else
                            $k = json_encode(array('result' => 'fail', 'data' => 'Failed to redeem. KPLC could not be reached, please try again.'));
                    } else {
                        $o = $obj->transaction;
                        $token = $o->token;
                        $units = $o->units;
                        $ref = $o->ref;
                        $operator = "KPLC tokens";
                        $k = json_encode(array('result' => 'ok', 'data' => 'Token: ' . $token . ' Units: ' . $units));
                        $this->deduct_amount($mobile, $amount, $operator, "KPLC", $ref);
                        @$this->msgmodel->insert_comm($mobile, "sms", "You have redeemed KSH " .  $amount  . " on KPLC tokens. Units : " . $units . " Token : " . $token, "KPLC Tokens", $customer, "KPLC");
                    }
                } else
                    $k = json_encode(array('result' => 'fail', 'data' => 'Failed to get account name'));
            } else
                $k = json_encode(array('result' => 'fail', 'data' => 'Failed please try again.'));
        } else
            $k = json_encode(array('result' => 'fail', 'data' => 'Failed please try again.'));
        return $k;
    }

    private function kplc_bill_only($account, $amount, $mobile)
    {
        //login
        $url = 'https://vendingpointea.com:2053/v3/login';
        $data = array('username' => 'mzawadi', 'password' => 'Tally2020#');
        $response = $this->execute($url, $data);
        $obj = json_decode($response);
        $k = array();
        if ($obj->status == 0) {
            $key = $obj->key;
            if (($obj->balance / 100) >  $amount) {
                $url = 'https://vendingpointea.com:2053/v3/postpaidverify';
                $data = array("username" => "mzawadi", "accountNo" => "$account", "key" => $key);
                $response = $this->execute($url, $data);
                $this->auditmodel->insert("Verified account details >> " . $mobile . " Account " . $account . " topay " . $amount . " Account Balance " . ($obj->balance / 100), 1, "Service", $response);
                $obj = json_decode($response);

                //do pay now 
                if ($obj->status == 0) {
                    $customer = $obj->customerName;

                    $url = 'https://vendingpointea.com:2053/v3/postpaidbill';
                    $data = array("username" => "mzawadi", "accountNo" => "$account", "amount" => $amount, "key" => $key, "customerName" => $customer);
                    $response = $this->execute($url, $data);
                    $this->auditmodel->insert("Purchased Tokens account details >> Customer " . $customer . " Phone " . $mobile . " Account " . $account . " topay " . $amount, 1, "Service", $response);
                    $obj = json_decode($response);
                    $ref = "";
                    $operator = "";
                    if ($obj->status == 1) {
                        $msg = $obj->msg;
                        if (empty($msg)) {
                            $o = $obj->transaction;
                            $ref = $o->transactionId;
                            $operator = "KPLC Bill";
                            $this->deduct_amount($mobile, $amount, $operator, "KPLC", $ref);
                            @$this->msgmodel->insert_comm($mobile, "sms", "You have redeemed KSH " .  $amount  . " on KPLC bill.You will receive KPLC sms once it reflects.", "KPLC Bill", $customer, "KPLC");
                            $k = json_encode(array('result' => 'ok', 'data' => 'Transaction is pending. Wait for KPLC SMS'));
                        } else
                            $k = json_encode(array('result' => 'fail', 'data' => 'Failed to redeem. KPLC could not be reached, please try again.'));
                    } else {
                        $o = $obj->transaction;
                        $ref = $o->ref;
                        $operator = "KPLC Bill";
                        //$token = $o->token;
                        //$units = $o->units; 
                        $this->deduct_amount($mobile, $amount, $operator, "KPLC", $ref);
                        @$this->msgmodel->insert_comm($mobile, "sms", "You have redeemed KSH " .  $amount  . " on KPLC bill.You will receive KPLC sms once it reflects.", "KPLC Bill", $customer, "KPLC");
                        $k = json_encode(array('result' => 'ok', 'data' => 'Payment details have been posted to KPLC'));
                    }
                } else
                    $k = json_encode(array('result' => 'fail', 'data' => 'Failed to get account name'));
            } else
                $k = json_encode(array('result' => 'fail', 'data' => 'Failed please try again.'));
        } else
            $k = json_encode(array('result' => 'fail', 'data' => 'Failed please try again.'));
        return $k;
    }


    //USSD functions
    public function ussd_get()
    {
        //Get the variables from the USSD gateway 
        $SESSIONID = $this->get("SESSIONID");
        $USSDCODE = rawurldecode($this->get("USSDCODE"));
        $MSISDN = $this->get("MSISDN");
        $INPUT = rawurldecode($this->get("INPUT"));

        $MSISDN = "0" . substr($MSISDN, 3, strlen($MSISDN));
        $inputArray = explode("*", trim($INPUT));
        $lastInput = $inputArray[sizeof($inputArray) - 1];

        if (empty(trim($INPUT))) {
            $response = "END Invalid entry\n";
            header('Content-type: text/plain');
            echo $response;
            return;
        }

        if ($lastInput == "33") {
            $users = $this->usersmodel->get(array('Usercode' => $MSISDN, 'recordstate' => 0));
            if ($users->num_rows() > 0)
                $response = "CON Welcome to " . APP_NAME . ".\n1 Enter PIN\n2 Forgot pin";
            else
                $response = "CON Welcome to " . APP_NAME . ".\n1 Register\n2 Exit";
            //note the NEW LINE \n 
        } else {
            //this is where we do register or not
            if (is_numeric($lastInput) && $lastInput == 0 && strlen($lastInput) == 1) {
                //this is go back
                $preprocessed = array($inputArray[0], $inputArray[1], $inputArray[2]);
            } else {
                if (count($inputArray) < 3) {
                    $preprocessed = $inputArray;
                } else {
                    $preprocessed = array($inputArray[0], $inputArray[1], $inputArray[2]);
                    if (count($inputArray) > 2) {
                        array_shift($inputArray);
                        array_shift($inputArray);
                        array_shift($inputArray);

                        $itm = explode("*0", implode("*", $inputArray));
                        $finalindex = $itm[sizeof($itm) - 1];
                        $array = explode("*", trim($finalindex));
                        foreach ($array as $a) {
                            if (!empty($a)) {
                                array_push($preprocessed, $a);
                            }
                        }
                    }
                }
            }

            $inputArray = array();
            $inputArray  = $preprocessed;

            //print_r($inputArray);

            $uexists = $this->usersmodel->get(array('UserCode' => $MSISDN, 'Usertype' => "retailer", 'recordstate' => 0));
            if ($uexists->num_rows() > 0) {
                if (count($inputArray) == 2) {
                    if ($lastInput == 2) {
                        $data = $this->reset_password($MSISDN);
                        $array = json_decode($data);
                        if (strtolower($array->result) == "success") {
                            $response = "END Your pin has been reset. Check your SMS for the new pin.";
                        } else {
                            $response = "END Could not reset pin. Please try again.";
                        }
                    } else
                        $response = "CON Enter your pin";
                } else if (count($inputArray) == 3) {
                    //login
                    $data = $this->oauth($MSISDN, $inputArray[2], "retailer");
                    $array = json_decode($data);
                    if (strtolower($array->result) == "success")
                        $response = "CON " . ucfirst($array->fname) . ", please select an option\n1.Change PIN\n2.Redeem\n3.Check points balance\n4.Cancel";
                    else
                        $response = "END " . ucfirst($array->message);
                } else if (count($inputArray) >= 3) {
                    //account logged in and normal operations are available.
                    if ($inputArray[3] == 1) {
                        //change password
                        if ($lastInput == 1)
                            $response = "CON Enter your new PIN.";
                        else {
                            $resp = json_decode($this->change_password($MSISDN, $lastInput));
                            $response = "END Your PIN has been changed. \nPlease login with your new pin.";
                        }
                    } else if ($inputArray[3] == 3) {
                        $mbal = 0;
                        $balance = json_decode($this->check_balance($MSISDN, ""));

                        if (strtolower($balance->result) == "success") {
                            $mbal = "";
                            $obs = $balance->data;
                            $response = "CON Your point balance is " . number_format($obs->points, 2) . " worth KSH " .  number_format($obs->points, 2);
                        } else
                            $response = "CON Your  balance is 0 points.";
                        $response .= "\n0 Go back";
                    } else if ($inputArray[3] == 4) {
                        $response = "END Thank you for participating in the " . APP_NAME;
                    } else if ($inputArray[3] == 2) {
                        //redemption goes here
                        $partners = $this->cmerchantmodel->get(array('record_state' => 0, 'ussd_state' => '1'));
                        $list = $partners->result_array();

                        sort($list);
                        if ($partners->num_rows() > 0) {
                            //partlers are available
                            if (sizeof($inputArray) == 4) {
                                //list the partners for customer search
                                $index = 1;
                                $response = "CON Select redemption partner\n";
                                foreach ($list as $row) {
                                    $response .= $index . ". " . $row['name'] . "\n";
                                    $index++;
                                }
                                $response .= "0. Go Back\n";
                            }

                            if (sizeof($inputArray) == 5) {
                                //selected partner..listing redemption units
                                $selectedIndex = $lastInput - 1;
                                $response = "CON Amount to redeem\n";
                                $units = $this->cunitsmodel->get(array('dmo_id' => $list[$selectedIndex]['dmo_id'], 'type' => 'fixed'));
                                $index = 1;
                                $list = $units->result_array();
                                $kshs = $this->redeemsmodel->get(array('item' => 'Redemption Rate KSH', 'record_state' => 0));
                                $redeemval = 0;
                                if ($kshs->num_rows() > 0) {
                                    $redeemval = $kshs->row()->value;
                                }

                                foreach ($list as $row) {
                                    $response .= $index . ". Ksh " . $row['value'] . ($redeemval > 0 ? " for " . number_format($row['value'] / $redeemval, 0) . " point(s)" : "") . "\n";
                                    $index++;
                                }
                            }

                            if (sizeof($inputArray) == 6) {
                                //selected unit..getting amount to redeem.
                                $selectedPartner = $inputArray[4] - 1;
                                $partners = $this->cmerchantmodel->get(array('record_state' => 0, 'ussd_state' => '1'));
                                $list = $partners->result_array();
                                sort($list);
                                $list = $list[$selectedPartner];

                                $selectedIndex = $lastInput - 1;
                                $units = $this->cunitsmodel->get(array('dmo_id' => $list['dmo_id'], 'type' => 'fixed'));
                                $ulist = $units->result_array()[$selectedIndex];

                                //$u = $this->redeemCrossIndustry($MSISDN, $ulist['value'], $ulist['dmo_id']);
                                //print_r($u);

                                $response = "";
                                $redeem = json_decode($this->redeemCrossIndustry($MSISDN, $ulist['value'], $ulist['dmo_id']));
                                if ($redeem->result == 'success') {
                                    $response = "CON Redemption successfull.Voucher code: " . $redeem->code . ".Check SMS for details (0 Go back)";
                                } else
                                    $response = "CON " . $redeem->message . ". (0 Go back)";
                            }

                            if (sizeof($inputArray) > 6)
                                $response = "CON Redemption is currently unavailable.Please try again later. (0 Go back)";
                        } else
                            $response = "CON Redemption is currently unavailable.Please try again later. (0 Go back)";
                    } else
                        $response = "END Thank you for showing interest in " . APP_NAME;
                }
            } else {
                $regions = array(
                    array(19, 'NAIROBI'), array(20, 'COAST'), array(21, 'MT KENYA'), array(22, 'EASTERN '), array(23, 'SOUTH RIFT'),
                    array(24, 'NORTH RIFT'), array(25, 'WESTERN'), array(26, 'NYANZA'), array(27, 'SOUTH NYANZA '), array(28, 'NORTH EASTERN')
                );

                //registration goes here.   && count($inputArray)==2
                if ($lastInput == 2 && count($inputArray) == 2)
                    $response = "END Thank you for expressing interest in " . APP_NAME;
                else {

                    if (count($inputArray) == 2)
                        $response = "CON Enter account type\n1. Retailer\n2. Fundi / End User";
                    else if (count($inputArray) > 2) {
                        if ($inputArray[2] == 1) {
                            if (count($inputArray) == 3)
                                $response = "CON Enter Business name (Step 1 of 6)";
                            else if (count($inputArray) == 4) {
                                $fname = $inputArray[3];
                                if (!preg_match("/([A-Za-z']){3,10}/", $fname))
                                    $response = "CON Enter a valid first name.\n0. Go back";
                                else
                                    $response = "CON Enter First name (Step 2 of 6)";
                            } else if (count($inputArray) == 5) {
                                $sname = $inputArray[4];
                                if (!preg_match("/([A-Za-z']){3,10}/", $sname))
                                    $response = "CON Enter a valid second name.\n0. Go back";
                                else
                                    $response = "CON Enter Second name (Step 3 of 6)";
                            } else if (count($inputArray) == 6)
                                $response = "CON Enter business location (Step 4 of 6)";
                            else if (count($inputArray) == 7) {
                                $response = "CON Select Region (Step 5 of 6)\n";
                                $i = 1;
                                foreach ($regions as $r) {
                                    $response .= $i . ". " . $r[1] . "\n";
                                    $i++;
                                }
                            } else if (count($inputArray) == 8) {
                                $response = "CON Select County (Step 6 of 6)\n";
                                $region = $inputArray[7];
                                $region -= 1;
                                $r = $regions[$region];
                                $counties = $this->countiesmodel->get(array('region' => $r[0]));
                                $j = 1;
                                foreach ($counties->result_array() as $m) {
                                    $response .= $j . ". " . $m['countyName'] . "\n";
                                    $j++;
                                }
                            } else if (count($inputArray) > 8) {

                                $region = $inputArray[7];
                                $region = $region - 1;
                                $r = $regions[$region];
                                $counties = $this->countiesmodel->get(array('region' => $r[0]));
                                $k = $inputArray[8];
                                $k -= 1;
                                $cid = $counties->result_array()[$k];

                                $phone = $MSISDN;
                                $bsnname = $inputArray[3];
                                $fname = $inputArray[4];
                                $sname = $inputArray[5];
                                $loc = $inputArray[6];
                                $region = $r[0];
                                $county = $cid['id'];
                                $distcode = "";

                                $data = $this->enroll_retailer($phone, $bsnname, $fname, $sname, $loc, $region, $county, $distcode, "");
                                $array = json_decode($data);
                                if (strtolower($array->result) == "ok") {
                                    $response = "END Your have been registered on the loyalty program. Check your SMS for pin.";
                                } else {
                                    $response = "END " . ucfirst($array->message);
                                }

                                /*$ot = $this->outletsmodel->get(array('CUST_CD' => $distcode, 'DIST_CD' => 'Distributor', 'record_state' => 0));

                                if ($ot->num_rows() > 0) {
                                   $dist = $ot->row();

                                    if ($dist->OBOS == 1 && count($inputArray) == 10) {
                                        $response = "CON Enter your customer code (Final step)";
                                    } else if ((($dist->OBOS == 0 || empty($dist->OBOS)) && count($inputArray) == 10) ||  count($inputArray) == 11) {
                                        $code = "";
                                        if (count($inputArray) == 11)
                                            $code = $inputArray[10];

                                        $ct = $this->outletsmodel->get(array('CUST_CD' => $code, 'DIST_CD' => 'Retailer', 'record_state' => 0));
                                        if (!empty($code) && $ct->num_rows() > 0)
                                            $response = "END Failed to register. Customer code already exists in the system.";
                                        else {
                                            $data = $this->enroll_retailer($phone, $bsnname, $fname, $sname, $loc, $region, $county, $distcode, $code);
                                            $array = json_decode($data);
                                            if (strtolower($array->result) == "ok") {
                                                $response = "END Your have been registered on the loyalty program. Check your SMS for pin.";
                                            } else {
                                                $response = "END " . ucfirst($array->message);
                                            }
                                        }
                                    //}
                                } else {
                                    $response = "END Failed to register. Distributor code entered is not valid.";
                                }*/
                            } else
                                $response = "END Could not register you to the loyalty program. Please try again.";
                        } else {
                            if (count($inputArray) == 3)
                                $response = "CON Enter First name (Step 1 of 5)";
                            else if (count($inputArray) == 4) {
                                $fname = $inputArray[3];
                                if (!preg_match("/([A-Za-z']){3,10}/", $fname))
                                    $response = "CON Enter a valid first name.\n0. Go back";
                                else
                                    $response = "CON Enter Second name (Step 2 of 5)";
                            } else if (count($inputArray) == 5) {
                                $sname = $inputArray[4];
                                if (!preg_match("/([A-Za-z']){3,10}/", $sname))
                                    $response = "CON Enter a valid second name.\n0. Go back";
                                else
                                    $response = "CON Enter location where you are based (Step 3 of 5)";
                            } else if (count($inputArray) == 6) {
                                $response = "CON Select Region (Step 4 of 5)\n";
                                $i = 1;
                                foreach ($regions as $r) {
                                    $response .= $i . ". " . $r[1] . "\n";
                                    $i++;
                                }
                            } else if (count($inputArray) == 7) {
                                $response = "CON Select County (Step 5 of 5)\n";
                                $region = $inputArray[6];
                                $region -= 1;
                                $r = $regions[$region];
                                $counties = $this->countiesmodel->get(array('region' => $r[0]));
                                $j = 1;
                                foreach ($counties->result_array() as $m) {
                                    $response .= $j . ". " . $m['countyName'] . "\n";
                                    $j++;
                                }
                            } else if (count($inputArray) > 7) {
                                $region = $inputArray[6];
                                $region = $region - 1;
                                $r = $regions[$region];
                                $counties = $this->countiesmodel->get(array('region' => $r[0]));
                                $k = $inputArray[7];
                                $k -= 1;
                                $cid = $counties->result_array()[$k];

                                $phone = $MSISDN;
                                $fname = $inputArray[3];
                                $sname = $inputArray[4];
                                $loc = $inputArray[5];
                                $region = $r[0];
                                $county = $cid['id'];
                                $bsnname = $fname . " " . $sname;
                                $distcode = "";

                                $data = $this->enroll_retailer($phone, $bsnname, $fname, $sname, $loc, $region, $county, $distcode, "");
                                $array = json_decode($data);
                                if (strtolower($array->result) == "ok") {
                                    $response = "END Your have been registered on the loyalty program. Check your SMS for pin.";
                                } else {
                                    $response = "END " . ucfirst($array->message);
                                }

                                /*$ot = $this->outletsmodel->get(array('CUST_CD' => $distcode, 'DIST_CD' => 'Distributor', 'record_state' => 0));

                                if ($ot->num_rows() > 0) {
                                    $dist = $ot->row();

                                    if ($dist->OBOS == 1 && count($inputArray) == 9) {
                                        $response = "CON Enter your customer code (Final step)";
                                    } else if ((($dist->OBOS == 0 || empty($dist->OBOS)) && count($inputArray) == 9) ||  count($inputArray) == 10) {
                                        $code = "";
                                        if (count($inputArray) == 10)
                                            $code = $inputArray[9];

                                        $ct = $this->outletsmodel->get(array('CUST_CD' => $code, 'DIST_CD' => 'Retailer', 'record_state' => 0));
                                        if (!empty($code) && $ct->num_rows() > 0)
                                            $response = "END Failed to register. Customer code already exists in the system.";
                                        else {
                                            $data = $this->enroll_retailer($phone, $bsnname, $fname, $sname, $loc, $region, $county, $distcode, $code);
                                            $array = json_decode($data);
                                            if (strtolower($array->result) == "ok") {
                                                $response = "END Your have been registered on the loyalty program. Check your SMS for pin.";
                                            } else {
                                                $response = "END " . ucfirst($array->message);
                                            }
                                        }
                                    }
                                } else {
                                    $response = "END Failed to register. Distributor code entered is not valid.";
                                }*/
                            } else
                                $response = "END Could not register you to the loyalty program. Please try again.";
                        }
                    }
                }
            }
        }
        //print out the response 
        header('Content-type: text/plain');
        echo $response;

        /* 
         if (count($inputArray) == 4) {
                            $response = "CON Redeem :\n1. Redeem Airtime\n2. Redeem for KPLC"; 
                            if (CROSS_INDUSTRY)
                                $response .= "\n3. External Redemption";
                        } else if (count($inputArray) == 5) {
                            //if ($lastInput == 1)
                            //    $response = "CON Enter the redemption code (Code of premises you are redeeming from).";
                            //else 
                            if($lastInput == 1) {
                                $response = "CON Provider:\n1. Safaricom\n2. Airtel"; //\n3. Orange\n4. Yu
                            } else if($lastInput == 2){
                                $response = "CON Account Type :\n1. KPLC Prepaid (tokens)\n2. KPLC Bill";
                            } else {
                                //cross industry
                                //curl to cross industry!!!
                                $m = $this->cmerchantmodel->get(array('record_state' => 0, 'isexternal' => '1'));
                                $u = "";
                                foreach ($m->result_array() as $k)
                                    $u .=  $k['ussdcode'] . ". " . $k['name'] . "\n"; 
                                $response = "CON Choose redemption partner.\n" . $u;
                            }
                        }* else if (count($inputArray) == 6 && $inputArray[4] == 1) {
                            //internal redemption - added redemption partner code
                            $balance = json_decode($this->check_balance($MSISDN, ""));
                            if (strtolower($balance->result) == "success" && $balance->data->points > 0) {
                                $obs = $balance->data;
                                $response = "CON Your point balance is " . number_format($obs->points, 2) . " worth KSH " .  number_format($obs->pointsksh, 2) . " @ KSH " . number_format($obs->pointsksh / $obs->points, 2)  . " per point\nHow many points do you want to redeem?";
                            } else
                                $response = "CON Your  balance is 0 points.\nYou have insufficient balance to redeem.\n0. Go back";
                        } else if (count($inputArray) == 7 && $inputArray[4] == 1) {
                            //internal redemption proceed to redemption.
                            $balance = json_decode($this->check_balance($MSISDN, ""));
                            $amount = $lastInput * ($balance->data->pointsksh / $balance->data->points);
                            if ($balance->data->pointsksh < $amount)
                                $response = "CON You have insufficient balance to redeem.\n0. Go back";
                            else {
                                $agentcode =  $inputArray[5];
                                $resp = json_decode($this->redeem($MSISDN, $amount, $agentcode));
                                if (strtolower($resp->result) == "success") {
                                    $response = "END Redemption successful. Use the following code " . $resp->code;
                                } else
                                    $response = "CON Failed to redeem." . $resp->message . "\n0 Go back";
                            }
                        } *else if (count($inputArray) == 6 && $inputArray[4] == 3) {
                            //cross industry redemption - added redemption partner code
                            $balance = json_decode($this->check_balance($MSISDN, ""));
                            if (strtolower($balance->result) == "success" && $balance->data->points > 0) {
                                $obs = $balance->data;

                                $redemptionpartner = $inputArray[5];
                                $m = $this->cmerchantmodel->get(array('record_state' => 0, 'isexternal' => '1', 'ussdcode' => $redemptionpartner));
                                if ($m->num_rows() > 0) {
                                    $dmoid = $m->row()->dmo_id;
                                    $m = $this->cunitsmodel->get(array('type' => 'fixed', 'value <=' => $balance->data->pointsksh, 'dmo_id' => $dmoid));

                                    $u = "";
                                    $i = 1;
                                    foreach ($m->result_array() as $k) {
                                        $u .=  $i . ". " . $k['value'] . "\n";
                                        $i++;
                                    }

                                    $response = "CON Choose Voucher amount (KSH).\n" . $u;
                                } else
                                    $response = "CON Enter a correct redemption point.\n0. Go back";
                            } else
                                $response = "CON Your  balance is 0 points.\nYou have insufficient balance to redeem.\n0. Go back";
                        } else if (count($inputArray) == 7 && $inputArray[4] == 3) {
                            //Cross industry redemption proceed to redemption.
                            $redemptionpartner = $inputArray[5];
                            $amountindex = $inputArray[6];
                            $balance = json_decode($this->check_balance($MSISDN, ""));

                            $m = $this->cmerchantmodel->get(array('record_state' => 0, 'isexternal' => '1', 'ussdcode' => $redemptionpartner))->row();
                            $dmoid = $m->dmo_id;
                            $agentcode = $m->merchantcode;
                            $m = $this->cunitsmodel->get(array('type' => 'fixed', 'value <=' => $balance->data->pointsksh, 'dmo_id' => $dmoid));

                            if ($m->num_rows() > 0) {
                                $balindex = $m->result_array()[$amountindex - 1];
                                $amount = $balindex['value'];

                                if ($balance->data->pointsksh < $amount)
                                    $response = "CON You have insufficient balance to redeem.\n0. Go back";
                                else { 
                                    $resp = json_decode($this->redeemCrossIndustry($MSISDN, $amount, $agentcode));
                                    if (strtolower($resp->result) == "success") {
                                        $response = "END Redemption successful. Use the following voucher code " . $resp->code;
                                    } else
                                        $response = "CON Failed to redeem." . $resp->message . "\n0 Go back";
                                }
                            } else
                                $response = "CON You have entered an invalid redemption amount.\n0 Go back";
                        } else if ( $inputArray[4] == 1) {
                            //Buy credit. 
                            $operators = ['Safaricom','Airtel']; //,'Orange','Yu' 
                            if (count($inputArray) == 6) {
                                $response = "CON Enter airtime amount\n";
                            } else if (count($inputArray) == 7) {
                                $amount = $inputArray[6];
                                $operator = $operators[$inputArray[5]-1];
    
                                $balance = json_decode($this->check_balance($MSISDN, ""));
                                if (strtolower($balance->result) == "success" && $balance->data->points > 0 ) {
                                    $obs = $balance->data; 
                                    if($obs->pointsksh>=$amount){  
                                        $r = $this->send_credit($amount,$MSISDN,$operator); 
                                        $tstatus = $r->transaction; 
                                        if($tstatus->status == 1)
                                            $response = "CON Redemption successful. Your credit will be topped up instantly.\n0. Go back";
                                        else
                                            $response = "CON Could not buy the specified amount. Please try again.\n0. Go back";
                                    } else 
                                    $response = "CON You have insufficient balance to buy airtime.\n0. Go back";
                                } else
                                    $response = "CON Your  balance is 0 points.\nYou have insufficient balance to buy airtime.\n0. Go back";
                            
                            } else
                            $response = "CON Sorry could not buy credit.Try again later\n0. Go back";
                        } else if ( $inputArray[4] == 2) {
                            //Buy kplc
                            if (count($inputArray) == 6) {
                                $response = "CON Amount to pay\n";
                            } else if (count($inputArray) == 7) {
                                $response = "CON Account / Meter Number.\n";
                            } else if (count($inputArray) ==8 ) { 
                                $amount = $inputArray[6];
                                $account = $inputArray[7];
    
                                $balance = json_decode($this->check_balance($MSISDN, ""));
                                if (strtolower($balance->result) == "success" && $balance->data->points > 0 ) {
                                    $obs = $balance->data; 
                                    if($obs->pointsksh>=$amount){ 
                                        if($inputArray[5]==1){
                                            $token = $this->kplc_bill($account,$amount,$MSISDN); 
                                            $token = json_decode($token);
                                            $response = "CON ".$token->data."\n0. Go back";
                                        } else {
                                            $token = $this->kplc_bill_only($account,$amount,$MSISDN);
                                            $token = json_decode($token);
                                            $response = "CON ".$token->data."\n0. Go back";
                                        }
                                    } else 
                                    $response = "CON You have insufficient balance to redeem for KPLC bill.\n0. Go back";
                                } else
                                    $response = "CON You have insufficient balance to redeem for KPLC bill.\n0. Go back";
         */
    }
}
