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

// 1. SEGURIDAD: Solo tú puedes ver esta página
if (!isset($_SESSION['email']) || $_SESSION['email'] !== 'educajoam33@gmail.com') {
    header("Location: login.php");
    exit();
}

// --- LÓGICA DE APROBACIÓN DE PAGO ---
if (isset($_GET['aprobar_pago'])) {
    $id_pago = filter_input(INPUT_GET, 'aprobar_pago', FILTER_SANITIZE_NUMBER_INT);
    
    $stmt = $conexion->prepare("SELECT * FROM pagos_pendientes WHERE id = ? AND estado = 'pendiente'");
    $stmt->bind_param("i", $id_pago);
    $stmt->execute();
    $pago = $stmt->get_result()->fetch_assoc();
    
    if ($pago) {
        $u_id = $pago['usuario_id'];
        $m_id = $pago['material_id'];
        $monto = $pago['monto'];
        $ref = "YAPE-" . strtoupper(bin2hex(random_bytes(4)));

        $conexion->begin_transaction();
        try {
            // Insertamos en ventas (con descargas_realizadas en 0 por defecto)
            $ins = $conexion->prepare("INSERT INTO ventas (usuario_id, material_id, monto, referencia_pago, fecha_venta, descargas_realizadas) VALUES (?, ?, ?, ?, NOW(), 0)");
            $ins->bind_param("iids", $u_id, $m_id, $monto, $ref);
            $ins->execute();

            $upd = $conexion->prepare("UPDATE pagos_pendientes SET estado = 'aprobado' WHERE id = ?");
            $upd->bind_param("i", $id_pago);
            $upd->execute();

            $conexion->commit();
            echo "<script>alert('¡Pago aprobado correctamente!'); window.location='admin.php';</script>";
        } catch (Exception $e) {
            $conexion->rollback();
            echo "Error: " . $e->getMessage();
        }
    }
}

// --- LÓGICA PARA ELIMINAR MATERIAL ---
if (isset($_GET['eliminar'])) {
    $id_eliminar = filter_input(INPUT_GET, 'eliminar', FILTER_SANITIZE_NUMBER_INT);
    
    $stmt = $conexion->prepare("SELECT archivo_url FROM materiales WHERE id = ?");
    $stmt->bind_param("i", $id_eliminar);
    $stmt->execute();
    $archivo = $stmt->get_result()->fetch_assoc();
    
    if ($archivo) {
        $nombre_fichero = basename($archivo['archivo_url']); 
        $ruta_fisica = __DIR__ . '/archivos_vendedores/' . $nombre_fichero;
        
        if (file_exists($ruta_fisica)) { 
            unlink($ruta_fisica); 
        }
        
        $del = $conexion->prepare("DELETE FROM materiales WHERE id = ?");
        $del->bind_param("i", $id_eliminar);
        $del->execute();
        
        echo "<script>alert('Material eliminado correctamente.'); window.location='admin.php';</script>";
    }
}

// --- ESTADÍSTICAS GENERALES ---
$res_total = mysqli_query($conexion, "SELECT SUM(monto) as total FROM ventas");
$total_ventas = mysqli_fetch_assoc($res_total)['total'] ?? 0;

$res_mes = mysqli_query($conexion, "SELECT SUM(monto) as total FROM ventas WHERE MONTH(fecha_venta) = MONTH(CURRENT_DATE()) AND YEAR(fecha_venta) = YEAR(CURRENT_DATE())");
$ventas_mes = mysqli_fetch_assoc($res_mes)['total'] ?? 0;

$res_mats = mysqli_query($conexion, "SELECT COUNT(*) as total FROM materiales");
$total_materiales = mysqli_fetch_assoc($res_mats)['total'] ?? 0;

// --- CONSULTA TOP 3 POPULARES ---
$query_top = "SELECT m.titulo, SUM(v.descargas_realizadas) as total 
              FROM ventas v 
              INNER JOIN materiales m ON v.material_id = m.id 
              GROUP BY v.material_id 
              ORDER BY total DESC 
              LIMIT 3";
$res_top = mysqli_query($conexion, $query_top);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panel de Administración - 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">
    <style>
        body { background-color: #f0f2f5; font-family: 'Outfit', sans-serif; }
        .card { border-radius: 15px; border: none; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        .stat-card { border-left: 5px solid #0d6efd; transition: 0.3s; }
        .stat-card:hover { transform: translateY(-5px); }
        .top-card { background: white; border-radius: 12px; border: 1px solid #eef2f7; transition: 0.3s; }
        .top-card:hover { border-color: #0d6efd; background: #f8fbff; }
        .img-comprobante { width: 50px; height: 50px; object-fit: cover; cursor: pointer; border-radius: 8px; }
        .btn-historial { background: #0f172a; color: white; border-radius: 10px; padding: 10px 20px; text-decoration: none; transition: 0.3s; }
    </style>
</head>
<body>

    <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4 shadow">
        <div class="container">
            <a class="navbar-brand fw-bold" href="admin.php"><i class="fas fa-user-shield me-2"></i>EDUJOAM ADMIN</a>
            <div class="ms-auto">
                <a href="historial_ventas.php" class="btn-historial me-3"><i class="fas fa-users me-2"></i>Historial y clientes</a>
                <a href="logout.php" class="btn btn-danger btn-sm rounded-pill px-3">Salir</a>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row g-3 mb-4">
            <div class="col-md-4">
                <div class="card p-4 stat-card">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted fw-bold d-block mb-1">RECAUDACIÓN TOTAL</small>
                            <h2 class="fw-bold text-primary mb-0">S/ <?= number_format($total_ventas, 2); ?></h2>
                        </div>
                        <i class="fas fa-wallet fa-2x opacity-25"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card p-4 stat-card" style="border-left-color: #198754;">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted fw-bold d-block mb-1">VENTAS DEL MES</small>
                            <h2 class="fw-bold text-success mb-0">S/ <?= number_format($ventas_mes, 2); ?></h2>
                        </div>
                        <i class="fas fa-chart-line fa-2x opacity-25"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card p-4 stat-card" style="border-left-color: #6f42c1;">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted fw-bold d-block mb-1">MATERIALES EN TIENDA</small>
                            <h2 class="fw-bold text-purple mb-0" style="color: #6f42c1;"><?= $total_materiales; ?></h2>
                        </div>
                        <i class="fas fa-box-open fa-2x opacity-25"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-5 border-0 shadow-sm">
            <div class="card-body p-4">
                <h5 class="fw-bold mb-4"><i class="fas fa-trophy text-warning me-2"></i> Materiales más Populares (Descargas)</h5>
                <div class="row">
                    <?php 
                    $colores = ['text-warning', 'text-secondary', 'text-danger'];
                    $i = 0;
                    while($top = mysqli_fetch_assoc($res_top)): 
                    ?>
                    <div class="col-md-4 mb-3">
                        <div class="top-card p-3">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-medal <?= $colores[$i] ?> fs-2 me-3"></i>
                                <div>
                                    <h6 class="mb-0 fw-bold text-truncate" style="max-width: 180px;"><?= $top['titulo'] ?></h6>
                                    <span class="badge bg-primary rounded-pill small"><?= $top['total'] ?> descargas</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php $i++; endwhile; ?>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-4 mb-4">
                <div class="card shadow-sm border-0">
                    <div class="card-header bg-primary text-white fw-bold py-3" style="border-radius: 15px 15px 0 0;">
                        <i class="fas fa-plus-circle me-2"></i>Nuevo Material
                    </div>
                    <div class="card-body p-4">
                        <form action="guardar_material.php" method="POST" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="small fw-bold mb-1">Título del Recurso</label>
                                <input type="text" name="titulo" class="form-control" required>
                            </div>
                            <div class="row">
                                <div class="col-6 mb-3">
                                    <label class="small fw-bold mb-1">Precio (S/)</label>
                                    <input type="number" name="precio" step="0.10" class="form-control" required>
                                </div>
                                <div class="col-6 mb-3">
                                    <label class="small fw-bold mb-1">Nivel</label>
                                    <select name="nivel" class="form-select">
                                        <option value="Inicial">Inicial</option>
                                        <option value="Primaria">Primaria</option>
                                        <option value="Secundaria">Secundaria</option>
                                    </select>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="small fw-bold mb-1">Archivo Digital</label>
                                <input type="file" name="archivo" class="form-control" required>
                            </div>
                            <button class="btn btn-primary w-100 fw-bold py-2 shadow-sm rounded-3">PUBLICA AHORA</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-8">
                <div class="card mb-4 border-0 shadow-sm overflow-hidden">
                    <div class="card-header bg-warning text-dark fw-bold py-3">
                        <i class="fas fa-bell me-2"></i>VOUCHERS POR VALIDAR
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light small text-muted">
                                <tr>
                                    <th class="ps-4">COMPROBANTE</th>
                                    <th>USUARIO</th>
                                    <th>MONTO</th>
                                    <th class="text-center">ACCIÓN</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $pendientes = mysqli_query($conexion, "SELECT p.*, u.nombre, m.titulo FROM pagos_pendientes p JOIN usuarios u ON p.usuario_id = u.id JOIN materiales m ON p.material_id = m.id WHERE p.estado = 'pendiente'");
                                while($p = mysqli_fetch_assoc($pendientes)): ?>
                                <tr>
                                    <td class="ps-4">
                                        <img src="comprobantes/<?= $p['comprobante_url']; ?>" class="img-comprobante" data-bs-toggle="modal" data-bs-target="#imgModal<?= $p['id']; ?>">
                                    </td>
                                    <td>
                                        <span class="fw-bold d-block small"><?= htmlspecialchars($p['nombre']); ?></span>
                                        <span class="text-muted" style="font-size: 0.75rem;"><?= htmlspecialchars($p['titulo']); ?></span>
                                    </td>
                                    <td class="fw-bold">S/ <?= number_format($p['monto'], 2); ?></td>
                                    <td class="text-center">
                                        <a href="admin.php?aprobar_pago=<?= $p['id']; ?>" class="btn btn-sm btn-success rounded-pill px-3 fw-bold" onclick="return confirm('¿Aprobar?')">Aprobar</a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="card border-0 shadow-sm overflow-hidden">
                    <div class="card-header bg-white fw-bold py-3">GESTIÓN DE CATÁLOGO</div>
                    <div class="table-responsive" style="max-height: 400px;">
                        <table class="table table-sm table-hover align-middle mb-0">
                            <thead class="bg-light small">
                                <tr>
                                    <th class="ps-4">Material</th>
                                    <th class="text-center">Descargas</th>
                                    <th class="text-end pe-4">Acción</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $mats = mysqli_query($conexion, "SELECT m.id, m.titulo, m.precio, (SELECT SUM(descargas_realizadas) FROM ventas WHERE material_id = m.id) as clics FROM materiales m ORDER BY id DESC");
                                while($m = mysqli_fetch_assoc($mats)): ?>
                                <tr>
                                    <td class="ps-4 py-3">
                                        <div class="fw-bold small"><?= htmlspecialchars($m['titulo']); ?></div>
                                        <div class="text-primary" style="font-size: 0.7rem;">S/ <?= number_format($m['precio'], 2); ?></div>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-light text-dark border"><?= $m['clics'] ?? 0 ?></span>
                                    </td>
                                    <td class="text-end pe-4">
                                        <a href="admin.php?eliminar=<?= $m['id']; ?>" class="text-danger" onclick="return confirm('¿Eliminar?')"><i class="fas fa-trash-alt"></i></a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>