<?php
// FILE: /digitalpremium/pages/plataformas.php (CON CORRECCIÓN DE COLOR EN LABELS)

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['id_usuario'])) {
    header("Location: /digitalpremium/login.php");
    exit();
}

require_once '../config/db.php';
$page_title = "Gestión de Plataformas - DigitalPremium";

include_once '../includes/header.php';

function getPlatformVisuals($name) {
    $name_lower = strtolower($name);
    $visuals = ['icon' => 'fas fa-tv', 'color' => '#6c757d'];
    $platforms = [
        'disney'    => ['icon' => 'fas fa-wand-magic-sparkles', 'color' => '#011e59'],
        'netflix'   => ['icon' => 'fab fa-netflix', 'color' => '#E50914'],
        'prime'     => ['icon' => 'fab fa-amazon', 'color' => '#00A8E1'],
        'hbo'       => ['icon' => 'fas fa-crown', 'color' => '#9b59b6'],
        'max'       => ['icon' => 'fas fa-crown', 'color' => '#9b59b6'],
        'spotify'   => ['icon' => 'fab fa-spotify', 'color' => '#1DB954'],
        'youtube'   => ['icon' => 'fab fa-youtube', 'color' => '#FF0000'],
        'apple'     => ['icon' => 'fab fa-apple', 'color' => '#A2AAAD'],
        'hulu'      => ['icon' => 'fas fa-film', 'color' => '#1CE783'],
        'star+'     => ['icon' => 'fas fa-star', 'color' => '#a10a6d'],
    ];
    foreach ($platforms as $key => $value) {
        if (strpos($name_lower, $key) !== false) return $value;
    }
    return $visuals;
}

$sql_plataformas = "
    SELECT 
        p.id_plataforma, p.nombre_plataforma, p.max_perfiles_cuenta, p.descripcion, p.estado,
        COALESCE(cuenta_stats.num_cuentas, 0) AS num_cuentas_maestras,
        COALESCE(perfil_stats.num_perfiles, 0) AS num_perfiles_vendidos
    FROM plataformas p
    LEFT JOIN (
        SELECT 
            id_plataforma,
            COUNT(*) as num_cuentas
        FROM cuentas_maestras 
        GROUP BY id_plataforma
    ) cuenta_stats ON p.id_plataforma = cuenta_stats.id_plataforma
    LEFT JOIN (
        SELECT 
            cm.id_plataforma,
            COUNT(pv.id_perfil_vendido) as num_perfiles
        FROM cuentas_maestras cm
        INNER JOIN perfiles_vendidos pv ON cm.id_cuenta_maestra = pv.id_cuenta_maestra
        GROUP BY cm.id_plataforma
    ) perfil_stats ON p.id_plataforma = perfil_stats.id_plataforma
    ORDER BY p.nombre_plataforma ASC
";
$stmt_plataformas = $pdo->prepare($sql_plataformas);
$stmt_plataformas->execute();
$plataformas = $stmt_plataformas->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    :root {
        --primary-color: #6a6ee0;
        --background-color: #f4f6f9;
        --card-bg-color: #ffffff;
        --border-color: #e9ecef;
        --hover-bg-color: #f8f9fa;
        --text-muted: #6c757d;
        --text-dark: #495057;
    }
    body { background-color: var(--background-color); }
    .page-title { color: #343a40; }
    .platform-list-container {
        background: var(--card-bg-color);
        border-radius: 12px;
        padding: 1rem;
        box-shadow: 0 4px 25px rgba(0,0,0,0.07);
        border: 1px solid var(--border-color);
    }
    .platform-list-header {
        display: flex; padding: 0.75rem 1.5rem; color: var(--text-muted); font-size: 0.8rem;
        font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid var(--border-color);
    }
    .platform-row {
        display: flex; align-items: center; padding: 1rem 1.5rem;
        border-bottom: 1px solid var(--border-color);
        transition: background-color 0.2s ease, transform 0.2s ease;
    }
    .platform-row:last-child { border-bottom: none; }
    .platform-row:hover { background-color: var(--hover-bg-color); transform: translateY(-2px); }
    .platform-cell { display: flex; align-items: center; }
    .platform-cell.col-name { flex: 4; min-width: 200px; }
    .platform-cell.col-stats { flex: 2; justify-content: center; gap: 1.5rem; }
    .platform-cell.col-status { flex: 1; justify-content: center; }
    .platform-cell.col-actions { flex: 1; justify-content: flex-end; gap: 0.5rem; }
    .platform-icon { font-size: 1.6rem; margin-right: 1.2rem; width: 30px; text-align: center; }
    .platform-name-text { font-weight: 500; color: #343a40; font-size: 1rem; }
    .stat-item { text-align: center; }
    .stat-number { font-size: 1.25rem; font-weight: 600; color: #212529; }
    .stat-label { font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; }
    .action-btn {
        width: 38px; height: 38px; border-radius: 50%; border: 1px solid var(--border-color);
        background-color: #fff; transition: all 0.2s ease; color: #6c757d;
    }
    .action-btn:hover {
        transform: scale(1.1); border-color: var(--primary-color);
        color: var(--primary-color); box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    
    /* MEJORAS A LOS MODALES */
    .modal-header { border-bottom: none; padding: 1.5rem 1.5rem 0.5rem; }
    .modal-header .modal-title { font-weight: 600; }
    .modal-header .btn-close { position: absolute; top: 1.5rem; right: 1.5rem; }
    .modal-body { padding: 1rem 1.5rem 1.5rem; }
    .modal-footer { border-top: 1px solid var(--border-color); }
    .modal-content { border-radius: 0.75rem; border: none; box-shadow: 0 8px 30px rgba(0,0,0,0.15); }
    .modal-header-icon {
        width: 48px; height: 48px; border-radius: 50%; display: flex;
        align-items: center; justify-content: center; margin-right: 1rem;
        color: #fff; font-size: 1.2rem;
    }

    /* ================================================================ */
    /* ======>     AQUÍ ESTÁ LA CORRECCIÓN PARA LOS TÍTULOS     <====== */
    /* ================================================================ */
    .modal-body .form-label {
        color: var(--text-dark); 
    }
    
    @media (max-width: 992px) {
        .platform-list-header { display: none; }
        .platform-row {
            flex-direction: column; align-items: flex-start; padding: 1rem; margin-bottom: 1rem;
            border: 1px solid var(--border-color); border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        .platform-row:hover { transform: none; }
        .platform-cell { width: 100%; padding: 0.5rem 0; border-bottom: 1px dashed var(--border-color); }
        .platform-cell:last-child { border-bottom: none; }
        .platform-cell::before {
            content: attr(data-label); font-weight: 600;
            width: 120px; min-width: 120px; color: var(--text-muted);
        }
        .platform-cell.col-name { min-width: 0; }
        .platform-cell.col-name::before { display: none; }
        .platform-cell.col-stats, .platform-cell.col-status, .platform-cell.col-actions { justify-content: flex-start; }
        .platform-cell.col-actions { padding-top: 1rem; }
    }
</style>

<div class="container-fluid px-lg-4">
    <header class="d-flex justify-content-between align-items-center my-4">
        <h1 class="h2 page-title fw-bold"><i class="fas fa-layer-group me-2" style="color: var(--primary-color);"></i>Gestión de Plataformas</h1>
        <button type="button" class="btn btn-primary rounded-pill shadow-sm" data-bs-toggle="modal" data-bs-target="#modalAgregarPlataforma">
            <i class="fas fa-plus me-2"></i> Agregar Plataforma
        </button>
    </header>

    <?php if (isset($_GET['mensaje'])): ?>
    <div class="alert alert-<?php echo htmlspecialchars($_GET['tipo'] ?? 'info'); ?> alert-dismissible fade show shadow-sm" role="alert">
        <?php echo htmlspecialchars(urldecode($_GET['mensaje'])); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <div class="mb-4">
        <div class="input-group">
            <span class="input-group-text bg-white border-end-0"><i class="fas fa-search"></i></span>
            <input type="text" id="quickSearchInput" class="form-control form-control-lg border-start-0" placeholder="Buscar por nombre de plataforma...">
        </div>
    </div>
    
    <div class="platform-list-container">
        <div class="platform-list-header d-none d-lg-flex">
            <div class="platform-cell col-name">Plataforma</div>
            <div class="platform-cell col-stats">Estadísticas</div>
            <div class="platform-cell col-status">Estado</div>
            <div class="platform-cell col-actions text-end">Acciones</div>
        </div>

        <div id="platforms-container">
            <?php if (count($plataformas) > 0): ?>
                <?php foreach ($plataformas as $plataforma): ?>
                    <?php
                        $visuals = getPlatformVisuals($plataforma['nombre_plataforma']);
                        $status_badge = $plataforma['estado'] == 1 
                            ? '<span class="badge bg-success-subtle text-success-emphasis rounded-pill">Activo</span>' 
                            : '<span class="badge bg-danger-subtle text-danger-emphasis rounded-pill">Inactivo</span>';
                    ?>
                    <div class="platform-row" data-search-text="<?php echo strtolower(htmlspecialchars($plataforma['nombre_plataforma'])); ?>">
                        <div class="platform-cell col-name">
                            <i class="<?php echo $visuals['icon']; ?> platform-icon" style="color: <?php echo $visuals['color']; ?>;"></i>
                            <span class="platform-name-text text-truncate" data-bs-toggle="tooltip" title="<?php echo htmlspecialchars($plataforma['nombre_plataforma']); ?>">
                                <?php echo htmlspecialchars($plataforma['nombre_plataforma']); ?>
                            </span>
                        </div>
                        <div class="platform-cell col-stats" data-label="Estadísticas">
                            <div class="stat-item">
                                <div class="stat-number"><?php echo $plataforma['num_cuentas_maestras']; ?></div>
                                <div class="stat-label">Cuentas</div>
                            </div>
                                                         <div class="stat-item">
                                 <div class="stat-number"><?php echo $plataforma['num_perfiles_vendidos']; ?></div>
                                 <div class="stat-label">Perfiles</div>
                             </div>
                        </div>
                        <div class="platform-cell col-status" data-label="Estado"><?php echo $status_badge; ?></div>
                        <div class="platform-cell col-actions" data-label="Acciones">
                            <button class="btn action-btn" title="Editar" 
                                    data-id="<?php echo $plataforma['id_plataforma']; ?>"
                                    data-nombre="<?php echo htmlspecialchars($plataforma['nombre_plataforma']); ?>"
                                    data-max_perfiles="<?php echo htmlspecialchars($plataforma['max_perfiles_cuenta']); ?>"
                                    data-descripcion="<?php echo htmlspecialchars($plataforma['descripcion'] ?? ''); ?>"
                                    data-estado="<?php echo $plataforma['estado']; ?>"
                                    data-bs-toggle="modal" data-bs-target="#modalEditarPlataforma">
                                <i class="fas fa-pencil-alt"></i>
                            </button>
                             <button class="btn action-btn" title="Eliminar"
                                    data-id="<?php echo $plataforma['id_plataforma']; ?>"
                                    data-nombre="<?php echo htmlspecialchars($plataforma['nombre_plataforma']); ?>"
                                    data-cuentas="<?php echo $plataforma['num_cuentas_maestras']; ?>"
                                    data-perfiles="<?php echo $plataforma['num_perfiles_vendidos']; ?>"
                                    data-bs-toggle="modal" data-bs-target="#modalEliminarPlataforma">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="text-center p-5 text-muted">Aún no has agregado ninguna plataforma. ¡Empieza ahora!</div>
            <?php endif; ?>
            <div id="no-results-message" class="text-center p-5 text-muted" style="display: none;">No se encontraron plataformas que coincidan con tu búsqueda.</div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalAgregarPlataforma" tabindex="-1" aria-labelledby="modalAgregarPlataformaLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form action="/digitalpremium/actions/plataformas_controlador.php" method="POST">
                <div class="modal-header">
                    <div class="d-flex align-items-center">
                        <div class="modal-header-icon bg-primary"><i class="fas fa-plus"></i></div>
                        <h5 class="modal-title" id="modalAgregarPlataformaLabel">Nueva Plataforma</h5>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="accion" value="agregar_plataforma">
                    <div class="mb-3">
                        <label for="nombre_plataforma_add" class="form-label">Nombre de la Plataforma</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-tag fa-fw"></i></span>
                            <input type="text" class="form-control" id="nombre_plataforma_add" name="nombre_plataforma" placeholder="Ej: Netflix, Disney+" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="max_perfiles_cuenta_add" class="form-label">Máximo de Perfiles por Cuenta</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-users fa-fw"></i></span>
                            <input type="number" class="form-control" id="max_perfiles_cuenta_add" name="max_perfiles_cuenta" min="1" value="1" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="descripcion_add" class="form-label">Descripción (Opcional)</label>
                        <textarea class="form-control" id="descripcion_add" name="descripcion" rows="3" placeholder="Añade detalles importantes..."></textarea>
                    </div>
                    <div class="form-check form-switch fs-5">
                        <input class="form-check-input" type="checkbox" role="switch" id="estado_add" name="estado" value="1" checked>
                        <label class="form-check-label" for="estado_add">Plataforma Activa</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>Guardar Plataforma</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditarPlataforma" tabindex="-1" aria-labelledby="modalEditarPlataformaLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form action="/digitalpremium/actions/plataformas_controlador.php" method="POST">
                <div class="modal-header">
                     <div class="d-flex align-items-center">
                        <div class="modal-header-icon bg-warning text-dark"><i class="fas fa-pencil-alt"></i></div>
                        <h5 class="modal-title" id="modalEditarPlataformaLabel">Editar Plataforma</h5>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="accion" value="editar_plataforma">
                    <input type="hidden" id="id_plataforma_edit" name="id_plataforma">
                    <div class="mb-3">
                        <label for="nombre_plataforma_edit" class="form-label">Nombre de la Plataforma</label>
                         <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-tag fa-fw"></i></span>
                            <input type="text" class="form-control" id="nombre_plataforma_edit" name="nombre_plataforma" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="max_perfiles_cuenta_edit" class="form-label">Máximo de Perfiles por Cuenta</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-users fa-fw"></i></span>
                            <input type="number" class="form-control" id="max_perfiles_cuenta_edit" name="max_perfiles_cuenta" min="1" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="descripcion_edit" class="form-label">Descripción (Opcional)</label>
                        <textarea class="form-control" id="descripcion_edit" name="descripcion" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="estado_edit" class="form-label">Estado</label>
                        <select class="form-select" id="estado_edit" name="estado" required>
                            <option value="1">Activo</option>
                            <option value="0">Inactivo</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-warning text-dark"><i class="fas fa-save me-2"></i>Guardar Cambios</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEliminarPlataforma" tabindex="-1" aria-labelledby="modalEliminarPlataformaLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form action="/digitalpremium/actions/plataformas_controlador.php" method="POST">
                <div class="modal-header bg-danger text-white">
                    <div class="d-flex align-items-center">
                        <div class="modal-header-icon bg-white text-danger"><i class="fas fa-exclamation-triangle"></i></div>
                        <h5 class="modal-title" id="modalEliminarPlataformaLabel">Confirmar Eliminación</h5>
                    </div>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center fs-5">
                    <input type="hidden" name="accion" value="eliminar_plataforma">
                    <input type="hidden" id="id_plataforma_delete" name="id_plataforma">
                    <p class="mt-3">¿Estás seguro de que deseas eliminar la plataforma <br><strong id="nombre_plataforma_delete" class="text-danger"></strong>?</p>
                    
                    <!-- Información de impacto -->
                    <div class="alert alert-warning border-0 rounded-3 mt-3">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-exclamation-triangle fa-2x text-warning me-3"></i>
                            <div class="text-start">
                                <h6 class="mb-2 fw-bold text-dark">⚠️ Impacto de la Eliminación</h6>
                                <p class="mb-1 small text-dark">
                                    <strong>Esta acción eliminará:</strong>
                                </p>
                                <ul class="mb-0 small text-dark text-start">
                                    <li>La plataforma seleccionada</li>
                                    <li><span id="count_cuentas_delete" class="fw-bold text-danger">0</span> cuentas maestras asociadas</li>
                                    <li><span id="count_perfiles_delete" class="fw-bold text-danger">0</span> perfiles vendidos asociados</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-danger border-0 rounded-3 mt-3">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-radiation fa-2x text-danger me-3"></i>
                            <div class="text-start">
                                <h6 class="mb-1 fw-bold text-danger">🚨 Acción Destructiva</h6>
                                <p class="mb-0 small text-danger">
                                    <strong>Esta acción es irreversible y no se puede deshacer.</strong><br>
                                    Todos los datos asociados se perderán permanentemente.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>No, cancelar
                    </button>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash-alt me-2"></i>Sí, eliminar todo
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include_once '../includes/footer.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl); });

    const searchInput = document.getElementById('quickSearchInput');
    const allPlatformRows = document.querySelectorAll('.platform-row');
    const noResultsMessage = document.getElementById('no-results-message');
    
    if (searchInput) {
        searchInput.addEventListener('keyup', function() {
            const searchTerm = this.value.toLowerCase().trim();
            let visibleCount = 0;
            allPlatformRows.forEach(row => {
                const searchableText = row.getAttribute('data-search-text') || '';
                const isVisible = searchableText.includes(searchTerm);
                if (isVisible) {
                    row.style.display = window.innerWidth <= 992 ? 'block' : 'flex';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });
            if (noResultsMessage) {
                noResultsMessage.style.display = (visibleCount === 0 && allPlatformRows.length > 0) ? 'block' : 'none';
            }
        });
    }

    const modalEditar = document.getElementById('modalEditarPlataforma');
    if (modalEditar) {
        modalEditar.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            document.getElementById('id_plataforma_edit').value = button.getAttribute('data-id');
            document.getElementById('nombre_plataforma_edit').value = button.getAttribute('data-nombre');
            document.getElementById('max_perfiles_cuenta_edit').value = button.getAttribute('data-max_perfiles');
            document.getElementById('descripcion_edit').value = button.getAttribute('data-descripcion');
            document.getElementById('estado_edit').value = button.getAttribute('data-estado');
        });
    }

    const modalEliminar = document.getElementById('modalEliminarPlataforma');
    if (modalEliminar) {
        modalEliminar.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const platformId = button.getAttribute('data-id');
            const platformName = button.getAttribute('data-nombre');
            const countCuentas = button.getAttribute('data-cuentas') || '0';
            const countPerfiles = button.getAttribute('data-perfiles') || '0';
            
            document.getElementById('id_plataforma_delete').value = platformId;
            document.getElementById('nombre_plataforma_delete').textContent = platformName;
            document.getElementById('count_cuentas_delete').textContent = countCuentas;
            document.getElementById('count_perfiles_delete').textContent = countPerfiles;
        });
    }
});
</script>