// 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 "medTEmails.h"
/* -- */
#include "function_backoffice.h"


long BkoCommonSessionCheck(long backoffice_id, long shop, long acc, const char *sessionid, int create);

long LoginBkoAdmin(CVars in, CVars &out) {
    long ret = PHP_API_BAD_PARAM;
    logfmt(logINFO, "LoginBkoAdmin()");
    REQ_STRING(in, "username", 5, 49, "(.*)");
    REQ_STRING(in, "password", 5, 49, "(.*)");
    //REQ_STRING (in, "sessionid",  4, 40, "(.*)");
    const char * loc = getenv("REMOTE_ADDR");

    load_db_record(out, "SELECT md5( md5('now()')||'%d' ) AS sessionid", rand()*10000);
    in["sessionid"] = out["sessionid"];
    in["sessionid"].set_valid(true);


    ret = load_db_record(out, "SELECT *,id AS backoffice_id FROM bko_users WHERE status=1 AND LOWER(username)=LOWER('%s') AND password= md5('%s')", in["username"].c_str(), in["password"].c_str());
    if (ret > 0) {
        if (BkoCommonSessionCheck(out["id"].Long(), 0, 0, in["sessionid"].c_str(), 1) > 0) {
            out["stauts"] = "OK";
            CVars y;
            y["user_id"] = out["backoffice_id"];
            y["user_id"].set_valid(true);
            y["action"] = "Back Office Login";
            y["action"].set_valid(true);
            y["loc"] = loc;
            y["loc"].set_valid(true);
            insert_db_record(DBS_VALID, "bko_users_log", "bko_users_log_id_seq", y);

            ret = PHP_API_OK;
        } else {
            out["status"] = "Session check failed";
        }
    } else {
        out["status"] = "Invalid username and/or password";
    }

    logfmt(logINFO, "/LoginBkoAdmin()");
    return ret;
}

long createBkoAdmin(CVars in, CVars &out) {
    long ret = PHP_API_BAD_PARAM;
    logfmt(logINFO, "medTrCreateMember()");
    try {
        REQ_LONG(in, "pid", 0, -1);
        REQ_STRING(in, "username", 5, 49, "(.*)");
        REQ_STRING(in, "firstname", 2, 49, "(.*)");
        REQ_STRING(in, "lastname", 2, 49, "(.*)");
        OPTIONAL(in, "phone") REQ_STRING(in, "phone", 5, 23, "(.*)");
        REQ_STRING(in, "password", 5, 49, "(.*)");
        OPTIONAL(in, "phone") REQ_STRING(in, "loc", 5, 16, "(.*)");
        REQ_LONG(in, "plevel", 0, -1);

        //REQ_STRING (in, "sessionid",  4, 40, "(.*)");
        const char * loc = getenv("REMOTE_ADDR");

        const PGresult *res = pgsql_query("SELECT * FROM bko_users WHERE lower(username)=lower('%s')", in["username"].c_str());
        if (res != NULL && pgsql_num_rows(res) > 0) {
            out["status"] = "Dulipcate username not allowed";
            return PHP_API_BAD_PARAM; // Active sessions found
        }

        CVars x;
        x["pid"] = in["pid"];
        x["pid"].set_valid(true);
        x["firstname"] = in["firstname"];
        x["firstname"].set_valid(true);
        x["lastname"] = in["lastname"];
        x["lastname"].set_valid(true);
        x["email"] = in["email"];
        x["email"].set_valid(true);
        x["username"] = in["username"];
        x["username"].set_valid(true);
        x["plevel"] = in["plevel"];
        x["plevel"].set_valid(true);
        x["password"] = "TEMP_ENTRY";
        x["password"].set_valid(true);
        long bko_user_id = insert_db_record(DBS_VALID, "bko_users", "bko_users_id_seq", x);
        if (bko_user_id > 0) {
            // update password now - password
            pgsql_query("UPDATE bko_users SET password = md5('%s') WHERE id  = %lu", in["password"].c_str(), bko_user_id);
        }
    } catch (bad_parameter) {

    }
    return ret;
}

long BkoCommonSessionCheck(long backoffice_id, long shop, long acc, const char *sessionid, int create) {
    logfmt(logINFO, "long BkoCommonSessionCheck(long backoffice_id,long shop, const char *sessionid, int create )");
    // Sanity check
    if (backoffice_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) {
        pgsql_exec("DELETE FROM backoffice_session WHERE backoffice_id=%ld %s ", backoffice_id, ptid);
    } else {
        pgsql_exec("DELETE FROM backoffice_session WHERE backoffice_id=%ld %s AND  updated < (now() - interval '15 minutes')", backoffice_id, ptid);
    }

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

