<main class="container" v-if="page === 'host'" v-scope @vue:mounted="mounted">
    <h1>Conectar un HOST</h1>
    <form action="action/conectar_moodle.php" method="post" v-scope="{host: null}">
        <div class="grid">
            <?php
            if ($db->count('moodle_host') > 0) : ?>
                <label for="moodle-host">
                    Moodle host
                    <input list="moodle-hosts" name="moodle-host" placeholder="Moodle host" required v-model="host">
                </label>
            <?php else : ?>
                <p>No hay hosts registrados</p>
            <?php endif ?>
            <label for="agregar-host">
                Agregar host
                <button id="agregar-host" type="button" @click="page = 'new_host'">
                    <i class="fas fa-plus"></i>
                </button>
            </label>
        </div>
        <?php if ($db->count('moodle_host') > 0) : ?>
            <datalist id="moodle-hosts" v-for="host in hosts">
                <option :value="host.host">
                    {{ host.etiqueta }}
                </option>
            </datalist> 
        <?php endif ?>
        <div class="grid">
            <button type="button" :disabled="!host" @click="editHost(host)">Editar <i class="fas fa-edit"></i></button>
            <button type="submit" :disabled="!host">Conectar <i class="fas fa-database"></i></button>
        </div>
    </form>
</main>

<div v-else-if="page === 'new_host'">
    <?php require 'new_host.php' ?>
</div>

<div v-else>
    <?php require 'edit_host.php' ?>
</div>



<script>
    PetiteVue.createApp({
        // state
        loading: false,
        page: 'host',
        // data
        hosts: [],
        current_host: null,

        async editHost(host) {
            this.loading = true
            const hosts = await fetch(`http://www.localhost:3000/moodle_host?etiqueta=eq.${host}`, {
                headers: {
                    'Prefer': 'plurality=singular'
                }
            })

            if (!hosts.ok) {
                this.loading = false
                alert('Error al obtener el host: ' + hosts.status)
                return
            }

            const data = await hosts.json()
            this.current_host = data[0]
            this.loading = false

            this.page = 'edit_host'
        },

        async mounted() {
            this.loading = true
            const hosts = await fetch('http://www.localhost:3000/moodle_host')
            const data = await hosts.json()
            this.loading = false

            this.hosts = data
        }
    }).mount()
</script>