#include "coregrade_api_main.h"
#include "coregrade_api.h"
#include "clog.h"
#include "input.h"
#include "interswitch_sendmoney.h"
#include "pgsql.h"
#include "email.h"
#include "account.h"
#include "groups.h"
#include "topups.h"
#include "storeface.h"
#include "pgsql_wrapper.h"

//extern CSQL  *sql;

long coregrade_api_main(CVars in, CVars &out) {
    logfmt(logINFO, "SystemStatus()09-09-********~************");

    // SystemStatus();
    CVars recipient;
    CVars cust;
    CVars xx;

    long maxAirtime = 0;
    int r;
    char ptid[180];
    char xtid[12];
    //int channel_code = 3;

    //out = in;

    logfmt(logINFO, "long coregrade_api_main(CVars in, CVars &out)");
    long retval = PHP_API_BAD_PARAM;
    long action = REQ_LONG(in, "action", 0, -1);
    logfmt(logINFO, "long coregrade_api_main(CVars in, CVars &out) action =%lu", action);

    if (action >= COREGRADE_ACCOUNT_START && action <= COREGRADE_ACCOUNT_END) {
        logfmt(logINFO, "account calls");
        return account_calls(in, out);
    }

    if (action >= COREGRADE_GROUP_START && action <= COREGRADE_GROUP_END) {
        logfmt(logINFO, "groups calls");
        return groups_calls(in, out);
    }

    switch (action) {

        default: out["status"] = "Unknown action";
    }




    switch (action) {
        case COREGRADE_LOG_ENTRY:
            out = in;
            insert_db_record(DBS_VALID, "raw_message", "raw_message_id_seq", in);
            break;

        case COREGRADE_SESSION_CHECK:
            retval = account_session_check(in, out);
            break;

        case 1000000055:
            //bonus_balance.mailfile
            return CustomerBalanceBonusEmail(in);
            break;

        case COREGRADE_ADD_MOBILE_TOPUPNUM:
            return AddMobileTopuNumber(in, out);
            break;

        case COREGRADE_PROMO_CALL:
            REQ_LONG(in, "pmode", 1, -1);
            REQ_LONG(in, "customer_id", 1, -1);
            REQ_LONG(in, "pro_id", 1, -1);

            if (load_db_record(out, "SELECT p.id,c.email,c.firstname,c.lastname FROM promotion p LEFT JOIN customer c ON c.id=p.customer_id WHERE p.promo%lu IS NULL AND p.id=%lu", in["pmode"].Long(), in["pro_id"].Long())) {
                out["pmode"] = in["pmode"];
                out["pmode"].set_valid(true);
                pgsql_exec("UPDATE promotion SET promo%lu = now() WHERE id = %lu ", out["pmode"].Long(), in["pro_id"].Long());

                SendPromoEmail(out);
                out["status"] = "I passed this point";
            }

            break;



        case COREGRADE_PAYPAL_IPNMSG:
            /*
 CREATE TABLE ipn_message (
      id serial NOT NULL,
          payment_date TIMESTAMP,
          mc_currency character varying(5) ,
          last_name character varying(100) ,
          first_name character varying(100),
          payer_email character varying(100),
      receiver_email character varying(100),
          payer_id character varying(50),
          receiver_id character varying(50),
          txn_id character varying(50),
          item_number character varying(25), 
          item_name character varying(100),	  
          payment_gross float,
          mc_gross float,	 
          ipn_track_id character varying(100), 
          status integer DEFAULT 1, 
          added TIMESTAMP DEFAULT NOW()
 );
             */
            out["ipn_id"] = "0";

            if (load_db_record(out, "SELECT id AS ipn_id FROM ipn_message WHERE txn_id = '%s'", in["txn_id"].c_str())) {
                out["status"] = "I passed this point";
            } else {

            }

            if (out["ipn_id"].Long() == 0) {
                xx["payment_date"] = in["payment_date"];
                xx["payment_date"].set_valid(true);
                xx["mc_currency"] = in["mc_currency"];
                xx["mc_currency"].set_valid(true);
                xx["last_name"] = in["last_name"];
                xx["last_name"].set_valid(true);
                xx["first_name"] = in["first_name"];
                xx["first_name"].set_valid(true);
                xx["payer_email"] = in["payer_email"];
                xx["payer_email"].set_valid(true);
                xx["receiver_email"] = in["receiver_email"];
                xx["receiver_email"].set_valid(true);
                xx["payer_id"] = in["payer_id"];
                xx["payer_id"].set_valid(true);
                xx["receiver_id"] = in["receiver_id"];
                xx["receiver_id"].set_valid(true);
                xx["txn_id"] = in["txn_id"];
                xx["txn_id"].set_valid(true);
                xx["item_number"] = in["item_number"];
                xx["item_number"].set_valid(true);
                xx["item_name"] = in["item_name"];
                xx["item_name"].set_valid(true);
                xx["payment_gross"] = in["payment_gross"];
                xx["payment_gross"].set_valid(true);
                xx["mc_gross"] = in["mc_gross"];
                xx["mc_gross"].set_valid(true);
                xx["ipn_track_id"] = in["ipn_track_id"];
                xx["ipn_track_id"].set_valid(true);
                insert_db_record(DBS_VALID, "ipn_message", "ipn_message_id_seq", xx);
            }


            return 0;

            break;

        case COREGRADE_COMPLETE_ADDMONEY:
            REQ_LONG(in, "request_id", 1, -1);
            REQ_LONG(in, "customer_id", 1, -1);
            REQ_LONG(in, "csr_id2", 1, -1);
            REQ_LONG(in, "status", 1, -1);
            REQ_STRING(in, "ip2", 1, 20, "(.*)");

            if (in["status"] == APPROVED_BALANCE) {

                if (load_db_record(out, " SELECT c.*,c.amount AS prop_amount,cc.balance AS curr_balance FROM customer_addbalance c LEFT JOIN customer cc ON cc.id=c.customer_id WHERE c.status = 1 AND c.id = %lu AND c.customer_id = %lu", in["request_id"].Long(), in["customer_id"].Long())) {
                    pgsql_exec("UPDATE customer SET balance = balance + %lu WHERE id = %lu ", out["prop_amount"].Long(), out["customer_id"].Long());
                    load_db_record(out, "SELECT balance AS fin_balance FROM customer WHERE id=%lu", out["customer_id"].Long());
                    pgsql_exec("UPDATE customer_addbalance SET status=%d,completed= now(),ip2='%s',csr_id2=%lu,cur_balance =%lu,fin_balance= %lu WHERE id = %lu ", APPROVED_BALANCE, in["ip2"].c_str(), in["csr_id2"].Long(), out["curr_balance"].Long(), out["fin_balance"].Long(), in["request_id"].Long());
                    out["result"] = "Completed";
                    SendBalanceCompleteAlert(in);
                } else {
                    out["result"] = "Invalid call for approval";
                }


            }

            if (in["status"] == DISAPROVE_BALANCE) {


            }

            /*
             $inx["request_id"] = $request_id;
   $inx["customer_id"] = $customer_id;
   $inx["csr_id2"] = $csr_id2; 
   $inx["status"] = APPROVED_BALANCE;
   $inx["action"] = COREGRADE_COMPLETE_ADDMONEY;
             */
            break;

        case COREGRADE_START_ADDMONEY:

            REQ_LONG(in, "customer_id", 1, -1);
            REQ_LONG(in, "csr_id", 1, -1);
            REQ_LONG(in, "amount", 1, -1);
            REQ_STRING(in, "ip", 1, 20, "(.*)");

            xx["customer_id"] = in["customer_id"];
            xx["customer_id"].set_valid(true);
            xx["csr_id"] = in["csr_id"];
            xx["csr_id"].set_valid(true);
            xx["amount"] = in["amount"];
            xx["amount"].set_valid(true);
            xx["ip"] = in["ip"];
            xx["ip"].set_valid(true);
            out["request_id"] = insert_db_record(DBS_VALID, "customer_addbalance", "customer_addbalance_id_seq", xx);
            if (out["request_id"].Long() > 0) {
                in["request_id"] = out["request_id"];
                in["request_id"].set_valid(true);
                SendBalanceRequestAlert(in);
            }

            break;



        case COREGRADE_COMPLETE_PASSWORDRESET:
            REQ_STRING(in, "reset_link", 1, 100, "(.*)");
            REQ_STRING(in, "newpass", 1, 20, "(.*)");
            if (load_db_record(out, "SELECT l.id AS lostpass_id,c.firstname,c.lastname,c.email,l.customer_id,c.username FROM lostpass l LEFT JOIN customer c ON c.id = l.customer_id  WHERE l.reset_link = '%s' AND l.status  IN (1,3)", in["reset_link"].c_str())) {
                pgsql_exec("UPDATE lostpass SET status = 5 WHERE status IN (1,3) AND customer_id=%lu AND id = %lu ", out["customer_id"].Long(), out["lostpass_id"].Long());

                pgsql_exec("UPDATE customer SET pass =md5('%s')  WHERE id = %lu  ", in["newpass"].c_str(), out["customer_id"].Long());
                //complete_losspass.mailfile
                CompletePassResetEmail(out);
            } else {
                out["status_message"] = "Pass Reset Failed";
            }

            break;

        case COREGRADE_START_PASSWORDRESET:
            REQ_STRING(in, "email", 1, 100, "(.*)");
            if (load_db_record(out, "SELECT id as customer_id,* FROM customer WHERE LOWER(email)=LOWER('%s') AND status=1", in["email"].c_str())) {
                xx["customer_id"] = out["id"];
                xx["customer_id"].set_valid(true);
                srand(time(NULL));
                r = abs(rand()*100000000);
                sprintf(ptid, "RS-%09lu-%08lu", out["id"].Long(), r);
                xx["reset_link"] = ptid;
                xx["reset_link"].set_valid(true);
                xx["loc"] = in["loc"];
                xx["loc"].set_valid(true);
                out["reset_id"] = insert_db_record(DBS_VALID, "lostpass", "lostpass_id_seq", xx);
                if (out["reset_id"].Long() > 0) {
                    pgsql_exec("UPDATE lostpass SET status = 777 WHERE status IN (1,2,3) AND customer_id=%lu AND id <> %lu ", out["customer_id"].Long(), out["reset_id"].Long());

                    pgsql_exec("UPDATE lostpass SET expire = now() + '15 minutes' WHERE id=%lu ", out["reset_id"].Long());
                    StartPassResetEmail(out);
                }
            }
            break;

        case COREGRADE_BULKTOPUP_ORDER:
            return CreateBulkTopupBatch(in, out);
            break;

        case COREGRADE_BULKTOPUP_ITEM:
            return AddBulkTopupBatchItem(in, out);
            break;

        case COREGRADE_BULKTOPUP_ITEMUPDATE:
            return UpdateBulkTopupItem(in, out);
            break;

        case COREGRADE_BULKTOPUP_DELIVER:
            return DeliverBulkTopupItem(in, out);
            break;

        case COREGRADE_CREATE_USER_ACCOUNT:

            out = in;
            REQ_STRING(in, "firstname", 1, 50, "(.*)");
            REQ_STRING(in, "lastname", 1, 50, "(.*)");
            REQ_STRING(in, "email", 1, 100, "(.*)");
            REQ_STRING(in, "pass", 5, 12, "(.*)");
            REQ_STRING(in, "username", 1, 100, "(.*)");

            OPTIONAL(in, "country")
            REQ_STRING(in, "country", 1, 4, "(.*)");


            cust["firstname"] = in["firstname"];
            cust["firstname"].set_valid(true);
            cust["lastname"] = in["lastname"];
            cust["lastname"].set_valid(true);
            cust["email"] = in["email"];
            cust["email"].set_valid(true);
            cust["pass"] = in["pass"];
            cust["pass"].set_valid(true);
            cust["username"] = in["username"];
            cust["username"].set_valid(true);
            cust["country"] = in["country"];
            cust["country"].set_valid(true);


            out["user_id"] = insert_db_record(DBS_VALID, "customer", "customer_id_seq", cust);
            if (out["user_id"].Long() > 0) {
                pgsql_exec("UPDATE customer SET pass=md5('%s') WHERE id=%lu AND username='%s'", cust["pass"].c_str(), out["user_id"].Long(), cust["username"].c_str());
                SendAccountCreateAlert(out["user_id"].Long());
                CustomerEmailWelcome(out);
            }

            break;


            //#define COREGRADE_BALANCE_TOPUP_ORDER      800020
            //#define COREGRADE_BALANCE_TOPUP_PURCHASE	  800030
        case COREGRADE_BALANCE_TOPUP_PAYMENT:
            REQ_STRING(in, "orderid", 1, 50, "(.*)");
            // this is used to send email about payment only
            return CustomerAirSalePayment(in);
            break;


        case COREGRADE_BALANCE_TOPUP_ORDER:
            REQ_LONG(in, "amount", 1, -1);
            REQ_LONG(in, "customer_id", 1, -1);

            // CustomerAirSalePayment(in);


            /*
            CREATE TABLE trans_balance_topup (
            id serial NOT NULL,
            customer_id INT NOT NULL references customer(id),
            orderid character varying(25) NOT NULL,
            description VARCHAR(100),
            amount INT DEFAULT 0,
            txnref character varying(25),
            payref character varying(200),
            retref character varying(50),
            status integer DEFAULT 1,
            added timestamp without time zone DEFAULT now(),
            recipient_id INT NOT NULL references customer(id),
            completed timestamp without time zone DEFAULT NULL,
            appramt integer DEFAULT 0,
            rspcode character varying(10)
            );

             */
            srand(time(NULL));
            r = abs(rand()*100000000);
            out["orderid"] = "";
            cust["customer_id"] = in["customer_id"];
            cust["customer_id"].set_valid(true);
            cust["amount"] = in["amount"];
            cust["amount"].set_valid(true);
            cust["orderid"] = r;
            cust["orderid"].set_valid(true);
            cust["recipient_id"] = in["customer_id"];
            cust["recipient_id"].set_valid(true);
            out["order_id"] = insert_db_record(DBS_VALID, "trans_balance_topup", "trans_balance_topup_id_seq", cust);
            if (out["order_id"].Long() > 0) {
                sprintf(xtid, "7%08lu", out["order_id"].Long());
                xx["orderid"] = xtid;
                pgsql_exec("UPDATE trans_balance_topup SET orderid ='%s',recipient_id=%lu WHERE id=%lu AND customer_id = %lu ", xtid, in["customer_id"].Long(), out["order_id"].Long(), in["customer_id"].Long());
                out["orderid"] = xtid;
            } else {
                out["orderid"] = "";
            }

            out["balanceorderid"] = xtid; //"AMEYE000000011";
            break;

        case COREGRADE_BALANCE_TOPUP_PURCHASE:
            REQ_STRING(in, "orderid", 1, 50, "(.*)");

            if (load_db_record(out, "SELECT id AS trans_not_id, * FROM trans_balance_topup WHERE orderid='%s' AND resp='00' AND completed IS NULL", in["orderid"].c_str())) {

                if (out["amount"].Long()*100 == out["appramt"].Long()) {
                    in["customer_id"] = out["customer_id"];
                    in["customer_id"].set_valid(true);
                    // find customer 
                    if (load_db_record(out, "SELECT balance FROM customer WHERE id = %lu  ", in["customer_id"].Long())) {

                        /*
							
                        CREATE TABLE balance_topup (
                        id serial NOT NULL,
                        customer_id INT NOT NULL references customer(id),
                        orderid character varying(25) NOT NULL,	
                        amount INT DEFAULT 0,
                        curr_balance INT DEFAULT 0,
                        final_balance INT DEFAULT 0,
                        status integer DEFAULT 1,
                        added timestamp without time zone DEFAULT now(),
                        completed timestamp without time zone DEFAULT NULL	
                        );

						
                         */


                        xx["orderid"] = in["orderid"];
                        xx["orderid"].set_valid(true);
                        xx["customer_id"] = out["customer_id"];
                        xx["customer_id"].set_valid(true);
                        xx["curr_balance"] = out["balance"];
                        xx["curr_balance"].set_valid(true);
                        xx["amount"] = out["appramt"];
                        xx["amount"].set_valid(true);
                        out["topup_id"] = insert_db_record(DBS_VALID, "balance_topup", "balance_topup_id_seq", xx);
                        //--------------------------------------------------
                        pgsql_exec("UPDATE customer SET balance = balance + %lu  WHERE id=%lu ", out["appramt"].Long(), in["customer_id"].Long());
                        //--------------------------------------------------
                        load_db_record(out, "SELECT balance AS final_balance FROM customer WHERE id = %lu  ", in["customer_id"].Long());
                        pgsql_exec("UPDATE balance_topup SET final_balance  = %lu, completed = now()  WHERE id=%lu ", out["final_balance"].Long(), out["topup_id"].Long());
                        pgsql_exec("UPDATE trans_balance_topup SET  completed = now()  WHERE id=%lu ", out["trans_not_id"].Long());
                        out["status"] = "Completed";
                        BalanceUpdateAlert(in);
                        CustomerBalanceEmail(in);

                    } else {
                        out["status"] = "Error Processing request, customer not found";
                    }
                } else { // amount error
                    out["status"] = "Error Processing request, amount error";
                }



            } else {
                out["status"] = "Unable to process or the order was completed";
            }


            //  out["status"] = "Yes we get this in backend";

            // BalanceUpdateAlert(out);  // contains everythinng 
            break;

        case COREGRADE_TOPUP_ORDER_PURCHASE:
            out = in;

            REQ_LONG(in, "pmode", 1, -1);
            REQ_LONG(in, "paymentitemid", 1, -1);
            REQ_STRING(in, "orderid", 1, 50, "(.*)");
            REQ_LONG(in, "payment_code", 1, -1);

            if (in["pmode"].Long() == PAY_MODE_BALANCE) // paying with balance
            {
                REQ_LONG(in, "customer_id", 1, -1);
            }

            out["route_id"] = "0";
            out["route_etisalat"] = "0";
            if (load_db_record(out, "SELECT id AS route_id  FROM airtime_route  WHERE payment_code ='%s'", in["payment_code"].c_str())) {
                out["route_etisalat"] = "1";
            } else {
            }



            out["status"] = "";
            out["status_code"] = "";

            if (load_db_record(out, "SELECT gid AS paymentitemid  FROM interswitch_biller_payment_items WHERE paymentcode = '%lu'", in["payment_code"].Long())) {
                in["paymentitemid"] = out["paymentitemid"];
                in["paymentitemid"].set_valid(true);
            }




            //		ret = load_db_record( paymentitem, "SELECT id,billerid,billername,name,amount,paymentcode FROM interswitch_biller_payment_items WHERE gid = %lu", paymentItemId);

            if (load_db_record(out, "SELECT id AS trans_not_id, * FROM trans_notification WHERE orderid='%s' AND customer_id = %lu AND completed IS NULL", in["orderid"].c_str(), in["customer_id"].Long())) {
                in["amount"] = out["amount"].Long()*100;
                in["amount"].set_valid(true);

                in["customermobile"] = out["recipient_no"];
                in["customermobile"].set_valid(true);
                in["order_id"] = in["orderid"];
                in["order_id"].set_valid(true);

                REQ_LONG(in, "amount", 1, -1);
                load_db_record(out, "SELECT value AS max_topup FROM global_settings WHERE name = 'MAXIMUM_TOPUP_KOGO'");
                maxAirtime = out["max_topup"].Long();
                if (maxAirtime >= in["amount"].Long()) {

                    if (in["pmode"].Long() == PAY_MODE_BONUS) // paying with balance
                    {
                        if (load_db_record(out, "SELECT * FROM customer WHERE id = %lu AND bonus_pend = 1", in["customer_id"].Long())) {

                            //--------------------------------------------------
                            pgsql_exec("UPDATE customer SET bonus_pend=3  WHERE id=%lu ", in["customer_id"].Long());
                            //--------------------------------------------------
                            //	retval = INTW_sendBillPaymentAdvice( in, out );
                            if (out["route_etisalat"].Long() > 0 && out["route_id"].Long() > 0) {
                                retval = DeliverMobilseEtisalat(in, out);
                                out["ResponseCode"] = retval;
                            } else {
                                retval = INTW_sendBillPaymentAdvice(in, out);
                            }

                            if (out["ResponseCode"].Long() == 90000L) {
                                out["status"] = "Completed";
                                out["status_code"] = "A0001";
                                pgsql_exec("UPDATE trans_notification SET completed = now(),description='Bonus to %s' WHERE id=%lu AND customer_id = %lu ", in["customermobile"].c_str(), out["trans_not_id"].Long(), in["customer_id"].Long());
                                pgsql_exec("UPDATE customer SET bonus_pend=5  WHERE id=%lu ", in["customer_id"].Long());
                                out["email_alert"] = "I am sending Email of Success";
                                CustomerAirBonus(in);
                                VirtualAirSaleAlert(out);
                            } else {
                                //--------------------------------------------------
                                //  pgsql_exec( "UPDATE customer SET balance = balance + %lu  WHERE id=%lu ",in["amount"].Long(),in["customer_id"].Long());
                                //--------------------------------------------------										
                                //VirtualAirSaleAlert(out);
                                out["email_alert"] = "I am sending Email of Failure";
                                out["status"] = "Unable to deliver topup";
                                out["status_code"] = "F0005";

                            }

                        } else { // customer not found
                            out["status"] = "Account not found";
                            out["status_code"] = "F0003";
                        }
                    }


                    if (in["pmode"].Long() == PAY_MODE_BALANCE) // paying with balance
                    {
                        if (load_db_record(out, "SELECT * FROM customer WHERE id = %lu", in["customer_id"].Long())) {
                            if (out["balance"].Long() < in["amount"].Long()) {
                                out["status"] = "Insufficient Balance for Purchase";
                                out["status_code"] = "F0004";
                            } else {
                                //--------------------------------------------------
                                pgsql_exec("UPDATE customer SET balance = balance - %lu  WHERE id=%lu ", in["amount"].Long(), in["customer_id"].Long());
                                //--------------------------------------------------
                                //retval = INTW_sendBillPaymentAdvice( in, out );
                                if (out["route_etisalat"].Long() > 0 && out["route_id"].Long() > 0) {
                                    retval = DeliverMobilseEtisalat(in, out);
                                    out["ResponseCode"] = retval;
                                } else {
                                    retval = INTW_sendBillPaymentAdvice(in, out);
                                }
                                if (out["ResponseCode"].Long() == 90000L) {
                                    out["status"] = "Completed";
                                    out["status_code"] = "A0001";
                                    pgsql_exec("UPDATE trans_notification SET completed = now() WHERE id=%lu AND customer_id = %lu ", out["trans_not_id"].Long(), in["customer_id"].Long());
                                    out["email_alert"] = "I am sending Email of Success";
                                    CustomerAirSale(in);
                                    VirtualAirSaleAlert(out);
                                } else {
                                    //--------------------------------------------------
                                    pgsql_exec("UPDATE customer SET balance = balance + %lu  WHERE id=%lu ", in["amount"].Long(), in["customer_id"].Long());
                                    //--------------------------------------------------										
                                    VirtualAirSaleAlert(out);
                                    out["email_alert"] = "I am sending Email of Failure";

                                    out["status"] = "Unable to deliver topup";
                                    out["status_code"] = "F0005";

                                }
                            }
                        } else { // customer not found
                            out["status"] = "Account not found";
                            out["status_code"] = "F0003";
                        }
                    }

                    if (in["pmode"].Long() == PAY_MODE_CCARD) // paying with balance
                    {
                        /*							
                                $ordd["customer_id"] =  $_SESSION["uid"];
                                $ordd["customerid"] =$_SESSION["uid"]; 
                                $in["amount"] = isset($_POST["amount"])?((int)(100*$_POST["amount"])):0;
                                $in["customeremail"] = $_SESSION["email"];
                                $in["customermobile"] = GetPostVar('customermobile',''); //"08081009999";
                         */
                        if (load_db_record(out, "SELECT id AS trans_not_id, * FROM trans_notification WHERE orderid='%s' AND rspcode='00' AND completed IS NULL", in["orderid"].c_str())) {
                            in["customermobile"] = out["recipient_no"];
                            in["customermobile"].set_valid(true);

                            in["amount"] = out["amount"].Long() * 100;
                            in["amount"].set_valid(true);

                            in["customer_id"] = out["customer_id"];
                            in["customer_id"].set_valid(true);

                            in["customerid"] = out["customer_id"];
                            in["customerid"].set_valid(true);

                            //retval = INTW_sendBillPaymentAdvice( in, out );
                            if (out["route_etisalat"].Long() > 0 && out["route_id"].Long() > 0) {
                                retval = DeliverMobilseEtisalat(in, out);
                                out["ResponseCode"] = retval;
                            } else {
                                retval = INTW_sendBillPaymentAdvice(in, out);
                            }

                            if (out["ResponseCode"].Long() == 90000L) {
                                out["status"] = "Completed";
                                out["status_code"] = "A0001";
                                pgsql_exec("UPDATE trans_notification SET completed = now() WHERE id=%lu AND customer_id = %lu ", out["trans_not_id"].Long(), in["customer_id"].Long());
                                out["email_alert"] = "I am sending Email of Success";
                                CustomerAirSale(in);
                                VirtualAirSaleAlert(out);

                            } else {
                                out["email_alert"] = "I am sending Email of Failure";
                                out["status"] = "Unable to deliver topup";
                                out["status_code"] = "F0005";
                                VirtualAirSaleAlert(out);
                            }


                            /*
                                         id | customer_id |  orderid   |                 description                 | amount |   txnref   |              payref               |    retref    | status |           added            | resp | recipient_no | completed | appramt | rspcode 
                                         ----+-------------+------------+---------------------------------------------+--------+------------+-----------------------------------+--------------+--------+----------------------------+------+--------------+-----------+---------+---------
                                         33 |           1 | 1625865344 | 08174596139                                 |     50 |            |                                   |              |      1 | 2014-09-21 04:48:18.309023 |      | 08174596139  |           |       0 | 
                                         32 |           1 | 1605802112 | 08174596139                                 |     50 |            |                                   |              |      1 | 2014-09-21 04:38:27.146335 |      | 08174596139  |           |       0 | 
                                         31 |           1 | 1476321664 | Success: Approved by Financial Institution  |   1000 | 1476321664 | FBN|WEB|Mobilis|20-09-2014|022815 | 000000016906 |      1 | 2014-09-20 18:52:46.787728 | 00   | 08174596144  |           |  100000 | 00
			   
                             */




                        }




                    }

                } else {
                    out["status"] = "Amount too large based on settings";
                    out["status_code"] = "F0002";
                }


            } else {
                out["status"] = "Valid order not found";
                out["status_code"] = "F0001";
                retval = -1;
            }
            break;

        case COREGRADE_TOPUP_ORDER: //      900020
            REQ_LONG(in, "amount", 1, -1);
            REQ_STRING(in, "recipient_no", 1, 15, "(.*)");
            REQ_LONG(in, "customer_id", 1, -1);

            OPTIONAL(in, "xrate")
            REQ_LONG(in, "xrate", 1, -1);

            OPTIONAL(in, "dollar")
            REQ_LONG(in, "dollar", 1, -1);


            srand(time(NULL));
            r = abs(rand()*10000000);

            cust["orderid"] = r;
            in["orderid"] = r;

            in["orderid"].set_valid(true);

            cust["amount"] = in["amount"];
            cust["amount"].set_valid(true);
            cust["description"] = in["description"];
            cust["description"].set_valid(true);
            cust["customer_id"] = in["customer_id"];
            cust["customer_id"].set_valid(true);
            cust["recipient_no"] = in["recipient_no"];
            cust["recipient_no"].set_valid(true);

            cust["xrate"] = in["xrate"];
            cust["xrate"].set_valid(true);
            cust["dollar"] = in["dollar"];
            cust["dollar"].set_valid(true);

            cust["orderid"].set_valid(true);
            out = in;

            out["order_id"] = insert_db_record(DBS_VALID, "trans_notification", "trans_notification_id_seq", cust);


            if (out["order_id"].Long() > 0) {
                sprintf(xtid, "9%011lu", out["order_id"].Long());
                xx["orderid"] = xtid;
                pgsql_exec("UPDATE trans_notification SET orderid ='%s' WHERE id=%lu AND customer_id = %lu ", xtid, out["order_id"].Long(), in["customer_id"].Long());
                out["orderid"] = xtid;
            } else {
                out["orderid"] = "";
            }


            break;

        case COREGRADE_USER_ACCOUNT_LOGIN:


            break;


        case VIRTUAL_AIRTOPUP:
            out = in;
            REQ_LONG(in, "amount", 1, -1);
            load_db_record(out, "SELECT value AS max_topup FROM global_settings WHERE name = 'MAXIMUM_TOPUP_KOGO'");
            maxAirtime = out["max_topup"].Long();
            if (maxAirtime >= in["amount"].Long()) {
                retval = INTW_sendBillPaymentAdvice(in, out);
                if (retval == 90000L) {
                    out["email_alert"] = "I am sending Email of Success";
                    VirtualAirSaleAlert(out);
                } else {
                    VirtualAirSaleAlert(out);
                    out["email_alert"] = "I am sending Email of Failure";
                }

            } else {
                out["status"] = "Amount too large based on settings";
            }

            break;

        case COREGRADE_ADD_MONEYRECIPIENT:

            REQ_LONG(in, "customerid", 1, -1);
            REQ_STRING(in, "bank_code", 1, 5, "(.*)");
            REQ_STRING(in, "lastname", 1, 50, "(.*)");
            REQ_STRING(in, "firstname", 1, 50, "(.*)");
            REQ_STRING(in, "account_no", 5, 12, "(.*)");
            REQ_LONG(in, "account_type", 1, -1);

            recipient["customerid"] = in["customerid"];
            recipient["customerid"].set_valid(true);
            recipient["bank_code"] = in["bank_code"];
            recipient["bank_code"].set_valid(true);
            recipient["firstname"] = in["firstname"];
            recipient["firstname"].set_valid(true);
            recipient["lastname"] = in["lastname"];
            recipient["lastname"].set_valid(true);
            recipient["account_no"] = in["account_no"];
            recipient["account_no"].set_valid(true);
            recipient["account_type"] = in["account_type"];
            recipient["account_type"].set_valid(true);

            out = in;
            out["sendmoney_recipient_id"] = insert_db_record(DBS_VALID, "sendmoney_recipient", "sendmoney_recipient_id_seq", recipient);
            break;

        case COREGRADE_CREDIT_TOPUP:
            //  REQUIRED STRING customer_number
            REQ_LONG(in, "amount", 1, -1);
            load_db_record(out, "SELECT value AS max_topup FROM global_settings WHERE name = 'MAXIMUM_TOPUP_KOGO'");
            maxAirtime = out["max_topup"].Long();
            if (maxAirtime >= in["amount"].Long()) {
                paylid_directAirTimeTopUp(in, out);
            } else {
                out["status"] = "Amount too large based on settings";
            }


            break;

        case COREGRADE_USER_LOGIN:
            REQ_STRING(in, "username", 1, 50, "(.*)");
            REQ_STRING(in, "pass", 3, 25, "(.*)");

            if (load_db_record(out, "SELECT * FROM customer WHERE username='%s' AND pass = md5('%s')", in["username"].c_str(), in["pass"].c_str())) {


            } else {

            }
            break;
        case COREGRADE_USER_LOGOUT:
            //#define COREGRADE_USER_LOGIN      300
            //#define COREGRADE_USER_LOGOUT     301
            break;

        case COREGRADE_CREATE_ACCOUNT:
            retval = CreateCoreGradeAccount(in, out);
            break;

        case COREGRADE_GETBILLER_INTERSW:
            retval = INTW_getBillers(in, out);
            break;

        case COREGRADE_INTERSW_GETBILLERPAYMENTINTEMS: // 558
            retval = INTW_getBillerPaymentItems(in, out);
            break;

        case COREGRADE_INTERSW_GETBILLERCATEGORIES:
            retval = INTW_getBillerCategories(in, out);
            break;

        case COREGRADE_INTERSW_BILL_PAYMENT_ADVICE:

            REQ_LONG(in, "amount", 1, -1);
            load_db_record(out, "SELECT value AS max_topup FROM global_settings WHERE name = 'MAXIMUM_TOPUP_KOGO'");
            maxAirtime = out["max_topup"].Long();
            if (maxAirtime >= in["amount"].Long()) {
                retval = INTW_sendBillPaymentAdvice(in, out);
            } else {
                out["status"] = "Amount too large based on settings";
            }



            break;

        case COREGRADE_INTERSW_DO_TRANSFER: // 560
            retval = INTW_doTransfer(in, out);
            break;

        case COREGRADE_INTERSW_QUERY_TRANSACTION: // 561
            retval = INTW_queryTransaction(in, out);
            break;

        case COREGRADE_STOREFACE_GET_ACCOUNT_BALANCE:
            retval = paylid_getAccountBalance(in, out);
            break;

    }
    logfmt(logINFO, "/long coregrade_api_main(CVars in, CVars &out)");
    return retval;
}


//possible login $ret
#define GITS_VALID_LOGIN           101
#define GITS_INVALID_LOGIN         800

long customer_login(CVars in, CVars &out) {

    //  plog->SetFileName( PREFIX"/logs/customer_access.log" );

    try {

        try {
            if (in["lastip"].length() > 0) {
                int result = 0;
                // result = pgsql_exec( "UPDATE customer SET last_login=now(),lastip='%s' WHERE id=%lu", in["lastip"].c_str(), uid);
                if (result == 1) {
                    // We are OK
                }
                //  st.Select( "UPDATE customer SET last_login=now(),lastip='%s' WHERE id=%lu", in["lastip"].c_str(), uid);
            } else {
                //	st.Select( "UPDATE customer SET last_login=now() WHERE id=%lu",  uid);
            }

        } catch (bad_parameter) {
            //   st.Select( "UPDATE customer SET last_login=now() WHERE id=%lu",  uid);

        }





        /*
          if ( session )
               out["sessionid"] = session->session_id;
          session_to_php();
         */

        // out["uid"]        = uid;
        // out["account_no"] = account_no;
        out["status"] = "Customer is logged in";

        CVars x;

        // x["uid"] = uid;     x["uid"].set_valid( true );
        x["status"] = "1";
        x["status"].set_valid(true);

        // track_customer_login(x, out);

        return GITS_VALID_LOGIN;
    } catch (bad_parameter) {
        out["status"] = "bad parameter";
        return PHP_API_BAD_PARAM;
    }
    return GITS_INVALID_LOGIN;
}


