// Topup management toosl
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "jubabox_api.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include <curl/curl.h>
/* -- */
#include "jubabox_session.h"


long SessionCheck(long uid, const char *sessionid, int create) {
    logfmt(logINFO, "long SessionCheck(long uid, const char *sessionid, int create )");
    // Sanity check

    long session_expired_minutes = 15; // load in the global 


    if (uid < 1 || sessionid == NULL || strlen(sessionid) < 4) {
        return -1L; // Invalif parameters
    }
    logfmt(logINFO, "#######-#########-A");
    // Clean old sessions
    if (create == 1) // Clean Previous session by force
    {
        pgsql_exec("DELETE FROM members_session WHERE member_id=%ld", uid);
    }
    logfmt(logINFO, "#######-#########-B");

   // pgsql_exec("DELETE FROM members_session WHERE member_id=%ld AND updated < (now() - interval '%lu minutes')", uid, session_expired_minutes);
    // Update/check existing session
    if (create == 0) {

        pgsql_exec("UPDATE members_session SET updated=NOW() WHERE member_id=%ld AND session='%s'", uid, sessionid);

        const PGresult *res = pgsql_query("SELECT * FROM members_session WHERE member_id=%ld AND session='%s'", uid, sessionid);
        if (res != NULL && pgsql_num_rows(res) > 0) {
            logfmt(logINFO, "VALID SESSION *****");
            return 1L; // Session updated
        } else {
            logfmt(logINFO, "INVALID SESSION *****");
            //INVALID SESSION DETECTED
            return -1L; // Invalid parameters
        }

    }

    if (create > 0) {
        // Check session i?
        const PGresult *res = pgsql_query("SELECT * FROM members_session WHERE member_id=%ld AND session<>'%s'", uid, 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 members_session WHERE member_id=%lu AND session='%s'", uid, sessionid) > 0) {
            pgsql_exec("UPDATE members_session SET updated=NOW() WHERE member_id=%ld AND session='%s'", uid, sessionid);
            return sess["id"].Long();
        }
        // Create a new session
        const char * loc = getenv("REMOTE_ADDR");
        sess["loc"] = loc;
        sess["loc"].set_valid(true);
        sess["member_id"] = uid;
        sess["member_id"].set_valid(true);
        sess["session"] = sessionid;
        sess["session"].set_valid(true);
        long sid = insert_db_record(DBS_VALID, "members_session", "members_session_id_seq", sess); //members_session_id_seq
        if (sid > 0) {
            return sid; // New session created
        }
        return -3L; // Failed to create new session
    }
    logfmt(logINFO, "/long SessionCheck(long uid, const char *sessionid, int create )");
    return 0L; // No route
}