<?php
session_start();

require("../includes/db_connect.php");
require_once("../includes/get_browser.php");
require_once("../includes/get_ip_info.php");

$email = "";
$password = "";

$admin_login = 0;

$browser_client = new BrowserClient();
$ip_info_client = new IPClient();

$recaptcha_secret = "6LdYt34pAAAAANJ3BPmbvqFPPFb9YdEzB6ln-rMz";
$response_token = $_POST['g-recaptcha-response'] ?? '';

$verify_url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
    'secret' => $recaptcha_secret,
    'response' => $response_token
);

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);

$context  = stream_context_create($options);
$verify_result = file_get_contents($verify_url, false, $context);
$verify_response = json_decode($verify_result);

if (!$verify_response->success) {
    
   
    die("reCAPTCHA verification failed. Please try again.");
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ((!empty($_POST['email'])) && (!empty($_POST['password']))) {

        if ($conn) {
            try {

                $admin_login = 0;

                $email = $_POST['email'];
                $password = $_POST['password'];

                if (strpos($email, '@') !== false) {
                    //if it contains email
                    create_access_token();
                } else {

                    $sql = "SELECT * FROM admin_users WHERE accountId = ? LIMIT 1";
                    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $sth->execute([$email]);
                    $admin_users = $sth->fetchAll();

                    if (count($admin_users) > 0) {

                        foreach ($admin_users as $key => $value) {
                            $acc_password = $value['password'];

                            if (password_verify($password, $acc_password)) {

                                $_SESSION['adm_accountId'] = $email;
                                $_SESSION['adm_accessToken'] = $acc_password;

                                die("admin_login");
                            } else {
                                die("Invalid login credentials. Please check and try again.");
                            }
                        }
                    } else {
                        die("Invalid login credentials. Please check and try again.");
                    }
                }
            } catch (PDOException $e) {
                die('An unexpected error occurred. Connection failed');
            }
        } else {
            die('An unexpected error occurred. Connection failed.');
        }
    } else {
        die('Invalid user information.');
    }
} else {
    die('Invalid request.');
}


function create_access_token()
{

    global $email, $password, $conn;

    $usr_sql = "SELECT * FROM users WHERE email =? LIMIT 1";
    $usr_sth = $conn->prepare($usr_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
    $usr_sth->execute([$email]);
    $users = $usr_sth->fetchAll();

    if (count($users) > 0) {

        foreach ($users as $key => $value) {
            $accountId = $value['accountId'];
            $email_confirmation = $value['email_confirmation'];
            $email_tutorial = ($value['email_confirmation'] == 1) ? true : false ;
            $fullName = $value['fullname'];
            $acc_password = $value['password'];
            $status = $value['status'];
            $country = $value['country'];

            if ($email_confirmation == 0) {

                $token = 'qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM0123456789!$*';
                $token = str_shuffle($token);
                $token = substr($token, 0, 100);

                $user_sql = "UPDATE users SET access_token=?, email_confirmation=? WHERE accountId=?";

                $update_user = $conn->prepare($user_sql)->execute([$token, 0, $accountId]);

                if ($update_user) {
                    send_vcode($accountId, $email, $token, $fullName);
                } else {
                    die("Unable to send verification mail. Please try again.");
                } 
            } else {

                if (password_verify($password, $acc_password)) {
 
                    if ($status == 1) {
                        
                        $_SESSION['usr_accountId'] = $accountId;
                        $_SESSION['usr_fullName'] = $fullName;
                        $_SESSION['usr_email'] = $email;
                        $_SESSION['usr_country'] = $country;
                        create_login_session();
                        if(!$email_tutorial) {
                            send_tutorial($accountId, $email, $fullName);
                        }
                    } else {
                        die("This account has been disabled. Kindly contact management for more details.");
                    }
                } else {
                    die("Invalid login credentials. Please check and try again.");
                }
            }
        }
    } else {
        die("Invalid login credentials. Please check and try again.");
    }
}


function send_vcode($accountId, $email, $token, $fullName)
{

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "accountId=$accountId&email=$email&token=$token&name=$fullName");
    curl_setopt($ch, CURLOPT_URL, 'https://www.rocketta.io/email/send_verification_mail');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_exec($ch);
    curl_close($ch);
    die("verify-account");
}

function send_tutorial($accounId, $email, $fullName)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "accountId=$accountId&email=$email&name=$fullName");
    curl_setopt($ch, CURLOPT_URL, 'https://www.rocketta.io/email/send_trading_tutorial_email');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_exec($ch);
    curl_close($ch);
    die("send-tutorial");
}

function create_login_session()
{

    global $browser_client, $ip_info_client, $conn;

    $ua = $browser_client->get_browser_info();

    $browser_name = $ua['name'];
    $os = $ua['platform'];

    $ipaddress = get_client_ip();

    $country = $ip_info_client->get_ip_info($ipaddress, "Country");

    $ls_sql = "INSERT INTO login_sessions (os, accountId, browser, ip_address, country) VALUES (?,?,?,?,?)";
    $create_session = $conn->prepare($ls_sql)->execute([$os, $_SESSION['usr_accountId'], $browser_name, $ipaddress, $country]);

    if ($create_session) {
        set_session_token();
    } else {
        die("An unexpected error occurred. Please try again.");
    }
}

function set_session_token()
{
    $session_token = base64_encode(random_bytes(10)); // ~14 characters, includes /=+

    global $conn;

    $sql = "SELECT accountId FROM session_tokens WHERE accountId = :accountId LIMIT 1";
    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
    $sth->execute([':accountId' => $_SESSION['usr_accountId']]);
    $session_tokens = $sth->fetchAll();

    if (count($session_tokens) > 0) {

        $session_tokens_sql = "UPDATE session_tokens SET session_token=? WHERE accountId=?";

        $update_session_token = $conn->prepare($session_tokens_sql)->execute([$session_token, $_SESSION['usr_accountId']]);

        if ($update_session_token) {
            $_SESSION['usr_accessToken'] = $session_token;
            die("success");
        } else {
            die("An unexpected error occurred. Please try again.");
        }
    } else {

        $session_tokens_sql = "INSERT INTO session_tokens (accountId, session_token) VALUES (?,?)";
        $create_session_token = $conn->prepare($session_tokens_sql)->execute([$_SESSION['usr_accountId'], $session_token]);

        if ($create_session_token) {
            $_SESSION['usr_accessToken'] = $session_token;
            die("success");
        } else {
            die("An unexpected error occurred. Please try again.");
        }
    }
}


function get_client_ip()
{
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if (getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if (getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if (getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if (getenv('HTTP_FORWARDED'))
        $ipaddress = getenv('HTTP_FORWARDED');
    else if (getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}