<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

$root = dirname(__DIR__);
require $root . '/core/DB.php';
require $root . '/core/config.php';
require $root . '/core/Security.php';

Security::init();

$token = Security::sanitizeInput($_GET['token'] ?? '');
$error = null;
$download = null;
$product = null;

if (!$token) {
    $error = 'Token requerido';
} else {
    $stmt = $pdo->prepare("SELECT d.*, p.name as product_name, p.file FROM downloads d JOIN products p ON d.product_id = p.id WHERE d.token = ?");
    $stmt->execute([$token]);
    $download = $stmt->fetch();

    if (!$download) {
        $error = 'Token inválido o inexistente';
    } elseif ($download['downloads_used'] >= $download['downloads_limit']) {
        $error = 'Límite de descargas alcanzado';
    } else {
        $expires = new DateTime($download['expires_at']);
        if ($expires < new DateTime()) {
            $error = 'Enlace expirado. Por favor solicita uno nuevo.';
        }
    }
}

if ($error) {
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Error de Descarga - Cuboid Store</title>
    
    <meta name="description" content="No se pudo completar la descarga. El enlace puede haber expirado o alcanzado el límite máximo.">
    <meta name="robots" content="noindex, follow">
    
    <meta property="og:type" content="website">
    <meta property="og:title" content="Error de Descarga - Cuboid Store">
    <meta property="og:description" content="No se pudo completar la descarga.">
    
    <link href="styles.css" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    
    <script>
        if (localStorage.getItem('darkMode') === 'true' || (!localStorage.getItem('darkMode') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
        }
    </script>
</head>
<body>
    <nav class="navbar">
        <div class="navbar-content">
            <a href="index.php" class="logo">Cuboid</a>
            <div class="nav-links">
                <a href="index.php" class="nav-link">Tienda</a>
                <button class="dark-toggle" onclick="toggleDarkMode()" title="Cambiar modo">
                    <svg class="sun-icon" width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"/></svg>
                    <svg class="moon-icon" width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display:none"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"/></svg>
                </button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="error-card">
            <div class="error-icon">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                </svg>
            </div>
            <h1>Error de Descarga</h1>
            <p class="error-message"><?=htmlspecialchars($error)?></p>
            <p class="error-description">
                <?php if ($download): ?>
                Has utilizado las <?=$download['downloads_used']?> de <?=$download['downloads_limit']?> descargas permitidas para este producto.
                <br>El enlace expiró el <?=date('d/m/Y', strtotime($download['expires_at']))?>.
                <?php else: ?>
                El enlace que intentas usar no es válido o ha expirado.
                <?php endif; ?>
            </p>
            <div class="error-actions">
                <a href="index.php" class="btn btn-primary">Volver a la Tienda</a>
                <a href="mailto:<?=htmlspecialchars($config['smtp']['from'])?>" class="btn btn-secondary">Contactar Soporte</a>
            </div>
        </div>
    </div>

    <footer class="footer">
        <div class="footer-content">
            <div class="footer-section">
                <h3>Cuboid Store</h3>
                <p>Tu tienda de archivos digitales segura y confiable.</p>
            </div>
            <div class="footer-section">
                <h3>Enlaces</h3>
                <a href="index.php">Inicio</a>
                <a href="admin/index.php">Admin</a>
            </div>
            <div class="footer-section">
                <h3>Soporte</h3>
                <a href="mailto:<?=htmlspecialchars($config['smtp']['from'])?>">Ayuda</a>
            </div>
        </div>
        <div class="footer-bottom">
            <p>&copy; 2026 Cuboid Store. Todos los derechos reservados.</p>
        </div>
    </footer>

    <script>
        function toggleDarkMode() {
            document.documentElement.classList.toggle('dark');
            localStorage.setItem('darkMode', document.documentElement.classList.contains('dark'));
            updateIcons(document.documentElement.classList.contains('dark'));
        }
        function updateIcons(isDark) {
            document.querySelector('.sun-icon').style.display = isDark ? 'none' : 'block';
            document.querySelector('.moon-icon').style.display = isDark ? 'block' : 'none';
        }
        updateIcons(document.documentElement.classList.contains('dark'));
    </script>
</body>
</html>
<?php
    exit;
}

$filePath = $download['file'];
if (!file_exists($filePath)) {
    http_response_code(404);
    exit;
}

$updateStmt = $pdo->prepare("UPDATE downloads SET downloads_used = downloads_used + 1 WHERE id = ?");
$updateStmt->execute([$download['id']]);

$filename = basename($filePath);
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($filePath));
header('Pragma: public');
readfile($filePath);
exit;
