<?php
$page_security = 'SA_SETUPCOMPANY';
$path_to_root = "../..";
include($path_to_root . "/includes/session.inc");

page(_($help_context = "MPesa Setup"));
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/admin/db/company_db.inc");

//-------------------------------------------------------------------------------------------------
// initialize stuff just in case
$init = 0;
if (get_company_pref('mpesa_api') === null) {
    set_company_pref('mpesa_api', 'system.external', 'varchar', 100, '');
    $init++;
}

if (get_company_pref('mpesa_api_bank_account') === null) {
    set_company_pref('mpesa_api_bank_account', 'system.external', 'varchar', 5, '');
    $init++;
}

if (get_company_pref('mpesa_api_shortcode') === null) {
    set_company_pref('mpesa_api_shortcode', 'system.external', 'varchar', 10, '');
    $init++;
}

if (get_company_pref('mpesa_api_customer_key') === null) {
    set_company_pref('mpesa_api_customer_key', 'system.external', 'varchar', 150, '');
    $init++;
}

if (get_company_pref('mpesa_api_customer_secret') === null) {
    set_company_pref('mpesa_api_customer_secret', 'system.external', 'varchar', 150, '');
    $init++;
}

if (get_company_pref('mpesa_api_validation_url') === null) {
    set_company_pref('mpesa_api_validation_url', 'system.external', 'varchar', 150, '');
    $init++;
}

if (get_company_pref('mpesa_api_confirmation_url') === null) {
    set_company_pref('mpesa_api_confirmation_url', 'system.external', 'varchar', 150, '');
    $init++;
}

//if ($init)
//    refresh_sys_prefs();

function can_process() {
    $errors = 0;
    return ($errors == 0);
}

//-------------------------------------------------------------------------------------------------

if (isset($_POST['submit']) && can_process()) {
    update_company_prefs(get_post(array('mpesa_api', 'mpesa_api_bank_account', 'mpesa_api_shortcode', 'mpesa_api_customer_key', 'mpesa_api_customer_secret', 'mpesa_api_validation_url', 'mpesa_api_confirmation_url')));

    display_notification(_("MPesa Settings have been saved."));
} else if (isset($_POST['register_urls']))  {
    //get auth tokem
        $url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        $credentials = base64_encode(get_company_pref('mpesa_api_customer_key').':'.get_company_pref('mpesa_api_customer_secret'));
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); //setting a custom header
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $curl_response = curl_exec($curl);
        $access_token = json_decode($curl_response)->access_token;

        //reqister urls
        $url = 'https://api.safaricom.co.ke/mpesa/c2b/v1/registerurl';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Authorization:Bearer '.$access_token)); //setting custom header
        $curl_post_data = array(
            //Fill in the request parameters with valid values
            'ShortCode' => get_company_pref('mpesa_api_shortcode'),
            'ResponseType' => 'Completed',
            'ConfirmationURL' => get_company_pref('mpesa_api_confirmation_url'),
            'ValidationURL' => get_company_pref('mpesa_api_validation_url')
        );
        $data_string = json_encode($curl_post_data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
        $curl_response = curl_exec($curl);
        display_notification($curl_response);
        $reg_response = json_decode($curl_response);
}

$prefs = get_company_prefs();
$_POST['mpesa_api'] = $prefs['mpesa_api'];
$_POST['mpesa_api_bank_account'] = $prefs['mpesa_api_bank_account'];
$_POST['mpesa_api_shortcode'] = $prefs['mpesa_api_shortcode'];
$_POST['mpesa_api_customer_key'] = $prefs['mpesa_api_customer_key'];
$_POST['mpesa_api_customer_secret'] = $prefs['mpesa_api_customer_secret'];
$_POST['mpesa_api_validation_url'] = $prefs['mpesa_api_validation_url'];
$_POST['mpesa_api_confirmation_url'] = $prefs['mpesa_api_confirmation_url'];
//-------------------------------------------------------------------------------------------------

start_form();

div_start('details');
start_table(TABLESTYLE2);

$Ajax->activate('_page_body');
array_selector_row(_("MPesa API:"), 'mpesa_api', $_POST['mpesa_api'], array('CustomerPayBillOnline' => _("CustomerPayBillOnline"), 'CustomerBuyGoodsOnline' => _("CustomerBuyGoodsOnline")));
bank_accounts_list_cells(_("MPesa Bank Account:"), 'mpesa_api_bank_account', $_POST['mpesa_api_bank_account'],FALSE);
text_row(_("Shortcode:"), 'mpesa_api_shortcode', $_POST['mpesa_api_shortcode'], 70, 150);
text_row(_("Customer Key:"), 'mpesa_api_customer_key', $_POST['mpesa_api_customer_key'], 70, 150);
text_row(_("Customer Secret:"), 'mpesa_api_customer_secret', $_POST['mpesa_api_customer_secret'], 70, 150);
text_row(_("Validation URL:"), 'mpesa_api_validation_url', $_POST['mpesa_api_validation_url'], 70, 150);
text_row(_("Confirmation URL:"), 'mpesa_api_confirmation_url', $_POST['mpesa_api_confirmation_url'], 70, 150);

end_table(1);
div_end();

echo '<center>';
submit('submit', _("Update"), true, '', 'default');
echo "&nbsp;";
echo "&nbsp;";
submit('register_urls', _(" Register Validation & Confirmation URLs"), true, '', 'default');
echo '</center>';
end_form(2);
echo "<hr>";

//-------------------------------------------------------------------------------------------------

end_page();
?>
