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

#include <curl/curl.h>

#include "account.h"




long LoginAdmin(CVars in, CVars &out)
{
	long ret = PHP_API_BAD_PARAM;
	logfmt( logINFO, "LoginWrenchBoardAccount()" );
	REQ_STRING (in, "username",   5, 49, "(.*)");
	REQ_STRING (in, "password",   5, 49, "(.*)");
	REQ_STRING (in, "sessionid",  4, 40, "(.*)");
	OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");

		ret = load_db_record( out, "SELECT *,id AS member_id FROM members WHERE status=1 AND LOWER(username)=LOWER('%s') AND password= md5('%s')", in["username"].c_str(), in["password"].c_str() );
		if (ret) {
			if (CommonSessionCheck(out["id"].Long(),0,0, in["sessionid"].c_str(), 1)>0) {
				out["stauts"] = "OK";
				ret = PHP_API_OK;
			} else {
				out["status"] = "Session check failed";
			}
		} else {
			out["status"] = "Invalid username and/or password";
		}
		
	
	logfmt( logINFO, "/LoginWrenchBoardAccount()" );	
	return ret;
}


long LoginManager(CVars in, CVars &out)
{
	long ret = PHP_API_BAD_PARAM;
	logfmt( logINFO, "LoginManager()" );
	REQ_STRING (in, "username",   5, 49, "(.*)");
	REQ_STRING (in, "password",   5, 49, "(.*)");
	REQ_STRING (in, "sessionid",  4, 50, "(.*)");
	OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");

		ret = load_db_record( out, "SELECT *,id AS member_id FROM managers_account WHERE status=1 AND LOWER(username)=LOWER('%s') AND password= md5('%s')", in["username"].c_str(), in["password"].c_str() );
		if (ret) {
			if (CommonSessionCheck(out["managers_id"].Long(),0,out["member_id"].Long(), in["sessionid"].c_str(), 1)>0) {
				out["login_status"] = "OK";
				out["sessionid"] = in["sessionid"]; out["sessionid"].set_valid(true);
				out["manager_session"] = in["sessionid"]; out["manager_session"].set_valid(true);
				load_db_record( out, "SELECT product_name FROM managers WHERE id = %lu ", out["managers_id"].Long() );
				
				char log_msg[149];
				sprintf( log_msg, "Admin Access By %s %s", out["firstname"].c_str(),out["lastname"].c_str() );
				in["managers_id"] = out["managers_id"];
				in["log_msg"] = log_msg;
				// in["loc"] =  ALredy in the IN
				LogManagerAction(in, out);
				
				ret = PHP_API_OK;
			} else {
				out["status"] = "Session check failed";
			}
		} else {
			out["status"] = "Invalid username and/or password";
		}
		
	logfmt( logINFO, "/LoginManager()" );	
	return ret;
}

long LoginShop(CVars in, CVars &out)
{
	long ret = PHP_API_BAD_PARAM;
	logfmt( logINFO, "LoginShop()" );
	REQ_STRING (in, "username",   5, 49, "(.*)");
	REQ_STRING (in, "password",   5, 49, "(.*)");
	REQ_STRING (in, "sessionid",  4, 40, "(.*)");
	OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");

		ret = load_db_record( out, "SELECT *,id AS managers_shop_id FROM managers_shops WHERE status=1 AND LOWER(username)=LOWER('%s') AND password= md5('%s')", in["username"].c_str(), in["password"].c_str() );
		if (ret) {
			if (CommonSessionCheck(out["managers_id"].Long(),out["managers_shop_id"].Long(),0, in["sessionid"].c_str(), 1)>0) {
				out["login_status"] = "OK";
				out["sessionid"] = in["sessionid"]; out["sessionid"].set_valid(true);
				
				/*
				wrenchboard_test=> select * from managers_survey;
				 id | managers_id |                   survey                    |           added           |        start_date         |         end_date          | status | loc 
				----+-------------+---------------------------------------------+---------------------------+---------------------------+---------------------------+--------+-----
				  1 |           1 |  Are you satisfied with your service today? | 2015-06-24 20:49:48.36751 | 2015-06-24 20:49:48.36751 | 2015-09-22 20:49:48.36751 |      1 | 
				(1 row)
				*/
				load_db_record( out, "SELECT id AS survey_id,survey,template FROM managers_survey WHERE managers_id = %lu ORDER BY id DESC LIMIT 1", out["managers_id"].Long() );
				/*
				wrenchboard_test=> select * from managers;
				 id | csr_id |   product_name   |  firstname  |  lastname  |           email            | status |           added            |      loc       
				----+--------+------------------+-------------+------------+----------------------------+--------+----------------------------+----------------
				  1 |      1 | Sample Test bank | MyFirstName | MyLastName | ses66181+wrenchboard@gmail.com |      1 | 2015-06-23 14:19:18.882625 | 38.101.241.140
				(1 row)
				*/
				load_db_record( out, "SELECT product_name FROM managers WHERE id = %lu ", out["managers_id"].Long() );
				char log_msg[149];
				sprintf( log_msg, "Location Access at %s By %s", out["shop_id"].c_str(),  out["username"].c_str());
				in["managers_id"] = out["managers_id"];
				in["log_msg"] = log_msg;
				// in["loc"] =  ALredy in the IN
				LogManagerAction(in, out);
	
	
				ret = PHP_API_OK;
			} else {
				out["status"] = "Session check failed";
			}
		} else {
			out["status"] = "Invalid username and/or password";
		}
		
	out["ret"] =  ret;
	logfmt( logINFO, "/LoginShop()" );	
	return ret;
}


long CommonSessionCheck(long managers_id,long shop,long acc, const char *sessionid, int create )
{
	logfmt( logINFO, "long CommonSessionCheck(long managers_id,long shop, const char *sessionid, int create )" );
	// Sanity check
	if (managers_id<1 || sessionid==NULL || strlen(sessionid)<4) {
		return -1L; // Invalif parameters
	}
	
	char ptid[30];
	if ( shop > 0 )
	{
		  sprintf( ptid, " AND shop=%lu ", shop );
	}
	else
	{
		 sprintf( ptid, " " );  // just empty space
	}
	// Clean old sessions
	   if (create>0) 
	   {   if ( shop > 0 ) pgsql_exec("DELETE FROM managers_session WHERE managers_id=%ld %s ", managers_id,ptid);   }
	   else
	   { 	pgsql_exec("DELETE FROM managers_session WHERE managers_id=%ld %s AND  updated < (now() - interval '15 minutes')", managers_id,ptid);    }

	   if (create==0 && pgsql_exec("UPDATE managers_session SET updated=NOW() WHERE managers_id=%ld %s AND sessionid='%s'", managers_id,ptid, sessionid)>0) {
		return 1L; // Session updated
        }
        if (create>0) {
		// Check session i?
		/*
		const PGresult *res = pgsql_query("SELECT * FROM managers_session WHERE managers_id=%ld %s AND sessionid<>'%s'", managers_id,ptid, sessionid);
		if (res!=NULL && pgsql_num_rows(res)>0) {
			return -2L; // Active sessions found
		}
		*/
		CVars sess; // Do we have the same session already?
		if (load_db_record( sess, "SELECT * FROM managers_session WHERE managers_id=%lu %s AND sessionid='%s'", managers_id,ptid, sessionid)>0) {
			pgsql_exec("UPDATE managers_session SET updated=NOW() WHERE managers_id=%ld %s AND sessionid='%s'", managers_id,ptid, sessionid);
			return sess["id"].Long();
		}
		// Create a new session
		sess["managers_id"] = managers_id; sess["managers_id"].set_valid(true);
		sess["sessionid"] = sessionid; sess["sessionid"].set_valid(true);
		if ( shop > 0 )
		{
			sess["shop"] = shop; sess["shop"].set_valid(true);
		}
				if ( acc > 0 )
		{
			sess["account"] = acc; sess["account"].set_valid(true);
		}
		long sid = insert_db_record( DBS_VALID, "managers_session", "managers_session_id_seq", sess );
		if (sid>0) {
			return sid; // New session created
		}
		return -3L; // Failed to create new session
	}
	logfmt( logINFO, "/long CommonSessionCheck(long managers_id,long shop, const char *sessionid, int create )" );
	return 0L; // No route
}

/*
 
 CREATE TABLE managers_session (
    id SERIAL,
	managers_id INT REFERENCES managers(id),
	shop INT DEFAULT 0,
	sessionid varchar(100) NOT NULL,
	added timestamp without time zone DEFAULT now(),
	updated timestamp without time zone DEFAULT now(),
	status   integer DEFAULT 1, 
    loc INET	
	);
 

*/