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

/**
 * 1. SEGURIDAD DE ACCESO
 */
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

/**
 * 2. CONSULTA DE MATERIALES APROBADOS
 * Traemos 'descargas_realizadas' de la tabla ventas.
 */
$stmt_aprobados = $conexion->prepare("
    SELECT 
        v.fecha_venta, 
        v.referencia_pago, 
        v.descargas_realizadas, 
        m.id as material_id, 
        m.titulo, 
        m.nivel, 
        m.area, 
        m.archivo_url 
    FROM ventas v 
    INNER JOIN materiales m ON v.material_id = m.id 
    WHERE v.usuario_id = ? 
    ORDER BY v.fecha_venta DESC
");
$stmt_aprobados->bind_param("i", $user_id);
$stmt_aprobados->execute();
$res_aprobados = $stmt_aprobados->get_result();

/**
 * 3. CONSULTA DE PAGOS PENDIENTES
 */
$stmt_pendientes = $conexion->prepare("
    SELECT p.id, m.titulo, p.monto, p.estado 
    FROM pagos_pendientes p 
    INNER JOIN materiales m ON p.material_id = m.id 
    WHERE p.usuario_id = ? AND p.estado = 'pendiente'
    ORDER BY p.id DESC
");
$stmt_pendientes->bind_param("i", $user_id);
$stmt_pendientes->execute();
$res_pendientes = $stmt_pendientes->get_result();
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mis Compras — Edujoam</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        :root {
            --oxford-blue: #0f172a;
            --brand-blue: #2563eb;
            --bg-body: #f8fafc;
            --accent-purple: #7c3aed;
        }
        body { 
            background-color: var(--bg-body); 
            font-family: 'Outfit', sans-serif; 
            color: var(--oxford-blue);
        }
        .hero-mini { 
            background: linear-gradient(135deg, #0f172a 0%, #1e3a8a 100%); 
            padding: 60px 0 80px; 
            color: white; 
            text-align: center; 
        }
        .alert-review { 
            background: white; 
            border-radius: 20px; 
            border-left: 6px solid #f59e0b; 
            box-shadow: 0 15px 30px -5px rgba(0,0,0,0.05); 
        }
        .card-download { 
            background: white; 
            border-radius: 24px; 
            border: 1px solid #edf2f7; 
            padding: 24px; 
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); 
            height: 100%; 
            display: flex; 
            flex-direction: column;
            position: relative;
        }
        .card-download:hover { 
            transform: translateY(-10px); 
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.1);
            border-color: var(--brand-blue);
        }
        
        /* Contador de Descargas */
        .download-info {
            background: #f1f5f9;
            border-radius: 12px;
            padding: 12px;
            margin-top: 15px;
        }
        .progress-container {
            height: 6px;
            background: #e2e8f0;
            border-radius: 10px;
            margin-top: 8px;
            overflow: hidden;
        }
        .progress-bar-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--brand-blue), var(--accent-purple));
            border-radius: 10px;
            transition: width 1s ease-in-out;
        }

        .btn-download { 
            background: var(--brand-blue); 
            color: white; 
            border-radius: 14px; 
            padding: 14px; 
            font-weight: 700; 
            text-decoration: none; 
            text-align: center; 
            margin-top: 20px; 
            border: none;
            transition: 0.3s;
        }
        .btn-download:hover { 
            background: var(--oxford-blue); 
            color: white; 
            box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.3);
        }
        .wa-float { 
            position: fixed; bottom: 30px; right: 30px; background: #22c55e; color: white; 
            width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; 
            justify-content: center; font-size: 30px; z-index: 1000; box-shadow: 0 10px 25px rgba(34,197,94,0.4);
            text-decoration: none; transition: 0.3s;
        }
        .wa-float:hover { transform: scale(1.1); color: white; }
    </style>
</head>
<body>

<?php if(file_exists('navbar.php')) include 'navbar.php'; ?>

<header class="hero-mini">
    <div class="container">
        <h1 class="fw-bold">Mis Compras Realizadas</h1>
        <p class="opacity-75">Bienvenido/a, <?= htmlspecialchars($_SESSION['nombre'] ?? 'Docente'); ?>. Gestiona tus materiales aquí.</p>
    </div>
</header>

<div class="container" style="margin-top: -40px;">
    
    <?php if($res_pendientes->num_rows > 0): ?>
        <div class="row justify-content-center mb-5">
            <div class="col-lg-10">
                <div class="alert-review p-4">
                    <div class="d-flex align-items-center mb-3">
                        <div class="bg-warning bg-opacity-10 p-2 rounded-3 me-3">
                            <i class="fas fa-clock text-warning fs-4"></i>
                        </div>
                        <h5 class="mb-0 fw-bold">Estamos verificando tus pagos</h5>
                    </div>
                    <div class="list-group list-group-flush">
                        <?php while($p = $res_pendientes->fetch_assoc()): ?>
                            <div class="list-group-item bg-transparent border-0 d-flex justify-content-between align-items-center px-0">
                                <span class="text-muted small"><i class="fas fa-file-invoice-dollar me-2"></i> <?= htmlspecialchars($p['titulo']); ?></span>
                                <span class="badge bg-warning text-dark px-3 py-2 rounded-pill" style="font-size: 0.65rem;">EN REVISIÓN</span>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <div class="row g-4 mb-5">
        <?php if($res_aprobados->num_rows > 0): ?>
            <div class="col-12"><h4 class="fw-bold mb-3"><i class="fas fa-check-circle text-success me-2"></i>Descargas Disponibles</h4></div>
            <?php while($v = $res_aprobados->fetch_assoc()): 
                $ext = pathinfo($v['archivo_url'] ?? '', PATHINFO_EXTENSION);
                $clicks = $v['descargas_realizadas'] ?? 0;
                // Calculamos el progreso (ejemplo: cada descarga llena un 10%, máximo 100%)
                $progreso = min($clicks * 10, 100);
            ?>
                <div class="col-md-6 col-lg-4">
                    <div class="card-download">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <span class="badge bg-light text-primary border px-2 py-1 small"><?= htmlspecialchars($v['nivel']); ?></span>
                            <small class="text-muted fw-bold"><?= date('d/m/Y', strtotime($v['fecha_venta'])); ?></small>
                        </div>
                        
                        <h5 class="fw-bold mb-1 text-dark"><?= htmlspecialchars($v['titulo']); ?></h5>
                        <p class="text-muted small mb-3">Área: <?= htmlspecialchars($v['area']); ?></p>

                        <div class="download-info">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <span class="small fw-bold text-muted">Uso del material:</span>
                                <span class="small fw-bold text-primary"><?= $clicks ?> descargas</span>
                            </div>
                            <div class="progress-container">
                                <div class="progress-bar-fill" style="width: <?= $progreso ?>%;"></div>
                            </div>
                        </div>

                        <a href="descargar.php?id=<?= $v['material_id']; ?>" class="btn-download">
                            <i class="fas fa-cloud-download-alt me-2"></i> DESCARGAR <?= strtoupper($ext) ?>
                        </a>
                        
                        <div class="text-center mt-3">
                            <small class="text-muted" style="font-size: 0.7rem;">Ref: #<?= htmlspecialchars($v['referencia_pago']); ?></small>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php elseif($res_pendientes->num_rows == 0): ?>
            <div class="col-12 text-center py-5 bg-white rounded-5 shadow-sm">
                <i class="fas fa-shopping-basket fa-4x opacity-25 mb-3 text-primary"></i>
                <h3 class="fw-bold">No tienes materiales aún</h3>
                <p class="text-muted px-3">Explora nuestra tienda y potencia tus sesiones de clase.</p>
                <a href="index.php" class="btn btn-primary rounded-pill px-5 py-2 fw-bold mt-2">IR A LA TIENDA</a>
            </div>
        <?php endif; ?>
    </div>
</div>

<a href="https://wa.me/51944748520?text=Hola%20Edujoam,%20quisiera%20agilizar%20mi%20descarga." class="wa-float" target="_blank">
    <i class="fab fa-whatsapp"></i>
</a>

<footer class="text-center py-5 text-muted small">
    <p>© <?= date('Y'); ?> <b>EDUJOAM PERÚ</b> • Calidad Educativa</p>
</footer>

</body>
</html>