<?php
require_once 'vendor/autoload.php';
session_start();


function methods($methodSchemas)
{
    $requestMethod = $_SERVER['REQUEST_METHOD'];

    if (!array_key_exists($requestMethod, $methodSchemas)) {
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        exit();
    }

    $data = json_decode(file_get_contents('php://input'), true);

    // Validate against the schema for the current request method
    $schema = $methodSchemas[$requestMethod];
    if (!$schema->validate($data)) {
        serverError('Error de validación', 'Los datos enviados no son válidos');
        exit();
    }
}


function returnResponse($status = 200, $data = null, $error = null, $message = null)
{
    header('Content-Type: application/json');
    http_response_code($status);

    $response = [];

    if ($error) {
        $response['error'] = true;
        if ($message) {
            $response['message'] = $message; // User-friendly error message
        }
        if ($data) {
            $response['details'] = $data; // Full error details (optional based on system config)
        }
    } else {
        $response['error'] = false;
        if ($data !== null) {
            $response['data'] = $data; // Data payload for successful response
        }
        if ($message) {
            $response['message'] = $message; // Success message or additional info
        }
    }

    echo json_encode($response);
    exit();
}
/*
// Usage:
// For a successful response with data
returnResponse(200, ['id' => 1, 'name' => 'John Doe']);

// For an error response with a message and full error details
returnResponse(500, $exception->getTraceAsString(), true, 'Internal Server Error');

// For a not found response with just a message
returnResponse(404, null, true, 'The requested resource was not found.');
*/

// Function server error
function serverError($title, $message)
{
    header('Content-Type: text/html');
    http_response_code(500);

    require "{$_SERVER['DOCUMENT_ROOT']}/action/error.php";
    exit();
}

// DOTENV: load environment variables from .env file
try {
    $dotenv = Dotenv\Dotenv::createImmutable($_SERVER['DOCUMENT_ROOT']);
    $dotenv->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    serverError('Error de configuración', 'No se pudo cargar el archivo de configuración');
    exit();
}

// POSTGRES: load PostgresDb class
use \SeinopSys\PostgresDb;

function makeConnection($hostOrConnectionString, $port = null, $dbname = null, $user = null, $password = null): PostgresDb
{
    $connectionString = is_null($port) ? $hostOrConnectionString : "pgsql:host=$hostOrConnectionString;port=$port;dbname=$dbname;user=$user;password=$password";

    try {
        $pdo = new PDO($connectionString);
        $db = new PostgresDb();
        $db->setConnection($pdo);
        return $db;
    } catch (PDOException $e) {
        serverError('Error de conexión', 'No se pudo conectar a la base de datos: ' . $e->getMessage() . ' ' . $connectionString);
        exit();
    }
}

# default DB connection
$db = makeConnection($_ENV['POSTGRES_HOST'], $_ENV['POSTGRES_PORT'], $_ENV['POSTGRES_DBNAME'], $_ENV['POSTGRES_USER'], $_ENV['POSTGRES_PASSWORD']);
$sgi_db = makeConnection($_ENV['SGI_POSTGRES_HOST'], $_ENV['SGI_POSTGRES_PORT'], $_ENV['SGI_POSTGRES_DBNAME'], $_ENV['SGI_POSTGRES_USER'], $_ENV['SGI_POSTGRES_PASSWORD']);
if (isset($_SESSION['moodle_db']))
    $moodle_db = makeConnection($_SESSION['moodle_db']);
