<?php
session_start();

// 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';
}

if ($_SESSION['initialized'] && 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'])) {
    exec_statement('UPDATE user SET is_active = true WHERE user_id = ' . $_COOKIE['user_id'] . ';', 1);
    exec_statement('UPDATE user SET last_active = CURRENT_TIMESTAMP WHERE user_id = ' . $_COOKIE['user_id'] . ';', 1);

    $query = 'SELECT user_id, username, email, role_id, profile_picture FROM user WHERE user_id = ' . $_COOKIE['user_id'] . ';';
    $user = query_one_result($query);
    $time = time() + 60 * 60 * 1;
    cookies($user, $time);
} else if (isset($_COOKIE['remember_user'])) {
    $query = 'SELECT * FROM remember_user WHERE token = "' . $_COOKIE['remember_user'] . '";';
    $remember = query_one_result($query);
    $query = 'SELECT user_id, username, email, role_id, profile_picture FROM user WHERE user_id = ' . $remember['user_id'] . ';';
    $user = query_one_result($query);

    exec_statement('UPDATE user SET is_active = true WHERE user_id = ' . $user['user_id'] . ';', 1);
    exec_statement('UPDATE user SET last_active = CURRENT_TIMESTAMP WHERE user_id = ' . $user['user_id'] . ';', 1);

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