// Topup management toosl
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
#include "topups.h"
#include "email.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"

#include <curl/curl.h>

#include "account.h"




long CreateBulkTopupBatch(CVars in, CVars &out)
{
long ret = 0;
        REQ_STRING( in, "batch_name", 1, 50, "(.*)"); 
		REQ_LONG( in, "customer_id", 1, -1 );
		CVars cust;
		cust["customer_id"] = in["customer_id"];  cust["customer_id"].set_valid(true);
		cust["batch_name"] = in["batch_name"];  cust["batch_name"].set_valid(true);
		
		out["bulk_id"] = insert_db_record( DBS_VALID, "bulktopup_batch", "bulktopup_batch_id_seq", cust );
		if (out["bulk_id"].Long() > 0 )
		{
		   ret = out["bulk_id"].Long();
		}
		
  return ret;
}
long AddBulkTopupBatchItem(CVars in, CVars &out)
{
long ret = 0;

/*
CREATE TABLE bulktopup_batch_items
(
	id serial NOT NULL,
	bulk_id INT  REFERENCES bulktopup_batch(id),
	customer_id INT REFERENCES customer(id),
	topup_name VARCHAR(50),
	topup_number VARCHAR(15) NOT NULL,
	topup_amount INT DEFAULT 0,
	topup_network VARCHAR(10),
	order_id VARCHAR(25),
	deliver_status VARCHAR(15),
	status integer DEFAULT 1,
added TIMESTAMP DEFAULT NOW()
);
*/

		REQ_STRING( in, "topup_name", 1, 50, "(.*)");
		REQ_STRING( in, "topup_number", 1, 15, "(.*)");
		REQ_STRING( in, "topup_network", 1, 15, "(.*)");  
		REQ_LONG( in, "topup_amount", 1, -1 ); 
		REQ_LONG( in, "customer_id", 1, -1 );
		REQ_LONG( in, "bulk_id", 1, -1 );

		CVars cust;
		cust["topup_name"] = in["topup_name"];  cust["topup_name"].set_valid(true);
		cust["topup_number"] = in["topup_number"];  cust["topup_number"].set_valid(true);
		cust["topup_network"] = in["topup_network"];  cust["topup_network"].set_valid(true);
		cust["topup_amount"] = in["topup_amount"];  cust["topup_amount"].set_valid(true);
		cust["customer_id"] = in["customer_id"];  cust["customer_id"].set_valid(true);
		cust["bulk_id"] = in["bulk_id"];  cust["bulk_id"].set_valid(true);

		out["bulk_item_id"] = insert_db_record( DBS_VALID, "bulktopup_batch_items", "bulktopup_batch_items_id_seq", cust );
		if (out["bulk_item_id"].Long() > 0 )
		{
		   ret = out["bulk_item_id"].Long();
		}
  return ret;
}
long UpdateBulkTopupItem(CVars in, CVars &out)
{
long ret =0;
  REQ_LONG( in, "bulk_id", 1, -1 );
  REQ_LONG( in, "customer_id", 1, -1 );
	if ( load_db_record( out, "SELECT  id FROM bulktopup_batch WHERE id= %lu AND status <> 5 AND completed IS NULL",in["bulk_id"].Long() )  )
	{
       pgsql_exec( "UPDATE bulktopup_batch SET status  = 2 WHERE completed IS NULL AND status <> 5  AND id=%lu AND customer_id = %lu",in["bulk_id"].Long(),in["customer_id"].Long());
	   ret = in["bulk_id"].Long();
	}
  
  return ret;
}

long DeliverBulkTopupItem(CVars in, CVars &out)
{
CVars xx;
CVars yy;
long ret = 0;
  REQ_LONG( in, "bulk_id", 1, -1 );
  REQ_LONG( in, "item_id", 1, -1 );
  REQ_STRING( in, "payment_code", 1, 50, "(.*)");
  
  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"];
	 xx["paymentitemid"] = out["paymentitemid"];
	 in["paymentitemid"].set_valid( true );
	 xx["paymentitemid"].set_valid( true );
   }
   else
   {
     return 0;
   }
  
	if ( load_db_record( out, "SELECT  * FROM bulktopup_batch WHERE id= %lu AND status <> 5 AND completed IS NULL",in["bulk_id"].Long() )  )
	{
		if ( load_db_record( yy, "SELECT  * FROM bulktopup_batch_items WHERE id= %lu AND status <> 5 AND completed IS NULL",in["item_id"].Long() )  )
		{
			xx["customer_id"]= out["customer_id"]; xx["customer_id"].set_valid( true );
			xx["amount"]= yy["topup_amount"]; xx["amount"].set_valid( true );
			xx["recipient_no"]= yy["topup_number"]; xx["topup_number"].set_valid( true );
			xx["bulk_topup_item_id"] = yy["id"]; xx["bulk_topup_item_id"].set_valid( true );
			 // pgsql_exec( "UPDATE bulktopup_batch SET status  = 2 WHERE completed IS NULL AND status <> 5  AND id=%lu AND customer_id = %lu",in["bulk_id"].Long(),in["customer_id"].Long());
			xx["trans_not_id"] =CreateTopupOrder(xx,out);
			
			if (  xx["trans_not_id"].Long() > 0 )
			{
			   
			    pgsql_exec( "UPDATE bulktopup_batch_items SET order_id = '%s', payment_code = '%s' WHERE id  = %lu",out["orderid"].c_str(),in["payment_code"].c_str(),in["item_id"].Long() );
			    xx["customermobile"]=xx["recipient_no"]; xx["customermobile"].set_valid( true );
				xx["customerid"]= xx["customer_id"]; xx["customerid"].set_valid( true );  // bad but true
				xx["orderid"] =out["orderid"];  xx["orderid"].set_valid( true ); 				
				xx["order_id"] =out["orderid"];  xx["order_id"].set_valid( true ); 
				xx["trans_not_id"].set_valid( true );
				xx["payment_code"] = in["payment_code"];  xx["payment_code"].set_valid( true ); 
				
				if ( DeliverTopOrderByBalance(xx,out) == 100 )
				{
				 pgsql_exec( "UPDATE bulktopup_batch_items SET completed=now(),status=5 WHERE id  = %lu",in["item_id"].Long() );
				}
			}
			
			ret = in["bulk_id"].Long();
		}

	}
return ret;
}

long DeliverTopOrderByBalance(CVars in, CVars &out)
{
long retval=0;
long process_status=0;
// in["amount"]   - arrives as niara - send cents/kobo to interswitch 

	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{  	}
			
			

	   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() )  )
			{
			       long amount_in_cents =  in["amount"].Long()*100;
				  
				   if ( out["balance"].Long() < amount_in_cents )
				   {
					out["status"]     = "Insufficient Balance for Purchase";
					out["status_code"]     = "F0004";
				   }
				   else
				   {	
                       in["amount"] = amount_in_cents;
			           in["amount"].set_valid( true );
					   //--------------------------------------------------
						   pgsql_exec( "UPDATE customer SET balance = balance - %lu  WHERE id=%lu ",amount_in_cents,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) {
						    process_status = 100; // completed
							out["status"]     = "Completed";
							out["status_code"]     = "A0001";
							pgsql_exec( "UPDATE trans_notification SET completed = now() WHERE id=%lu AND customer_id = %lu ",in["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 ",amount_in_cents,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";
			}
	   }


 return process_status;
}


long CreateTopupOrder(CVars in, CVars &out)
{
CVars cust;
CVars xx;
char xtid[12];
int r;
long ret =0;

        REQ_LONG( in, "amount", 1, -1 );		
		REQ_STRING( in, "recipient_no", 1, 15, "(.*)"); 
		REQ_LONG( in, "customer_id", 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["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;
		   ret = out["order_id"].Long();
		}
		else
		{
		out["orderid"]="";
		}
		return ret;
}
