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

Security::init();

$id = (int)($_GET['id'] ?? 0);
$s = $pdo->prepare("SELECT * FROM products WHERE id = ? AND active = 1");
$s->execute([$id]);
$p = $s->fetch();

$siteName = 'Cuboid Store';
$siteURL = $config['app']['url'];
$pageTitle = $p ? htmlspecialchars($p['name']) : 'Checkout';
$pageDescription = $p ? 'Comprar ' . htmlspecialchars($p['name']) : 'Completar compra';

$message = '';
$downloadLink = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $p) {
    $email = trim($_POST['email'] ?? '');
    
    if (!Security::validateEmail($email)) {
        $message = 'Por favor ingresa un correo válido';
    } else {
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+7 days'));
        
        $downloadsLimit = $p['downloads_limit'] ?? 3;
        $stmt = $pdo->prepare("INSERT INTO downloads (email, token, product_id, expires_at, downloads_limit, downloads_used) VALUES (?, ?, ?, ?, ?, 0)");
        $stmt->execute([$email, $token, $p['id'], $expires, $downloadsLimit]);
        
        $downloadId = $pdo->lastInsertId();
        $downloadLink = 'https://cuboid-ia.com/download.php?token=' . $token;
        
        $subject = 'Tu descarga - Cuboid Store';
        $body = "Hola,\n\nTu compra fue exitosa.\n\nProducto: {$p['name']}\nPrecio: {$p['price']} CLP\n\nDescarga tu archivo aquí: $downloadLink\n\nEste enlace expira en 7 días y tiene 3 descargas permitidas.\n\nSaludos,\nCuboid Store";
        
        $headers = "From: {$config['smtp']['from']}\r\nContent-Type: text/plain; charset=UTF-8";
        @mail($email, $subject, $body, $headers);
        
        header('Location: success.php?id=' . $downloadId);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?=$pageTitle?> - Checkout - Cuboid Store</title>
    
    <meta name="description" content="<?=$pageDescription?>">
    <meta name="robots" content="noindex, follow">
    <?php if($p): ?>
    <link rel="canonical" href="<?=$siteURL?>/checkout.php?id=<?=$p['id']?>">
    <?php endif; ?>
    
    <meta property="og:type" content="website">
    <meta property="og:site_name" content="<?=htmlspecialchars($siteName)?>">
    <meta property="og:title" content="<?=$pageTitle?> - Checkout">
    <meta property="og:description" content="<?=$pageDescription?>">
    
    <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="checkout-container">
        <?php if ($p): ?>
        <a href="product.php?id=<?=$id?>" class="back-link">
            <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
            </svg>
            Volver al producto
        </a>

        <div class="checkout-card">
            <h1 style="margin-bottom: 1.5rem;">Finalizar Compra</h1>
            
            <?php if ($message): ?>
            <div class="alert <?=strpos($message, 'exitosa') !== false ? 'alert-success' : ''?>" style="margin-bottom: 1.5rem; padding: 1rem; border-radius: 8px; background: <?=strpos($message, 'exitosa') !== false ? '#dcfce7' : '#fee2e2'?>; color: <?=strpos($message, 'exitosa') !== false ? '#166534' : '#991b1b'?>;">
                <?=htmlspecialchars($message)?>
            </div>
            <?php endif; ?>

            <?php if ($downloadLink): ?>
            <div style="margin-top: 1.5rem; padding: 1rem; background: var(--bg-secondary); border-radius: 8px;">
                <p style="margin-bottom: 0.5rem; font-weight: 600;">Tu enlace de descarga:</p>
                <a href="<?=$downloadLink?>" style="color: #3b82f6; word-break: break-all;"><?=$downloadLink?></a>
            </div>
            <?php endif; ?>

            <div style="text-align: left; margin-bottom: 2rem; padding-bottom: 1.5rem; border-bottom: 1px solid var(--border-color);">
                <p style="color: var(--text-secondary); margin-bottom: 0.5rem;">Producto</p>
                <p style="font-size: 1.25rem; font-weight: 600;"><?=htmlspecialchars($p['name'])?></p>
                <p style="font-size: 1.5rem; font-weight: 700; color: #3b82f6; margin-top: 1rem;">
                    $<?=number_format($p['price'], 0, ',', '.')?> CLP
                </p>
            </div>

            <?php if (!$downloadLink): ?>
            <form method="post">
                <div class="form-group">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 500;">Correo electrónico</label>
                    <input type="email" name="email" class="form-input" placeholder="tu@email.com" required>
                </div>
                <button type="submit" class="btn btn-primary" style="width: 100%;">
                    Pagar y descargar
                </button>
                <p style="margin-top: 1rem; font-size: 0.75rem; color: var(--text-secondary); text-align: center;">
                    Para pruebas: ingresa tu email y descarga directamente
                </p>
            </form>
            <?php else: ?>
            <a href="index.php" class="btn btn-secondary" style="margin-top: 1rem; display: block; text-align: center;">Volver a la tienda</a>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <div class="checkout-card">
            <p>Producto no encontrado</p>
            <a href="index.php" class="btn btn-secondary" style="margin-top: 1rem;">Volver a la tienda</a>
        </div>
        <?php endif; ?>
    </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="#">Ayuda</a>
                <a href="#">Términos</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>
