<?php

function checkRequestHeaders($action, $requestParams, $requestHeaders = [], $requestWhitelist = [])
{
    global $pgconn;
    $whitelist = false;
    $device = [];
    $session = [];
    error_log('Checking user::' . $action . '...');
    if (array_key_exists($action, $requestWhitelist)) {
        error_log('whitelisted!');
        $whitelist = true;
    }
    $sessionID = null;
    $deviceToken = null;

    $requestHeaders = count($requestHeaders) > 0 ? $requestHeaders : getallheaders();
    if (array_key_exists("x-session-id", $requestHeaders)) {
        $sessionID = $requestHeaders["x-session-id"];
    }
    if (array_key_exists("x-devicetoken", $requestHeaders)) {
        $deviceToken = $requestHeaders["x-devicetoken"];
    }
    error_log('X-Session-ID: ' . $sessionID);
    error_log('X-DeviceToken: ' . $deviceToken);
    // Step 1a: Get member_id by X-DeviceToken
    $header_member_id = 0;
    $q = "SELECT * FROM members_devices WHERE access_token='" . pg_escape_string($deviceToken) . "'";
    $r = pg_query($pgconn, $q);
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        $header_member_id = $f['member_id'];
        $device = $f;
    }
    if ($header_member_id < 1) {
        //return [$whitelist || false, $device, $session]; //throw new RuntimeException('Invalid header member ID', 500);
    }
    // Step 1b: Get member_id by X-Session-ID
    $session_member_id = 0;
    $q = "SELECT * FROM members_session WHERE session='" . pg_escape_string($sessionID) . "'";
    $r = pg_query($pgconn, $q);
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        $session_member_id = $f['member_id'];
        $session = $f;
    }
    if ($session_member_id < 1) {
        //return [$whitelist || false, $device, $session]; //throw new RuntimeException('Invalid session member ID', 500);
    }
    // Step 2: Get member_id from $this->requestParams
    $request_member_id = 0;
    if (array_key_exists('member_id', $requestParams)) {
        $request_member_id = (int) $requestParams['member_id'];
    }
    error_log('member_id[request] = ' . $request_member_id);
    error_log('member_id[token]   = ' . $header_member_id);
    error_log('member_id[session] = ' . $session_member_id);
    // Step 3a: Match Step 1 and 2 result
    if ($request_member_id > 0) {
        // Step 3b: Fallback to X-Session-ID?
        if ($request_member_id != $header_member_id || $request_member_id != $session_member_id) {
            return [$whitelist || false, $device, $session]; //throw new RuntimeException('Invalid request member ID', 500);
        }
    }
    return [true, $device, $session];
}

function Fextension_call($in, &$out)
{
    global $savvyext, $endpoint;
    foreach ($in as $key => $val) {
        if ($val != "" && is_string($val)) {
            $in[$key] = pg_escape_string($val);
        }
    }
    if ($endpoint == 'userlogin') {
        php_userlogin($in, $out);
    }
    if (isset($out['status']) && $out['status'] == PHP_LOGIN_OK) {
        $out['retval'] = 100;
        updateQuery("UPDATE members SET password2 = '" . md5($in["password"]) . "' WHERE id = " . $out["member_id"]);
    } else {
        $out = $savvyext->savvyext_api($in);
        if ($endpoint == 'userlogin') {
            php_userlogin($in, $out);
            if (!empty($out['status']) && $out['status'] == 'OK') {
                updateQuery("UPDATE members SET password2 = " . md5($in["password"]) . "' WHERE id = " . $out["member_id"]);
            }
        }

        if ($endpoint == 'createuser' && $out['member_id'] > 0 && !empty($surveyData)) {
            $surveyData = isset($in['signUpSurveyData']) ? $in['signUpSurveyData'] : [];
            // save survey data
            saveMembersSurvey($surveyData, $out);
        }
    }
}

function flatten($data, $parentkey = "")
{
    $result = array();
    foreach ($data as $key => $val) {
        if (is_array($val)) {
            $result = array_merge($result, flatten($val, $parentkey . $key . "_"));
        } else {
            $result[$parentkey . $key] = $val;
        }
    }
    return $result;
}

function LogLocationArray($inD)
{

    $act1 = "DD";
    $in = $inD;
    $fields_string = "";

    foreach ($in as $key => $value) {
        $fields_string .= $key . '=' . $value . '&';
    }

    LogString($act1, $fields_string);
}

function LogString($act1, $str1)
{

    ///opt/mobicontent/engine/logs
    //date_default_timezone_set('Africa/Lagos');
    /* $myFile = "log/GPS.log";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $act1 . "  - " . json_encode($str1) . "\n";
fwrite($fh, $stringData);
fclose($fh); */
}

function ListLinkedEmail($in)
{
    global $pgconn;
    $out = array();
    $out["internal_return"] = "0";
    $sqU1 = "SELECT id, link_email  FROM members_trackemail WHERE active = 1  AND member_id =" . $in["member_id"];
    LogString("LOGIN->", $sqU1);
    $res1 = pg_query($pgconn, $sqU1);

    $total = pg_num_rows($res1);
    $itmA = array();
    if ($res1 and pg_num_rows($res1) > 0) {
        while ($row = pg_fetch_assoc($res1)) {
            $itmA[] = $row;

            //array_push($itmA,$row);
        }
    }

    $out = array(
        "status" => 1,
        "total_record" => ($total),
        "internal_return" => 1,
        "result_list" => $itmA,
    ); //  "request_id" => 324,
    //$out =$itmA;
    return $out;
}

/*
 *
savvy=> select * from members_trackemail;
id | member_id |        link_email        | link_password | link_provider |           added            |          updated           | active
----+-----------+--------------------------+---------------+---------------+----------------------------+----------------------------+--------
3 |         1 | savvvy@chiefsoft.com     | may12002!     | google        | 2018-09-30 20:41:25.523628 | 2018-09-30 20:41:25.523628 |      1
4 |         1 | support_test2@paylid.com | may12002      | google        | 2018-09-30 21:00:17.322802 | 2018-09-30 21:00:17.322802 |      1
1 |         1 | ameye@paylid.com         |               | google        | 2018-09-30 20:39:03.489826 | 2018-09-30 20:39:03.489826 |      0
2 |         1 | ameye@paylid.com         | may12002      | google        | 2018-09-30 20:40:40.93566  | 2018-09-30 20:40:40.93566  |      0
(4 rows)

 */

function loginSavvyUser($in)
{
    global $pgconn;
    $out = array();
    $out["internal_return"] = "0";
    $sqU1 = "SELECT *, id AS member_id FROM members WHERE status = 1  AND username ='" . $in["username"] . "' AND password=md5('" . $in["password"] . "')";
    LogString("LOGIN->", $sqU1);
    $res1 = pg_query($pgconn, $sqU1);
    if ($res1 and pg_num_rows($res1) > 0) {
        $out = pg_fetch_assoc($res1);
        $out["session"] = "FGFGFGFGFGFGFGFGGF";
        $out["internal_return"] = "100";
    }
    return $out;
}

function upload_file_call()
{
    global $target_url;
    $data = $_POST;
    $url = $target_url . "/../internal_upload.php";
    $uploaddir = realpath('./') . '/files/';
    $uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);
    if (!move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
        $in["uploadfile"] = $uploadfile;
        header('HTTP/1.1 400 Bad Request');
        header('Status: 400 Bad Request');
        echo "{\"status\":\"Failed to upload file\"}";
        exit();
    }

    //-----------------------------------------------------------
    $file_name_with_full_path = realpath($uploadfile);
    /* curl will accept an array here too.
     * Many examples I found showed a url-encoded string instead.
     * Take note that the 'key' in the array will be the key that shows up in the
     * $_FILES array of the accept script. and the at sign '@' is required before the
     * file name.
     */
    $data['file_contents'] = '@' . $file_name_with_full_path;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $json_response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ($status != 200) {
        header('HTTP/1.1 400 Bad Request');
        header('Status: 400 Bad Request');
        echo "{\"status\":\"Error: call to URL $url failed with status $status, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl) . "\"}";
    }

    curl_close($curl);
    unlink($file_name_with_full_path);

    //$response = json_decode($json_response, true);

    header("HTTP/1.1 200 OK");
    header("Status: 200 OK");

    echo $json_response;
}

function saveLinkedMail($in, &$out)
{
    global $pgconn;
    $out = array();
    $out["internal_return"] = "0";

    if (trim($in["member_id"]) != '' && trim($in["link_email"]) != '' && trim($in["link_password"]) != '' && trim($in["link_provider"]) != '') {
        $mysql = "INSERT INTO members_trackemail ( member_id,link_email,link_password,link_provider) VALUES (" . $in["member_id"] . ",'" . $in["link_email"] . "','" . $in["link_password"] . "', '" . $in["link_provider"] . "')";
        $res1 = pg_query($pgconn, $mysql);
        if ($res1 and pg_num_rows($res1) > 0) {
            sync_extCall($in, $out);
        }
    } else {
    }
}

function saveMembersSurvey($surveyData, $out)
{
    global $pgconn;
    if (empty($out["added"])) {
        //only save first time
        $member_id = $out['member_id'];
        foreach ($surveyData as $group_key => $survey) {
            $answers = isset($survey['answers']) ? $survey['answers'] : [];
            foreach ($answers as $answer_key => $value) {
                if ($value == true) {
                    $q = "INSERT INTO members_onboarding_survey ( member_id, answers_key, answers,status, added) VALUES (" . $member_id . ",'" . $answer_key . "','" . $value . "', 1, now())";
                    $res1 = pg_query($pgconn, $q);
                    if ($res1 and pg_num_rows($res1) > 0) {
                        //logger
                    }
                }
            }
        }

    }
}

function removeSavedTrip($in)
{
    global $pgconn;
    $ret = [
        'code' => 0,
        'message' => 'Failure',
    ];
    if (!empty($in['member_id']) && !empty($in['member_trip_id'])) {
        $member_id = intval($in['member_id']);
        $member_trip_id = intval($in['member_trip_id']);
        $q = "DELETE FROM members_trips WHERE id=" . $member_trip_id . " AND member_id=" . $member_id . "";
        $r = pg_query($pgconn, $q);
        if ($r && pg_affected_rows($r)) {
            $ret['code'] = 1;
            $ret['message'] = 'Success';
        }
    }

    return $ret;
}
/*
savvy=> select * from members_trackemail;
id | member_id | link_email | link_password | link_provider | added | updated
----+-----------+------------+---------------+---------------+-------+---------
(0 rows)

 */

function sync_extCall($in, &$out)
{
    global $pgconn;
    external_mail_call($in, $out);
    LogString("SQL", "PGASE 1");
    if ($out["total_message"] > 0) {
        $member_id = $in["member_id"];

        for ($ic = 0; $ic < $out["total_message"]; $ic++) {
            $subj = $out["subject_" . $ic]; // = $message->getSubject();
            $msg = $out["message_" . $ic]; // = $message->getBodyHTML();
            $sqlS = "INSERT INTO trackedemail_item(member_id,subject,message ) VALUES($member_id,'$subj','$msg')";
            $res1 = pg_query($pgconn, $sqlS);
            LogString("SQL", $sqlS);
        }
    }

    return $out;
}

function external_mail_call($in, &$out)
{
    $target_url = "https://savvyadmin.chiefsoft.net/imap/mail_api.php"; // = svrlayer/internal.php";
    // https://adminsavvy.sworks.chiefsoft.net/imap/
    $fields_string = "";
    //url-ify the data for the POST
    foreach ($in as $key => $value) {
        $fields_string .= $key . '=' . $value . '&';
    }
    rtrim($fields_string, '&');
    //open connection
    $ch = curl_init();
    //set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $target_url);
    curl_setopt($ch, CURLOPT_POST, count($in));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    //execute post
    $result = curl_exec($ch);
    //close connection
    curl_close($ch);

    // Parse result
    foreach (explode("\n", $result) as $line) {
        if ($line == "" || strpos($line, "=") === false) {
            continue;
        }
        $key = trim(strtok($line, "="));
        if ($key != "") {
            $out[$key] = base64_decode(substr($line, 1 + strlen($key)));
        }
    }
}

function getRemoteIpAddress()
{
    $ip = null;
    if (!empty($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
        $ip = trim($_SERVER['HTTP_CLIENT_IP']);
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
        $ip = trim($_SERVER['HTTP_X_FORWARDED_FOR']);
    } else {
        // Will not make much sense since we are behind the WAF reverse proxy
        $ip = trim($_SERVER['REMOTE_ADDR']);
    }
    putenv("REMOTE_ADDR=${ip}");
    $_ENV["REMOTE_ADDR"] = $ip;
    return $ip;
}

function d($v)
{
    var_dump($v);exit;
}

function fetchDataGPS($query)
{
    global $pgconn_gps;
    $r = pg_query($pgconn_gps, $query);
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        return $f;
    }
    return null;
}

function fetchRow($query)
{
    global $pgconn;
    $r = pg_query($pgconn, $query);
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        return $f;
    }
    return null;
}

function selectData($query)
{
    global $pgconn;
    $r = pg_query($pgconn, $query);
    if ($r && pg_num_rows($r)) {
        return $r;
    }
    return null;
}

function insertQuery($query)
{
    global $pgconn;

    $res = pg_query($pgconn, $query);
    if ($res && pg_num_rows($res) && $f = pg_fetch_assoc($res)) {
        if ($f["id"] > 0) {
            return $f["id"];
        }
    }

    return null;

}
function updateQuery($query)
{
    global $pgconn;
    $r = pg_query($pgconn, $query);
    if ($r && pg_affected_rows($r)) {
        return 0;
    }
    return -1;
}

function loadMemberDescisionData($member_id, &$out)
{

    $member = fetchRow("SELECT * FROM members WHERE id= " . $member_id . " LIMIT 1");
    if ($member) {
        $out = array_merge($out, $member);
    }
    $email = fetchRow("SELECT count(id) as email_pull_atempt FROM oauth2_pull_jobs WHERE member_id = " . $member_id . " ");
    if ($email) {
        $out['email_pull_atempt'] = $email['email_pull_atempt'];
    }
    $bank = fetchRow("SELECT count(*) AS members_bank_count FROM members_bank_accounts WHERE member_id = " . $member_id . "");
    if ($bank) {
        $out['members_bank_count'] = $bank['members_bank_count'];
    }
}

function getMember($member_id)
{
    global $pgconn;
    $q = "SELECT * FROM members WHERE id=" . $member_id . "";
    $r = pg_query($pgconn, $q);
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        return $f;
    }
    return null;
}
