<?php

require_once "{$_SERVER['DOCUMENT_ROOT']}/bin/php/db_connect.php";
function checkLoginAttempts()
{
    $stmt = $GLOBALS['conn']->prepare("SELECT address 
        FROM ip_login_attempts 
        WHERE address LIKE ? 
        AND timestamp > (UNIX_TIMESTAMP() - 600)
    ");
    $stmt->bind_param('s', $_SERVER['REMOTE_ADDR']);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows;
}

function addLoginAttempts()
{
    $ip = $_SERVER["REMOTE_ADDR"];
    $stmt = $GLOBALS['conn']->prepare("INSERT INTO ip_login_attempts (address, timestamp) VALUES (?, UNIX_TIMESTAMP())");
    $stmt->bind_param('s', $ip);
    $stmt->execute();
    $stmt->close();
}

function setTimeZoneCookie()
{ ?>
    <script src="/src/js/timeZoneCookie.js"></script>
<?php }

function getUserTimezone()
{
    $default_timezone = 'America/New_York';
    if (isset($_COOKIE['user_timezone']) && in_array($_COOKIE['user_timezone'], DateTimeZone::listIdentifiers())) {
        $timezone = $_COOKIE['user_timezone'];
    } else {
        $timezone = $default_timezone;
    }

    return $timezone;
}

function setSessionParams()
{
    if (isset($_SESSION['user']['user_uuid'])) {
        $user_uuid = $_SESSION['user']['user_uuid'];
        $stmt = $GLOBALS['conn']->prepare("SELECT * FROM system_users INNER JOIN system_user_groups ON system_users.user_group_uuid = system_user_groups.user_group_uuid WHERE user_uuid = ? LIMIT 1");
        $stmt->bind_param('s', $user_uuid);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();

        $_SESSION['user'] = ['user_uuid' => $user['user_uuid'],
                'user_email' => $user['user_email'],
                'user_first_name' => $user['user_first_name'],
                'user_full_name' => $user['user_full_name'],
                'user_group_uuid' => $user['user_group_uuid'],
                'user_group_weight' => $user['user_group_weight'],
                'user_group_type' => $user['user_group_type'],
                'user_pref_language' => $user['user_pref_language'],
                'user_two_factor_enabled' => $user['user_two_factor_enabled'],
                'user_profile_picture' => $user['user_profile_picture'],
                'user_profile_picture_thumbnail' => $user['user_profile_picture_thumbnail'],
                'user_timezone' => getUserTimezone(),
        ];

        $stmt = $GLOBALS['conn']->prepare("SELECT system_user_group_permissions.permission_value, system_permissions.permission_name 
                FROM system_user_group_permissions
                INNER JOIN system_permissions ON system_user_group_permissions.permission_uuid = system_permissions.permission_uuid
                WHERE user_group_uuid = ?");
        $stmt->bind_param('s', $user['user_group_uuid']);
        $_SESSION['permission'] = array();
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $_SESSION['permission'][$row['permission_name']] = $row['permission_value'];
        }
    }
}

function loginUser($user_uuid)
{
    $update = $GLOBALS['conn']->prepare("UPDATE system_users SET user_last_login_timestamp = ? WHERE user_uuid = ?");
    $update->bind_param('is', time(), $user_uuid);
    $update->execute();

    session_regenerate_id(true);

    $_SESSION['user'] = ['user_uuid' => $user_uuid];

    setSessionParams();
}

# link the verification code input and check if it's a valid code.
function linkVerificationPosts()
{
    $codeParts = [];
    $allSet = true;
    for ($i = 1; $i <= 6; $i++) {
        $key = 'verification-' . $i;
        if (isset($_POST[$key]) && $_POST[$key] !== '') {
            $codeParts[] = $_POST[$key];
        } else {
            $allSet = false;
            break;
        }
    }

    if ($allSet) {
        return implode('', $codeParts);
    } else {
        return false;
    }
}
