<?php
if ($_POST['password-1'] != $_POST['password-2']) {
    header('location: /login/resetPassword.php?result=failed');
    exit;
}

require_once "{$_SERVER['DOCUMENT_ROOT']}/login/php/authFunctions.php";
$user_password = password_hash($_POST['password-1'], PASSWORD_BCRYPT, ["cost" => 12]);

if (isset($_POST['user_uuid'])) {
    session_start();

    if (!isset($_SESSION['user']['user_uuid'])) {
        header('location: /login/resetPassword.php?result=failed');
        exit;
    }

    $user_uuid = $_SESSION['user']['user_uuid'];
    $sql = "UPDATE system_users SET user_password = ?, 
            user_password_reset_token = NULL,
            user_password_reset_expires = NULL
        WHERE user_uuid = ?";
    $userSql = "SELECT COUNT(*) FROM system_users WHERE user_uuid = ?";
    $whereValue = $user_uuid;

} elseif (isset($_POST['user_password_reset_token'])) {
    $user_password_reset_token = $_POST['user_password_reset_token'];
    $sql = "UPDATE system_users SET user_password = ?, 
            user_password_reset_token = NULL,
            user_password_reset_expires = NULL,
            user_verified_email = 1,
            user_status = 'active'
        WHERE user_password_reset_token = ? AND user_status IN ('active', 'pending')";
    $userSql = "SELECT COUNT(*) FROM system_users WHERE user_password_reset_token = ?";
    $whereValue = $user_password_reset_token;
}

function checkUserExists($whereValue, $conn, $sql)
{
    $stmt = $conn->prepare($sql);
    $count = 0;
    $stmt->bind_param("s", $whereValue);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    return $count > 0;
}


if (!checkUserExists($whereValue, $GLOBALS['conn'], $userSql)) {
    header('location: /');
    exit;
}

$stmt = $GLOBALS['conn']->prepare($sql);
$stmt->bind_param("ss",
    $user_password,
    $whereValue
);


if ($stmt->execute()) {
    header('location: /login/resetPassword.php?result=success');
} else {
    header('location: /login/resetPassword.php?result=failed');
}
exit;