<?php
require_once "{$_SERVER['DOCUMENT_ROOT']}/dependencies.php";

use Respect\Validation\Validator as v;

/* methods(['POST' => v::keySet(
    v::key('moodle-host', v::stringType()->notEmpty()),
)]); */

// method must be POST
if (!isset($_SESSION['user'])) {
    serverError(title: 'Error de conexión', message: 'No se ha iniciado sesión');
    exit();
}

try {
    // $db->query("INSERT INTO moodle_host (etiqueta, host, puerto, postgres_user, postgres_dbname, postgres_password, periodos_gema) VALUES (:etiqueta, :host, :puerto, :postgres_user, :postgres_dbname, PGP_SYM_ENCRYPT(:postgres_password, '{$_ENV['KEY_ENCRYPT']}'), :periodos_gema)", $params);
    $string_connection = $db->querySingle(
        "SELECT CONCAT('pgsql:host=', host, ';port=', puerto, ';dbname=', postgres_dbname, ';user=', postgres_user, ';password=', PGP_SYM_DECRYPT(postgres_password, '{$_ENV['KEY_ENCRYPT']}')) AS connection_string FROM moodle_host WHERE host = :host",
        ['host' => $_POST['moodle-host']]
    )['connection_string'];
    $_SESSION['moodle_db'] = $string_connection;
    header('Location: /');
} catch (\PDOException $th) {
    serverError(title: 'Error de conexión', message: $string_connection);

    exit();
}
