<?php

function php_getMemberCardDescision($in, &$out)
{
    $cnt = 0;
    $card_limit = 35;
    $member_points = 0;
    $decision["decision_group"] = "A10AA01";

    $member_id = $in["member_id"];

    //CLEAN UP PREVIOUS CARDS
    updateQuery("UPDATE members_card_assign SET status = 0 WHERE member_id= " . $member_id . " AND status=1 AND trigger_key IS NULL");

    loadMemberDescisionData($member_id, $decision);

    $member_points = $decision["points"];

    $res = selectData("SELECT c.id,m.decision_group FROM members_card_assign c LEFT JOIN members m ON m.id = c.member_id WHERE c.member_id= " . $member_id . " AND c.status=1");
    if ($res != null) {
        $cnt = pg_num_rows($res);
    }

    $permCard = CARD_ADD_DENIED;

    if ($card_limit - $cnt > 0) {
        $cards = selectData("SELECT d.*,m.card_behavior,m.button1_action AS card_action FROM decision_cards d LEFT JOIN decision_group g ON g.id=d.decision_id LEFT JOIN main_cards m ON m.id=d.card_id
            WHERE g.dkey='" . $decision['decision_group'] . "' AND d.status =1  ORDER BY m.card_order ASC");

        if ($cards != null) {
            $member = getMember($member_id);
            while ($card = pg_fetch_assoc($cards)) {
                $permCard = verifyMemberCardDescision($card, $member, $outy);
                // END card action modification
                if (CARD_ADD_ALLOWED == $permCard) {
                    userCardAdd($member_id, $card['card_id'], $outy);
                }
            }
        }
    }
    $outy["status"] = "";
}

function php_member_email_calls($action, $in, &$out)
{
    // WE ARE NOT SENDING LOGIN EMAIL RIGHT NOW
}

function php_SessionCheck($uid, $sessionid, $create)
{
    global $pgconn;

    error_log("php_SessionCheck($uid, $sessionid, $create )");

    $session_expired_minutes = 15; // load in the global

    // Sanity check
    if ($uid < 1 || $sessionid == null || strlen($sessionid) < 4) {
        return -1; // Invalid parameters
    }
    // Clean old sessions
    if ($create == 1) // Clean Previous session by force
    {
        pg_query($pgconn, "DELETE FROM members_session WHERE member_id=" . $uid);
    }

    $q = "DELETE FROM members_session WHERE member_id=${uid} AND updated < (now() - interval '${session_expired_minutes} minutes')";
    pg_query($pgconn, $q);
    // Update/check existing session
    if ($create == 0) {
        $q = "UPDATE members_session SET updated=NOW() WHERE member_id=${uid} AND session='" . pg_escape_string($sessionid) . "'";
        pg_query($pgconn, $q);

        $q = "SELECT * FROM members_session WHERE member_id=${uid} AND session='" . pg_escape_string($sessionid) . "'";
        $res = pg_query($pgconn, $q);
        if ($res && pg_num_rows($res)) {
            error_log("VALID SESSION *****");
            return 1; // Session updated
        } else {
            error_log("INVALID SESSION *****");
            //INVALID SESSION DETECTED
            return -1; // Invalid parameters
        }
    }

    if ($create > 0) {
        // Check session i?
        $q = "SELECT * FROM members_session WHERE member_id=${uid} AND session<>'" . pg_escape_string($sessionid) . "'";
        $res = pg_query($pgconn, $q);
        if ($res && pg_num_rows($res)) {
            return -2; // Active sessions found
        }
        $sess = []; // Do we have the same session already?
        $q = "SELECT * FROM members_session WHERE member_id=${uid} AND session='" . pg_escape_string($sessionid) . "'";
        $res = pg_query($pgconn, $q);
        if ($res && pg_num_rows($res) && $sess = pg_fetch_assoc($res)) {
            $q = "UPDATE members_session SET updated=NOW() WHERE member_id=${uid} AND session='" . pg_escape_string($sessionid) . "'";
            pg_query($pgconn, $q);
            return $sess["id"];
        }
        // Create a new session
        $loc = getRemoteIpAddress();
        $sess["loc"] = $loc;
        $sess["member_id"] = $uid;
        $sess["session"] = $sessionid;
        $q = "INSERT INTO members_session (loc,member_id,session) VALUES ('" . pg_escape_string($loc) . "',${uid},'" . pg_escape_string($sessionid) . "') RETURNING id";
        $res = pg_query($pgconn, $q);
        if ($res && pg_num_rows($res) && $f = pg_fetch_assoc($res)) {
            if ($f["id"] > 0) {
                return $f["id"]; // New session created
            }
        }
        return -3; // Failed to create new session
    }
    error_log("/php_SessionCheck($uid, $sessionid, $create )");
    return 0; // No route
}

function php_get_appSettings($in, &$out)
{
    global $pgconn;
    $out["total_record"] = "0";
    $res = pg_query($pgconn, "SELECT * FROM app_settings");
    if ($res && pg_num_rows($res)) {
        $out["total_record"] = pg_num_rows($res);
        while ($f = pg_fetch_assoc($res)) {
            $out[$f["setting_key"]] = $f["value"];
        }
    }
    return 0;
}

function php_userlogin($in, &$out)
{
    global $pgconn;
    $ret = -1;
    #$q = "SELECT * FROM members WHERE lower(username)=lower('" . pg_escape_string($in["username"]) . "') AND password='" . md5($in["password"]) . "'";
    $q = "SELECT UPPER( md5( now()::text) ) AS sessionid,m.*,mp.*,m.id AS member_id,mp.id AS member_profile_id FROM members m ";
    $q .= " LEFT JOIN members_profile mp ON mp.member_id = m.id ";
    $q .= " WHERE m.status=1 AND LOWER(m.username)=LOWER('" . pg_escape_string($in["username"]) . "') AND m.password2='" . md5($in["password"]) . "'"; //
    $r = pg_query($pgconn, $q);

    if ($r && pg_num_rows($r) && $out = pg_fetch_assoc($r)) {
        unset($out["password"]);
        $q = "DELETE FROM members_session WHERE member_id=" . $out["member_id"];
        pg_query($pgconn, $q);
        if (php_SessionCheck($out["member_id"], $out["sessionid"], 1) > 0) {
            $iny = [];
            $outy = [];
            $iny["descision"] = "A10AA01";
            $iny["member_id"] = $out["member_id"];

            php_getMemberCardDescision($iny, $outy);
            $out["status"] = "OK";

            /*LOAD THE SESSION INTO OUT now */
            $q = "SELECT session FROM members_session WHERE member_id=" . $out["member_id"] . " ORDER BY id DESC LIMIT 1";
            $r = pg_query($pgconn, $q);
            $f = pg_fetch_assoc($r);
            $out = array_merge($out, $f);

            php_member_email_calls($in["action"], $out, $out);
            //===============================================================================================================================
            $q = "UPDATE members SET last_login = now(),login_failures=0 WHERE id = " . $out["member_id"];
            pg_query($pgconn, $q);
            //member_email_calls(ACCOUNT_LOGIN_ALERT,out,out); // ALERT CUSTOMER OF LOGIN
            $ret = PHP_LOGIN_OK;
            $out["email_linked"] = "0";
            $out["account_linked"] = "0";
            $out["gps_allowed"] = "0";
            $out["random"] = "0";
            $out["todays_trips"] = "0";
            $out["password"] = "REMOVED";
            $out["php_userlogin"] = true; // check
            $out["internal_return"] = 100;
            $out["retval"] = 100;
        } else {
            $out["status"] = "Session check failed";
        }
    } else {
        $q = "UPDATE members SET login_failures=login_failures+1 WHERE LOWER(username)=LOWER('" . $in["username"] . "')";
        pg_query($pgconn, $q);
        $out["status_message"] = "Invalid Username/Password";
    }
    php_get_appSettings($in, $out);
    //$out["FEED_BOOKING_SHOW"] = '100'; // temporary return to test other parts
    $out["password"] = "REMOVED";

    ksort($out);
}
