<?php

require_once __DIR__ . '/session.php';
require_once __DIR__ . '/database.php';
require_once __DIR__ . '/functions.php';

$db = Database::connect();

/*
|--------------------------------------------------------------------------
| LOGIN USER
|--------------------------------------------------------------------------
*/

function login($email, $password)
{
    global $db;

    $sql = "SELECT
            users.*,
            roles.role_name,
            corps_members.state_code AS corps_state_code
        FROM users
        INNER JOIN roles
            ON users.role_id = roles.id
        LEFT JOIN corps_members
            ON corps_members.user_id = users.id
        WHERE users.email = ?
        LIMIT 1";

    $stmt = $db->prepare($sql);

    $stmt->execute([$email]);

    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {

        return false;

    }

    if (!password_verify($password, $user['password'])) {

        return false;

    }

    $_SESSION['user'] = [
        'id' => $user['id'],
        'firstname' => $user['firstname'],
        'lastname' => $user['lastname'],
        'email' => $user['email'],
        'role' => $user['role_name'],
        'avatar' => $user['avatar'],
        'state_code' => $user['corps_state_code'] ?? null,
    ];
    

    return true;
}

/*
|--------------------------------------------------------------------------
| LOGOUT
|--------------------------------------------------------------------------
*/

function logout()
{
    $_SESSION = [];

    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();

        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params["path"],
            $params["domain"],
            $params["secure"],
            $params["httponly"]
        );
    }

    session_destroy();

    header("Location: ../auth/login.php");
    exit;
}