<?php
session_start();
include 'conexion.php';

// 1. Capturamos el ID y validamos
if (isset($_GET['id'])) {
    $id = mysqli_real_escape_string($conexion, $_GET['id']);
    $resultado = mysqli_query($conexion, "SELECT * FROM materiales WHERE id = '$id'");
    $material = mysqli_fetch_assoc($resultado);

    if (!$material) {
        header("Location: index.php");
        exit;
    }

    // --- LÓGICA DE CUPONES ---
    $precio_original = (float)$material['precio'];
    $precio_final = $precio_original;
    $descuento_aplicado = 0;
    $mensaje_cupon = "";

    if (isset($_POST['aplicar_cupon'])) {
        $codigo = mysqli_real_escape_string($conexion, $_POST['codigo_cupon']);
        // Buscamos si el cupón existe y está activo
        $sql_cupon = "SELECT * FROM cupones WHERE codigo = '$codigo' AND estado = 'activo' AND (fecha_expiracion >= CURDATE() OR fecha_expiracion IS NULL)";
        $res_cupon = mysqli_query($conexion, $sql_cupon);
        
        if ($cupon = mysqli_fetch_assoc($res_cupon)) {
            $porcentaje = $cupon['descuento_porcentaje'];
            $descuento_aplicado = $precio_original * ($porcentaje / 100);
            $precio_final = $precio_original - $descuento_aplicado;
            $mensaje_cupon = "<div class='alert alert-success py-1 mt-2 small fw-bold'><i class='fas fa-check-circle me-1'></i> Cupón '$codigo' aplicado (-$porcentaje%)</div>";
        } else {
            $mensaje_cupon = "<div class='alert alert-danger py-1 mt-2 small fw-bold'><i class='fas fa-times-circle me-1'></i> Cupón no válido.</div>";
        }
    }

    // --- BLOQUE DE MERCADO PAGO (USA EL PRECIO FINAL) ---
    $access_token = 'APP_USR-3711109459067211-020513-873a3c3d9020f870e7a23c36d0473636-3183322513'; 

    $url = "https://api.mercadopago.com/checkout/preferences";
    $data = [
        "items" => [
            [
                "title" => $material['titulo'] . ($descuento_aplicado > 0 ? " (Con Descuento)" : ""),
                "quantity" => 1,
                "unit_price" => (float)$precio_final, // <-- Aquí enviamos el precio con descuento
                "currency_id" => "PEN"
            ]
        ],
        "external_reference" => $id, 
        "back_urls" => [
            "success" => "https://edujoam.com/exito.php",
            "failure" => "https://edujoam.com/index.php",
            "pending" => "https://edujoam.com/index.php"
        ],
        "auto_return" => "approved"
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $access_token", "Content-Type: application/json"]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $response = curl_exec($ch);
    $result = json_decode($response, true);
    curl_close($ch);

    $preference_id = isset($result['id']) ? $result['id'] : '';

    $ext = pathinfo($material['archivo_url'], PATHINFO_EXTENSION);
    $es_zip = ($ext == 'zip' || $ext == 'rar');

} else {
    header("Location: index.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $material['titulo']; ?> - Edujoam</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://sdk.mercadopago.com/js/v2"></script>
    <style>
        body { background-color: #f4f7f6; }
        .card-detalle { border-radius: 25px; border: none; overflow: hidden; }
        .precio-tag { font-size: 3.5rem; color: #0d6efd; font-weight: 850; letter-spacing: -1px; }
        .precio-tachado { text-decoration: line-through; color: #adb5bd; font-size: 1.5rem; }
        .feature-item { padding: 12px; background: #f8f9fa; border-radius: 15px; margin-bottom: 10px; border: 1px solid #edf0f2; }
        .btn-whatsapp { background-color: #25d366; color: white; border-radius: 50px; padding: 10px 20px; transition: 0.3s; }
        .relacionado-card { border-radius: 20px; transition: 0.3s; border: 1px solid #eee; }
        .relacionado-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.05); }
    </style>
</head>
<body>
    <?php include 'navbar.php'; ?>
    
    <div class="container mb-5 mt-4">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="card shadow-lg card-detalle bg-white">
                    <div class="card-body p-0">
                        <div class="row g-0">
                            <div class="col-md-7 p-4 p-md-5">
                                <div class="mb-3">
                                    <span class="badge bg-primary-subtle text-primary px-3 rounded-pill me-2"><?php echo $material['nivel']; ?></span>
                                    <span class="badge bg-secondary-subtle text-secondary px-3 rounded-pill"><?php echo $material['area']; ?></span>
                                </div>
                                <h1 class="fw-bold text-dark display-6 mb-4"><?php echo $material['titulo']; ?></h1>
                                <p class="text-muted lh-lg mb-4" style="white-space: pre-line;"><?php echo $material['descripcion']; ?></p>
                                
                                <div class="row g-3">
                                    <div class="col-sm-6">
                                        <div class="feature-item d-flex align-items-center">
                                            <i class="fas fa-bolt text-warning me-3 fs-4"></i>
                                            <span class="small fw-bold">Descarga Inmediata</span>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="feature-item d-flex align-items-center">
                                            <i class="fas <?php echo $es_zip ? 'fa-file-archive text-warning' : 'fa-file-pdf text-danger'; ?> me-3 fs-4"></i>
                                            <span class="small fw-bold">Formato <?php echo strtoupper($ext); ?></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-5 p-4 p-md-5 bg-light border-start text-center">
                                <div class="mb-4 text-start bg-white p-3 rounded-4 shadow-sm">
                                    <label class="small fw-bold text-muted mb-2">¿Tienes un cupón?</label>
                                    <form method="POST" class="d-flex gap-2">
                                        <input type="text" name="codigo_cupon" class="form-control form-control-sm border-primary" placeholder="Ej: BIENVENIDA">
                                        <button type="submit" name="aplicar_cupon" class="btn btn-primary btn-sm px-3">Aplicar</button>
                                    </form>
                                    <?php echo $mensaje_cupon; ?>
                                </div>

                                <p class="text-muted mb-0 fw-bold small uppercase">TOTAL A PAGAR</p>
                                <?php if ($descuento_aplicado > 0): ?>
                                    <span class="precio-tachado">S/ <?php echo number_format($precio_original, 2); ?></span>
                                <?php endif; ?>
                                <h3 class="precio-tag mb-4">S/ <?php echo number_format($precio_final, 2); ?></h3>
                                
                                <div class="mb-4">
                                    <?php if (isset($_SESSION['user_id'])): ?>
                                        <div id="wallet_container" class="shadow-sm rounded-4 overflow-hidden"></div>
                                    <?php else: ?>
                                        <div class="p-4 bg-white rounded-4 border border-warning text-center">
                                            <i class="fas fa-lock text-warning fa-2x mb-3"></i>
                                            <p class="small fw-bold">Inicia sesión para descargar</p>
                                            <a href="login.php" class="btn btn-primary w-100 rounded-pill fw-bold">ENTRAR</a>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <div class="pt-4 border-top">
                                    <a href="https://wa.me/519XXXXXXXXX?text=Dudas%20material:%20<?php echo urlencode($material['titulo']); ?>" 
                                       target="_blank" class="btn btn-whatsapp w-100 fw-bold shadow-sm">
                                        <i class="fab fa-whatsapp me-2 fs-5"></i>¿Dudas? WhatsApp
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mt-5">
                    <h4 class="fw-bold mb-4"><i class="fas fa-star text-warning me-2"></i>También te puede interesar</h4>
                    <div class="row g-3">
                        <?php
                        $nivel = $material['nivel'];
                        $rel_query = mysqli_query($conexion, "SELECT * FROM materiales WHERE nivel = '$nivel' AND id != '$id' LIMIT 3");
                        while($rel = mysqli_fetch_assoc($rel_query)): ?>
                            <div class="col-md-4">
                                <a href="detalles.php?id=<?php echo $rel['id']; ?>" class="text-decoration-none">
                                    <div class="card h-100 relacionado-card bg-white p-3">
                                        <div class="card-body">
                                            <h6 class="fw-bold text-dark mb-2"><?php echo substr($rel['titulo'], 0, 45); ?>...</h6>
                                            <div class="d-flex justify-content-between align-items-center mt-3">
                                                <span class="text-primary fw-bold">S/ <?php echo number_format($rel['precio'], 2); ?></span>
                                                <span class="badge bg-light text-muted border px-2">Ver</span>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="py-4 bg-white border-top text-center mt-5">
        <p class="text-muted small mb-0">&copy; 2026 Edujoam | Calidad en recursos pedagógicos.</p>
    </footer>

    <script>
        const mp = new MercadoPago('APP_USR-0ee24c5a-16e6-407b-99c9-6cd51cc5c486', {
            locale: 'es-PE'
        });

        <?php if ($preference_id && isset($_SESSION['user_id'])): ?>
        mp.bricks().create("wallet", "wallet_container", {
            initialization: {
                preferenceId: '<?php echo $preference_id; ?>',
            },
            customization: {
                texts: { valueProp: 'smart_option' },
            },
        });
        <?php endif; ?>
    </script>
</body>
</html>