<?php
require_once "dependencies.php";

if (isset($_SESSION['moodle_db'], $_SESSION['user'])) {
    $page = 'menu';
} else if (isset($_SESSION['user'])) {
    $page = 'host';
} else {
    $page = 'login';
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administración de calificaciones</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@1/css/pico.min.css">
    <script src="https://unpkg.com/petite-vue"></script>
    <script>
        const store = PetiteVue.reactive({
            error: null,
            loading: false,
            token: sessionStorage.getItem('token'),

            async fetch(url, options = {}, custom_error = null) {
                store.loading = true
                const response = await fetch(url, {
                    ...options,
                    headers: {
                        ...options.headers,
                        'Authorization': `Bearer ${store.token}`
                    }
                })
                store.loading = false

                if (!response.ok) {
                    store.error = custom_error ?? {
                        title: 'Error en la autorización',
                        message: 'Puede ser que tu token haya expirado o que no tengas permisos para realizar esta acción',
                        avoidable: false,
                        actions: [{
                            label: 'Cerrar sesión',
                            handler: () => {
                                window.location.href = '/action/desconectar.php?action=sign-out'
                            },
                            class: 'primary'
                        }]
                    }
                    return []
                }

                return response.json()
            },
        });
    </script>
</head>

<body>
    <nav>
        <div class="container">
            <div class="grid">
                <h1>Administración de calificaciones</h1>
                <?php if (isset($_SESSION['user']) || isset($_SESSION['moodle_db'])) : ?>
                    <div class="grid">
                        <?php if (isset($_SESSION['user'])) : ?>
                            <form action="/action/desconectar.php">
                                <input type="hidden" name="action" value="sign-out">
                                <button type="submit" @click="sessionStorage.removeItem('token')">Cerrar sesión <i class="fas fa-sign-out-alt"></i></button>
                            </form>
                        <?php endif; ?>
                        <?php if (isset($_SESSION['moodle_db'])) : ?>
                            <form action="/action/desconectar.php">
                                <input type="hidden" name="action" value="desconectar">
                                <button type="submit">Desconectar <i class="fas fa-times-circle"></i></button>
                            </form>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </nav>
    <div class="container" v-scope>
        <dialog :open="store.loading">
            <div class="grid">
                <button aria-busy="true" class="secondary"></button>
            </div>
        </dialog>

        <dialog :open="store.error !== null" v-if="store.error">
            <article>
                <header>
                    <a href="#close" aria-label="Close" class="close" @click="store.error = null" v-if="store.error?.avoidable"></a>
                    <strong>
                        {{ store.error?.title }}
                    </strong>
                </header>
                <p>
                    {{ store.error?.message }}

                </p>
                <br>
                <div class="grid">
                    <button v-for="action in store.error?.actions ?? []" @click="action.handler" :class="action.class">
                        {{ action.label }}
                    </button>
                </div>
            </article>
        </dialog>
        <?php
        if (!isset($page)) {
            throw new Exception('No se ha definido la variable $page');
        }
        require "{$_SERVER['DOCUMENT_ROOT']}/pages/$page.html";
        ?>
    </div>

</body>

</html>