<?php
session_start();

// Verificar si el usuario ha iniciado sesión
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// Conexión centralizada
include 'db.php';

try {
    // $pdo ya está disponible desde db.php

    // Verificar si el usuario es un super revendedor
    $stmt = $pdo->prepare("SELECT super FROM resellers WHERE email = :user_email");
    $stmt->execute(['user_email' => $_SESSION['user_email']]);
    $userInfo = $stmt->fetch();
    $isSuper = isset($userInfo['super']) && $userInfo['super'] == 1;

    // Obtener el término de búsqueda si existe
    $searchTerm = isset($_POST['search']) ? trim($_POST['search']) : '';

    // Obtener todos los revendedores agregados por el usuario logueado
    $query = "SELECT * FROM resellers WHERE idv = :user_email";
    $params = ['user_email' => $_SESSION['user_email']];
    if (!empty($searchTerm)) {
        $query .= " AND (nombre LIKE :search_nombre OR email LIKE :search_email)";
        $params['search_nombre'] = '%' . $searchTerm . '%';
        $params['search_email'] = '%' . $searchTerm . '%';
    }
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $resellers = $stmt->fetchAll();
} catch (\PDOException $e) {
    echo "Error de base de datos: " . $e->getMessage();
    exit();
}

// Manejo de acciones POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'delete') {
        $id_to_delete = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM resellers WHERE id = :id");
        $stmt->execute(['id' => $id_to_delete]);
    } elseif ($_POST['action'] === 'pause' || $_POST['action'] === 'activate') {
        $id_to_change = $_POST['id'];
        $new_pause_value = $_POST['action'] === 'pause' ? 1 : 0;

        $stmt = $pdo->prepare("UPDATE resellers SET pause = :pause WHERE id = :id");
        $stmt->execute(['pause' => $new_pause_value, 'id' => $id_to_change]);
    } elseif ($_POST['action'] === 'promote' && $isSuper) {
        $id_to_promote = $_POST['id'];
        $stmt = $pdo->prepare("UPDATE resellers SET super = 1 WHERE id = :id");
        $stmt->execute(['id' => $id_to_promote]);
    }

    header("Location: " . $_SERVER['PHP_SELF'] . (!empty($searchTerm) ? "?search=" . urlencode($searchTerm) : ""));
    exit();
}

// Separar los revendedores en listas
$regularResellers = array_filter($resellers, function($reseller) {
    return $reseller['super'] == 0;
});
$superResellers = array_filter($resellers, function($reseller) {
    return $reseller['super'] == 1;
});
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Revendedores</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #16a085;
            --accent-color: #3498db;
            --danger-color: #e74c3c;
            --warning-color: #f39c12;
            --success-color: #27ae60;
            --light-bg: #f8f9fa;
            --dark-text: #2c3e50;
            --light-text: #ecf0f1;
            --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --hover-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
        }

        body {
            background-color: #f5f7fa;
            color: var(--dark-text);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .container {
            padding: 2rem 1rem;
        }

        .content-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: var(--card-shadow);
            padding: 2rem;
            margin-bottom: 2rem;
            transition: all 0.3s ease;
        }

        .content-container:hover {
            box-shadow: var(--hover-shadow);
        }

        .content-title {
            color: var(--primary-color);
            border-bottom: 2px solid var(--secondary-color);
            padding-bottom: 0.75rem;
            margin-bottom: 1.5rem;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .content-title i {
            margin-right: 0.5rem;
            color: var(--secondary-color);
        }

        .table {
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 0 0 1px rgba(0,0,0,0.05);
        }

        .table thead {
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            color: var(--light-text);
        }

        .table-success {
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color)) !important;
            color: white !important;
        }

        .table tbody tr {
            transition: background-color 0.2s ease;
        }

        .table tbody tr:hover {
            background-color: rgba(22, 160, 133, 0.05);
        }

        .btn {
            border-radius: 6px;
            transition: all 0.2s ease;
            margin: 0.15rem;
            font-weight: 500;
        }

        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }

        .btn-success {
            background-color: var(--success-color);
            border-color: var(--success-color);
        }

        .btn-warning {
            background-color: var(--warning-color);
            border-color: var(--warning-color);
            color: white;
        }

        .btn-info {
            background-color: var(--accent-color);
            border-color: var(--accent-color);
            color: white;
        }

        .btn-danger {
            background-color: var(--danger-color);
            border-color: var(--danger-color);
        }

        .btn-primary {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }

        .btn-outline-secondary {
            color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-outline-secondary:hover {
            background-color: var(--primary-color);
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .modal-content {
            border-radius: 10px;
            overflow: hidden;
        }

        .modal-header {
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            color: white;
            border-bottom: none;
        }

        .modal-title {
            font-weight: 600;
        }

        .btn-close {
            background-color: rgba(255,255,255,0.5);
        }

        .modal-footer {
            border-top: none;
            padding: 0.5rem 1rem 0.5rem 1rem;
            margin-bottom: 0;
        }

        .text-success {
            color: var(--success-color) !important;
            font-weight: 500;
        }

        .text-danger {
            color: var(--danger-color) !important;
            font-weight: 500;
        }

        .toggle-password {
            cursor: pointer;
            padding: 0.2rem 0.5rem;
            font-size: 0.75rem;
        }

        .badge {
            font-weight: 500;
            padding: 0.5em 0.75em;
            border-radius: 4px;
        }

        .badge-success {
            background-color: rgba(39, 174, 96, 0.15);
            color: var(--success-color);
        }

        .badge-danger {
            background-color: rgba(231, 76, 60, 0.15);
            color: var(--danger-color);
        }

        .status-indicator {
            display: inline-flex;
            align-items: center;
        }

        .status-indicator i {
            margin-right: 0.25rem;
        }

        .action-buttons {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
        }

        .search-form {
            margin-bottom: 1.5rem;
            display: flex;
            gap: 0.5rem;
            align-items: center;
        }

        .search-form input {
            max-width: 300px;
        }

        @media (max-width: 767.98px) {
            .table-responsive {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            .action-buttons {
                flex-direction: column;
                align-items: flex-start;
            }

            .action-buttons .btn {
                margin-bottom: 0.25rem;
            }

            .search-form {
                flex-direction: column;
                align-items: flex-start;
            }

            .search-form input {
                max-width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="content-container">
            <h2 class="content-title"><i class="fas fa-crown"></i> Lista de SUPER RESELLERS</h2>
            <form method="post" class="search-form">
                <input type="text" name="search" class="form-control" placeholder="Buscar por nombre o email..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Buscar</button>
                <?php if (!empty($searchTerm)): ?>
                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="btn btn-secondary"><i class="fas fa-times"></i> Limpiar</a>
                <?php endif; ?>
            </form>
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-success">
                        <tr>
                            <th><i class="fas fa-user"></i> Nombre</th>
                            <th><i class="fas fa-envelope"></i> Email</th>
                            <th><i class="fas fa-phone"></i> Teléfono</th>
                            <th><i class="fas fa-coins"></i> Créditos</th>
                            <th><i class="fas fa-lock"></i> Contraseña</th>
                            <th><i class="fas fa-toggle-on"></i> Estado</th>
                            <th><i class="fas fa-cogs"></i> Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($superResellers)): ?>
                            <tr><td colspan="7" class="text-center">No se encontraron Super Resellers.</td></tr>
                        <?php else: ?>
                            <?php foreach ($superResellers as $reseller): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($reseller['nombre']); ?></td>
                                <td><?php echo htmlspecialchars($reseller['email']); ?></td>
                                <td><?php echo htmlspecialchars($reseller['telefono']); ?></td>
                                <td><span class="badge bg-secondary"><?php echo htmlspecialchars($reseller['creditos']); ?></span></td>
                                <td>
                                    <span class="password-mask"><?php echo str_repeat('•', strlen($reseller['password'])); ?></span>
                                    <span class="password-hidden" style="display:none;"><?php echo htmlspecialchars($reseller['password']); ?></span>
                                    <button class="btn btn-sm btn-outline-secondary toggle-password"><i class="fas fa-eye"></i></button>
                                </td>
                                <td>
                                    <?php if ($reseller['pause'] == 1): ?>
                                        <span class="status-indicator text-danger"><i class="fas fa-pause-circle"></i> Pausado</span>
                                    <?php else: ?>
                                        <span class="status-indicator text-success"><i class="fas fa-check-circle"></i> Activo</span>
                                    <?php endif; ?>
                                </td>
                                <td class="action-buttons">
                                    <a href="editar_reseller.php?id=<?php echo $reseller['id']; ?>" class="btn btn-success btn-sm"><i class="fas fa-edit"></i> Editar</a>
                                    <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#pauseModal" data-id="<?php echo $reseller['id']; ?>" data-action="pause"><i class="fas fa-pause"></i> Pausar</button>
                                    <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#activateModal" data-id="<?php echo $reseller['id']; ?>" data-action="activate"><i class="fas fa-play"></i> Activar</button>
                                    <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal" data-id="<?php echo $reseller['id']; ?>"><i class="fas fa-trash"></i> Eliminar</button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <h2 class="content-title mt-5"><i class="fas fa-users"></i> Lista de RESELLERS</h2>
            <form method="post" class="search-form">
                <input type="text" name="search" class="form-control" placeholder="Buscar por nombre o email..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Buscar</button>
                <?php if (!empty($searchTerm)): ?>
                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="btn btn-secondary"><i class="fas fa-times"></i> Limpiar</a>
                <?php endif; ?>
            </form>
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-success">
                        <tr>
                            <th><i class="fas fa-user"></i> Nombre</th>
                            <th><i class="fas fa-envelope"></i> Email</th>
                            <th><i class="fas fa-phone"></i> Teléfono</th>
                            <th><i class="fas fa-coins"></i> Créditos</th>
                            <th><i class="fas fa-lock"></i> Contraseña</th>
                            <th><i class="fas fa-toggle-on"></i> Estado</th>
                            <th><i class="fas fa-cogs"></i> Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($regularResellers)): ?>
                            <tr><td colspan="7" class="text-center">No se encontraron Resellers.</td></tr>
                        <?php else: ?>
                            <?php foreach ($regularResellers as $reseller): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($reseller['nombre']); ?></td>
                                <td><?php echo htmlspecialchars($reseller['email']); ?></td>
                                <td><?php echo htmlspecialchars($reseller['telefono']); ?></td>
                                <td><span class="badge bg-secondary"><?php echo htmlspecialchars($reseller['creditos']); ?></span></td>
                                <td>
                                    <span class="password-mask"><?php echo str_repeat('•', strlen($reseller['password'])); ?></span>
                                    <span class="password-hidden" style="display:none;"><?php echo htmlspecialchars($reseller['password']); ?></span>
                                    <button class="btn btn-sm btn-outline-secondary toggle-password"><i class="fas fa-eye"></i></button>
                                </td>
                                <td>
                                    <?php if ($reseller['pause'] == 1): ?>
                                        <span class="status-indicator text-danger"><i class="fas fa-pause-circle"></i> Pausado</span>
                                    <?php else: ?>
                                        <span class="status-indicator text-success"><i class="fas fa-check-circle"></i> Activo</span>
                                    <?php endif; ?>
                                </td>
                                <td class="action-buttons">
                                    <a href="editar_reseller.php?id=<?php echo $reseller['id']; ?>" class="btn btn-success btn-sm"><i class="fas fa-edit"></i> Editar</a>
                                    <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#pauseModal" data-id="<?php echo $reseller['id']; ?>" data-action="pause"><i class="fas fa-pause"></i> Pausar</button>
                                    <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#activateModal" data-id="<?php echo $reseller['id']; ?>" data-action="activate"><i class="fas fa-play"></i> Activar</button>
                                    <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal" data-id="<?php echo $reseller['id']; ?>"><i class="fas fa-trash"></i> Eliminar</button>
                                    <?php if ($isSuper): ?>
                                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#promoteModal" data-id="<?php echo $reseller['id']; ?>"><i class="fas fa-arrow-up"></i> Promover a Super</button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="mt-4 text-center">
                <a href="opciones.php" class="btn btn-outline-secondary btn-lg">
                    <i class="fas fa-arrow-left"></i> Volver al Panel de Control
                </a>
            </div>
        </div>
    </div>

    <!-- Modal para confirmar eliminación -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel"><i class="fas fa-trash-alt"></i> Eliminar Revendedor</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i> ¿Estás seguro de que deseas eliminar este revendedor? Esta acción no se puede deshacer.
                        </div>
                        <input type="hidden" name="id" id="resellerIdToDelete">
                        <input type="hidden" name="search" value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times"></i> Cancelar</button>
                        <button type="submit" class="btn btn-danger" name="action" value="delete"><i class="fas fa-trash"></i> Eliminar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal para confirmar pausa -->
    <div class="modal fade" id="pauseModal" tabindex="-1" aria-labelledby="pauseModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="pauseModalLabel"><i class="fas fa-pause-circle"></i> Pausar Revendedor</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="alert alert-warning">
                            <i class="fas fa-info-circle"></i> ¿Estás seguro de que deseas pausar este revendedor? El revendedor no podrá acceder al sistema mientras esté pausado.
                        </div>
                        <input type="hidden" name="id" id="resellerIdToPause">
                        <input type="hidden" name="action" value="pause">
                        <input type="hidden" name="search" value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times"></i> Cancelar</button>
                        <button type="submit" class="btn btn-warning"><i class="fas fa-pause"></i> Pausar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal para confirmar activación -->
    <div class="modal fade" id="activateModal" tabindex="-1" aria-labelledby="activateModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="activateModalLabel"><i class="fas fa-play-circle"></i> Activar Revendedor</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i> ¿Estás seguro de que deseas activar este revendedor? El revendedor podrá acceder normalmente al sistema.
                        </div>
                        <input type="hidden" name="id" id="resellerIdToActivate">
                        <input type="hidden" name="action" value="activate">
                        <input type="hidden" name="search" value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times"></i> Cancelar</button>
                        <button type="submit" class="btn btn-info"><i class="fas fa-play"></i> Activar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal para promover a Super Reseller -->
    <div class="modal fade" id="promoteModal" tabindex="-1" aria-labelledby="promoteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="promoteModalLabel"><i class="fas fa-crown"></i> Promover a Super Reseller</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="alert alert-primary">
                            <i class="fas fa-info-circle"></i> ¿Estás seguro de que deseas promover este revendedor a Super Reseller?
                        </div>
                        <div class="card bg-light p-3">
                            <h6><i class="fas fa-exclamation-triangle text-warning"></i> Importante</h6>
                            <p class="mb-0">Esta acción otorgará privilegios adicionales al revendedor, incluyendo la capacidad de crear y gestionar sus propios revendedores.</p>
                        </div>
                        <input type="hidden" name="id" id="resellerIdToPromote">
                        <input type="hidden" name="action" value="promote">
                        <input type="hidden" name="search" value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times"></i> Cancelar</button>
                        <button type="submit" class="btn btn-primary"><i class="fas fa-crown"></i> Promover</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const deleteModal = document.getElementById('deleteModal');
            deleteModal.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const id = button.getAttribute('data-id');
                const input = deleteModal.querySelector('#resellerIdToDelete');
                input.value = id;
            });

            const pauseModal = document.getElementById('pauseModal');
            pauseModal.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const id = button.getAttribute('data-id');
                const input = pauseModal.querySelector('#resellerIdToPause');
                input.value = id;
            });

            const activateModal = document.getElementById('activateModal');
            activateModal.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const id = button.getAttribute('data-id');
                const input = activateModal.querySelector('#resellerIdToActivate');
                input.value = id;
            });

            const promoteModal = document.getElementById('promoteModal');
            if (promoteModal) {
                promoteModal.addEventListener('show.bs.modal', function(event) {
                    const button = event.relatedTarget;
                    const id = button.getAttribute('data-id');
                    const input = promoteModal.querySelector('#resellerIdToPromote');
                    input.value = id;
                });
            }

            document.querySelectorAll('.toggle-password').forEach(button => {
                button.addEventListener('click', () => {
                    const td = button.closest('td');
                    const passwordMask = td.querySelector('.password-mask');
                    const passwordHidden = td.querySelector('.password-hidden');
                    const isHiddenVisible = window.getComputedStyle(passwordHidden).display !== 'none';
                    if (isHiddenVisible) {
                        passwordHidden.style.display = 'none';
                        passwordMask.style.display = 'inline';
                        button.innerHTML = '<i class="fas fa-eye"></i>';
                    } else {
                        passwordHidden.style.display = 'inline';
                        passwordMask.style.display = 'none';
                        button.innerHTML = '<i class="fas fa-eye-slash"></i>';
                    }
                });
            });
        });
    </script>
</body>
</html>