<?php

session_start();
include_once '../config/properties.php';
include_once "../resources/EncryptDecrypt.php";
require_once('../config/database.php');

if (isset($_POST['username']) && isset($_POST['password'])) {
    require("../resources/manageusers.php");

    $username = $_POST['username'];
    $password = $_POST['password'];
    $csrf_token = $_POST['csrf_token'];

    if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {

        $object = new ManageUsers();
        $status = 'Active';
        $searchString = ',';

        $yoursecret = "6LePCPoUAAAAAIZ7-HYiMOsQVuAoT8pav4cC8uw_";
        $response = getSslPage('https://www.google.com/recaptcha/api/siteverify?secret=' . $yoursecret . '&response=' . $_POST['captcha']);
        $googleobj = json_decode($response);
        $verified = $googleobj->success;
        if ($verified === true) {

            $val = $object->Login_corp($username, $password, $date_time);
            if ($val == "error2") {
                echo json_encode(array("result1" => 'error', "result2" => _("LG0107")));
            } else if ($val == "error1") {
                echo json_encode(array("result1" => 'error', "result2" => _("LG0111")));
            } else if ($val == "error3") {
                echo json_encode(array("result1" => 'error', "result2" => _("LG0113")));
            } else if ($val == "error4") {
                echo json_encode(array("result1" => 'error', "result2" => _("LG0112")));
            } else if ($val == "error5") {
                echo json_encode(array("result1" => 'error', "result2" => _("LG0506")));
            } else if ($val == "error6") {
                echo json_encode(array("result1" => 'error', "result2" => _("LG0507")));
            } else if ($val == "error7") {
                echo json_encode(array("result1" => 'error', "result2" => _("LG0115")));
            } else {
                if (is_array($val) && isset($val["error_code"]) && $val["error_code"] === "error8") {
                    //echo json_encode(array("result1" => 'error',"result2" => _("LG0148"),"remaining_attempts" => $data["remaining_attempts"] ));
                    echo json_encode(array("result1" => 'error', "result2" => sprintf(_("LG0148"), $val["remaining_attempts"])));
                } else {
                    //ip address
                    $ua = getBrowser();
                    $ip_address = get_ip_address();
                    if ($ip_address == NULL) {
                        $ip_address = $_SERVER['REMOTE_ADDR'];
                    }
                    $device_name = getenv('COMPUTERNAME');
                    $browser = $ua['name'] . "-" . $ua['version'];
                    $os = $ua['platform'];
                    $val2 = $object->UpdateUserTrackLoggedIN($val, $ip_address, $browser, $os, $device_name, $date_time);

                    $val1 = $object->CheckUserLoginFlag($val);
                    if ($val1 == 0) {
                        unset($_SESSION['csrf_token']);
                        $res = 'changepassword.php?id=' . $val . '';
                        echo json_encode(array("result1" => $res));
                    } else if ($val1 == 1) {
                        if ($val2) {
                            unset($_SESSION['csrf_token']);
                            $_SESSION['uid'] = $val;
                            echo json_encode(array("result1" => "home.php"));
                        } else {
                            echo json_encode(array("result1" => "error2"));
                        }
                    }
                }
            }
        } else {
            echo json_encode(array("result1" => "error", "result2" => _("Please check I'm not a Robot")));
        }
    } else {
        echo json_encode(array("result1" => 'error', "result2" => "CSRF token validation failed."));
    }
}

function getSslPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function getBrowser() {
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version = "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    } elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'Windows';
    }

    // Next get the name of the useragent yes seperately and for good reason
    if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    } elseif (preg_match('/Firefox/i', $u_agent)) {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    } elseif (preg_match('/Chrome/i', $u_agent)) {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    } elseif (preg_match('/Safari/i', $u_agent)) {
        $bname = 'Apple Safari';
        $ub = "Safari";
    } elseif (preg_match('/Opera/i', $u_agent)) {
        $bname = 'Opera';
        $ub = "Opera";
    } elseif (preg_match('/Netscape/i', $u_agent)) {
        $bname = 'Netscape';
        $ub = "Netscape";
    }

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';

    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);

    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) {
            $version = $matches['version'][0];
        } else {
            $version = $matches['version'][1];
        }
    } else {
        $version = $matches['version'][0];
    }

    // check if we have a number
    if ($version == null || $version == "") {
        $version = "?";
    }
    return array(
        'userAgent' => $u_agent,
        'name' => $bname,
        'version' => $version,
        'platform' => $platform,
        'pattern' => $pattern
    );
}

function get_ip_address() {
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip); // just to be safe
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
    }
}

?>
