<?php
session_start();
header("Content-Security-Policy: default-src 'self'; font-src 'self' https://www.nerdfonts.com/assets/fonts/Symbols-2048-em%20Nerd%20Font%20Complete.woff2; style-src 'self' 'unsafe-inline' https://nerdfonts.com/assets/css/webfont.css https://www.nerdfonts.com/assets/css/webfont.css; script-src 'self'; img-src 'self';");

// Initialize Composer.
require_once 'vendor/autoload.php';
require_once 'db_functions.php';
require_once 'account_functions.php';

// Load environment variables.
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->safeLoad();

// Set SESSION variable.
if (!isset($_SESSION['initialized'])) {
    $_SESSION['initialized'] = true;
    $_SESSION['theme'] = 'dark';
} else if (isset($_POST['theme'])) {
    $_SESSION['theme'] = $_POST['theme'];
    unset($_POST['theme']);
}

// Update the database and cookies to keep the user logged in.
if (isset($_COOKIE['user_id'])) {
    $conn = get_connection();
    $stmt = $conn->prepare('UPDATE user SET is_active = true WHERE user_id = ?');
    $stmt->bind_param('i', $_COOKIE['user_id']);
    $stmt->execute();

    $stmt = $conn->prepare('UPDATE user SET last_active = CURRENT_TIMESTAMP WHERE user_id = ?');
    $stmt->bind_param('i', $_COOKIE['user_id']);
    $stmt->execute();

    $stmt = $conn->prepare('SELECT user_id, username, email, role_id, profile_picture FROM user WHERE user_id = ?');
    $stmt->bind_param('i', $_COOKIE['user_id']);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    $time = time() + 60 * 15;
    cookies($user, $time);
} else if (isset($_COOKIE['remember_user'])) {
    $conn = get_connection();
    $stmt = $conn->prepare('SELECT * FROM remember_user WHERE token = ?');
    $stmt->bind_param('s', $_COOKIE['remember_user']);
    $stmt->execute();
    $remember = $stmt->get_result()->fetch_assoc();

    if (hash('sha256', $_SERVER['REMOTE_ADDR']) != $remember['remote_addr'] || (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && hash('sha256', $_SERVER['HTTP_X_FORWARDED_FOR']) != $remember['forwarded_for'])) {
        // TODO: Log the attempt to use a cookie from a different browser/device than the cookie was created
        echo "Naughty, you are trying to use someone else's cookie...";
    } else {
        $stmt = $conn->prepare('SELECT user_id, username, email, role_id, profile_picture FROM user WHERE user_id = ?');
        $stmt->bind_param('s', $remember['user_id']);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();

        $conn = get_connection();
        $stmt = $conn->prepare('UPDATE user SET is_active = true WHERE user_id = ?');
        $stmt->bind_param('i', $_COOKIE['user_id']);
        $stmt->execute();

        $stmt = $conn->prepare('UPDATE user SET last_active = CURRENT_TIMESTAMP WHERE user_id = ?');
        $stmt->bind_param('i', $_COOKIE['user_id']);
        $stmt->execute();

        $time = time() + 60 * 15;
        cookies($user, $time);
    }
}
