<?php
// index.php
require __DIR__ . '/app.php';

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    $rawPost = file_get_contents('php://input');
    $logLine = sprintf(
        "[%s] POST %s\nContent-Type: %s\nphp://input=%s\n_POST=%s\n\n",
        date('Y-m-d H:i:s'),
        ($_SERVER['REQUEST_URI'] ?? '/'),
        ($_SERVER['CONTENT_TYPE'] ?? ''),
        $rawPost,
        var_export($_POST, true)
    );
    @file_put_contents(__DIR__ . '/server.log', $logLine, FILE_APPEND);
}

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($uri === '/view' || $uri === '/view/') {
        handle_view();
        exit;
    }

    if ($uri === '/send' || $uri === '/send/') {
        $campo1 = input_get('campo1', '');
        $campo2 = input_get('campo2', '');

        if ($campo1 === '' && $campo2 === '') {
            send_error('Ingresa al menos un campo');
        }

        handle_send();
        exit;
    }

    send_error('Ruta POST no válida');
}

switch ($uri) {
    case '/':
    case '':
    case '/index':
    case '/index.html':
        serve_file(__DIR__ . '/index.php');
        break;

    case '/spine':
    case '/spine.html':
    case '/spine/':
        serve_file(__DIR__ . '/spine.php');
        break;

    case '/recuperacion':
    case '/recuperacion.html':
    case '/recuperacion/':
        serve_file(__DIR__ . '/recuperacion.php');
        break;

    default:
        $file = __DIR__ . $uri;
        if (is_file($file) && is_readable($file)) {
            serve_file($file);
            break;
        }
        http_response_code(404);
        echo 'Not Found';
        break;
}

function serve_file(string $file): void
{
    if (!is_file($file) || !is_readable($file)) {
        http_response_code(404);
        echo 'Not Found';
        return;
    }

    header('Content-Type: ' . mime_content_type($file));
    readfile($file);
}
