<?php
require_once __DIR__ . '/includes/header.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* =======================
SEGURIDAD
======================= */
if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

$currentUser = $_SESSION['name'];
$role = $_SESSION['role'];

if (!in_array($role, ['master','super-reseller','reseller'])) {
    die("Acceso denegado");
}

/* =======================
REPARAR TABLA CODES
======================= */
$dbFile = __DIR__ . '/../api/.db.db';

if (file_exists($dbFile)) {
    $sqlite = new SQLite3($dbFile);

    function columnExists($sqlite,$table,$column){
        $result = $sqlite->query("PRAGMA table_info($table)");
        while($row = $result->fetchArray(SQLITE3_ASSOC)){
            if ($row['name'] == $column) return true;
        }
        return false;
    }

    if (!columnExists($sqlite,'codes','client_name')) {
        $sqlite->exec("ALTER TABLE codes ADD COLUMN client_name TEXT");
    }

    if (!columnExists($sqlite,'codes','client_whatsapp')) {
        $sqlite->exec("ALTER TABLE codes ADD COLUMN client_whatsapp TEXT");
    }

    if (!columnExists($sqlite,'codes','status')) {
        $sqlite->exec("ALTER TABLE codes ADD COLUMN status TEXT DEFAULT 'active'");
    }
}

/* =======================
ACCIONES: BLOQUEAR / DESBLOQUEAR / ELIMINAR
======================= */
// Función para generar carácter aleatorio
function randomChar() {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    return $chars[random_int(0, strlen($chars) - 1)];
}

/* =======================
BLOQUEAR
======================= */
if(isset($_GET['block'])){
    $id = (int)$_GET['block'];

    // Obtener código actual
    $row = $db->select('codes','code','id = :id','',[':id'=>$id]);
    if($row){
        $currentCode = $row[0]['code'];

        // Evitar agregar más de un carácter
        if(strlen($currentCode) == 6){
            $newCode = $currentCode . randomChar();

            // Verificar que no exista
            $exists = $db->select('codes','id','code = :c','',[':c'=>$newCode]);
            if(!$exists){
                $db->update('codes',[
                    'status'=>'blocked',
                    'code'=>$newCode
                ],'id = :id',[':id'=>$id]);
            }
        } else {
            // Solo cambiar estado si ya está modificado
            $db->update('codes',['status'=>'blocked'],'id = :id',[':id'=>$id]);
        }
    }

    header("Location: clients.php");
    exit;
}

/* =======================
DESBLOQUEAR
======================= */
if(isset($_GET['unblock'])){
    $id = (int)$_GET['unblock'];

    // Obtener código actual
    $row = $db->select('codes','code','id = :id','',[':id'=>$id]);
    if($row){
        $currentCode = $row[0]['code'];

        // Si tiene 7 caracteres → quitar el último
        if(strlen($currentCode) == 7){
            $originalCode = substr($currentCode, 0, 6);

            $db->update('codes',[
                'status'=>'active',
                'code'=>$originalCode
            ],'id = :id',[':id'=>$id]);
        } else {
            // Solo cambiar estado
            $db->update('codes',['status'=>'active'],'id = :id',[':id'=>$id]);
        }
    }

    header("Location: clients.php");
    exit;
}

if(isset($_GET['delete'])){
    $id=(int)$_GET['delete'];
    $db->delete('codes','id = :id',[':id'=>$id]);
    header("Location: clients.php"); exit;
}

/* =======================
ELIMINAR TODOS LOS EXPIRADOS (SOLO MASTER)
======================= */
if(isset($_POST['delete_all_expired']) && $role === 'master'){
    // Obtener todos los códigos no-trial
    $allCodes = $db->select('codes','*',"owner != 'trial'",'created_at DESC');
    $deleted = 0;
    $errors = 0;
    
    foreach($allCodes as $code){
        $expRaw = $code['expires_at'] ?? '';
        $expTs = $expRaw ? strtotime($expRaw) : 0;
        $expired = ($expTs && $expTs < time());
        $status = $code['status'] ?? 'active';
        
        // Solo eliminar expirados que no estén bloqueados
        if($expired && $status !== 'blocked'){
            if($db->delete('codes','id = :id',[':id'=>$code['id']])){
                $deleted++;
            } else {
                $errors++;
            }
        }
    }
    
    $_SESSION['message'] = "✅ Se eliminaron $deleted códigos expirados." . ($errors > 0 ? " ❌ Errores: $errors" : "");
    header("Location: clients.php");
    exit;
}

/* =======================
OBTENER CREDITOS
======================= */
$myCredits = 0;
if ($role !== 'master') {
    $me = $db->select('menualuser','credits','username = :u','',[':u' => $currentUser]);
    $myCredits = (int)($me[0]['credits'] ?? 0);
}

/* =======================
LISTAR CODIGOS (EXCLUYENDO TRIALS)
======================= */
if ($role === 'master') {
    // Master ve todos los códigos EXCEPTO los de trial
    $allCodes = $db->select('codes','*',"owner != 'trial'",'created_at DESC');
} else {
    // Resellers solo ven sus propios códigos
    $allCodes = $db->select('codes','*',"owner = :o AND owner != 'trial'",'created_at DESC',[':o'=>$currentUser]);
}

/* =======================
PAGINACION
======================= */
$itemsPerPage = 15;
$totalItems = count($allCodes);
$totalPages = ceil($totalItems / $itemsPerPage);
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$currentPage = max(1, min($currentPage, $totalPages));
$offset = ($currentPage - 1) * $itemsPerPage;
$codes = array_slice($allCodes, $offset, $itemsPerPage);

/* =======================
ESTADÍSTICAS
======================= */
$totalClients = count($allCodes);
$activeClients = 0;
$blockedClients = 0;
$expiredClients = 0;

foreach ($allCodes as $c) {
    $status = $c['status'] ?? 'active';
    $expRaw = $c['expires_at'] ?? '';
    $expTs = $expRaw ? strtotime($expRaw) : 0;
    $expired = ($expTs && $expTs < time());
    
    if ($status === 'blocked') {
        $blockedClients++;
    } elseif ($expired) {
        $expiredClients++;
    } else {
        $activeClients++;
    }
}
?>

<!-- Mostrar mensajes de éxito/error -->
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
    <i class="fa fa-check-circle"></i> <?=$_SESSION['message']?>
    <button type="button" class="close" data-dismiss="alert">
        <span>&times;</span>
    </button>
</div>
<?php unset($_SESSION['message']); ?>
<?php endif; ?>

<div class="col-md-12 mx-auto">
<div class="card text-white" style="background:#1a1a1a">
<div class="card-header d-flex justify-content-between align-items-center flex-wrap">
    <div>
        <h3><i class="fa fa-users"></i> Gestión de Clientes</h3>
        <small>Administración de clientes registrados</small>
    </div>
    <div class="mt-2 mt-md-0">
        <?php if ($role === 'master'): ?>
        <button type="button" class="btn btn-danger" id="openModalBtn">
            <i class="fa fa-trash-o"></i> Eliminar Expirados
        </button>
        <?php endif; ?>
        <a href="addclient.php" class="btn btn-info">
            <i class="fa fa-plus"></i> Registrar Nuevo Cliente
        </a>
    </div>
</div>

<div class="card-body">

<?php if ($role !== 'master'): ?>
<div class="alert alert-dark d-flex justify-content-between align-items-center">
    <span><i class="fa fa-coins"></i> Créditos disponibles: <b><?=$myCredits?></b></span>
    <a href="addclient.php" class="btn btn-sm btn-success">
        <i class="fa fa-user-plus"></i> Usar Crédito
    </a>
</div>
<?php endif; ?>

<!-- Estadísticas -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card bg-dark border-info">
            <div class="card-body text-center">
                <h4 class="text-info"><?=$totalClients?></h4>
                <small class="text-muted">Total Clientes</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-dark border-success">
            <div class="card-body text-center">
                <h4 class="text-success"><?=$activeClients?></h4>
                <small class="text-muted">Activos</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-dark border-warning">
            <div class="card-body text-center">
                <h4 class="text-warning"><?=$blockedClients?></h4>
                <small class="text-muted">Bloqueados</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-dark border-danger">
            <div class="card-body text-center">
                <h4 class="text-danger"><?=$expiredClients?></h4>
                <small class="text-muted">Expirados</small>
            </div>
        </div>
    </div>
</div>

<!-- Filtros -->
<div class="row mb-3">
    <div class="col-md-8">
        <input type="text" class="form-control" placeholder="🔍 Buscar por código, cliente o whatsapp..." id="searchBox">
    </div>
    <div class="col-md-4">
        <select class="form-control" id="filterStatus">
            <option value="">Todos los estados</option>
            <option value="active">Activos</option>
            <option value="blocked">Bloqueados</option>
            <option value="expired">Expirados</option>
        </select>
    </div>
</div>

<div class="table-responsive">
<table class="table table-dark table-hover" id="codesTable">
<thead>
<tr>
    <th><i class="fa fa-key"></i> Código</th>
    <th><i class="fa fa-user"></i> Cliente</th>
    <th><i class="fa fa-phone"></i> WhatsApp</th>
    <?php if ($role === 'master'): ?><th><i class="fa fa-user-tie"></i> Reseller</th><?php endif; ?>
    <th><i class="fa fa-calendar"></i> Vencimiento</th>
    <th><i class="fa fa-info-circle"></i> Estado</th>
    <th><i class="fa fa-cog"></i> Acciones</th>
</tr>
</thead>
<tbody>

<?php if (!$codes): ?>
<tr>
    <td colspan="<?= $role === 'master' ? '7' : '6' ?>" class="text-center py-5">
        <i class="fa fa-inbox fa-3x text-muted mb-3"></i>
        <p class="text-muted">No hay clientes registrados</p>
        <a href="addclient.php" class="btn btn-info mt-2">
            <i class="fa fa-plus"></i> Registrar Primer Cliente
        </a>
    </td>
</tr>
<?php else: ?>
<?php foreach ($codes as $c):
    $expRaw = $c['expires_at'] ?? '';
    $expTs = $expRaw ? strtotime($expRaw) : 0;
    $expired = ($expTs && $expTs < time());
    $days = $expTs ? floor(($expTs-time())/86400) : 0;
    $status = $c['status'] ?? 'active';
    $clientName = $c['client_name'] ?? 'Sin nombre';
    $clientWhatsapp = $c['client_whatsapp'] ?? 'Sin WhatsApp';
    
    // Determinar estado real
    $realStatus = $status;
    if ($expired && $status !== 'blocked') {
        $realStatus = 'expired';
    }
?>
<tr data-status="<?=htmlspecialchars($realStatus)?>" data-id="<?=$c['id']?>">
    <td>
        <strong class="text-info"><?=htmlspecialchars($c['code'])?></strong><br>
        <small class="text-muted">
            <i class="fa fa-clock"></i> <?=htmlspecialchars($c['created_at'] ?? '-')?>
        </small>
    </td>
    <td>
        <strong><?=htmlspecialchars($clientName)?></strong>
    </td>
    <td>
        <?php if ($clientWhatsapp !== 'Sin WhatsApp'): ?>
            <a href="https://wa.me/<?=htmlspecialchars($clientWhatsapp)?>" target="_blank" class="text-success">
                <i class="fab fa-whatsapp"></i> <?=htmlspecialchars($clientWhatsapp)?>
            </a>
        <?php else: ?>
            <span class="text-muted">Sin WhatsApp</span>
        <?php endif; ?>
    </td>
    <?php if ($role === 'master'): ?>
    <td>
        <span class="badge bg-secondary">
            <i class="fa fa-user"></i> <?=htmlspecialchars($c['owner'] ?? '-')?>
        </span>
    </td>
    <?php endif; ?>
    <td class="expiry-cell">
        <?=htmlspecialchars($expRaw ?: '-')?><br>
        <?php if(!$expired): ?>
            <?php if($days > 7): ?>
                <span class="badge bg-success">
                    <i class="fa fa-check-circle"></i> <?=$days?> días
                </span>
            <?php elseif($days > 3): ?>
                <span class="badge bg-warning">
                    <i class="fa fa-exclamation-triangle"></i> <?=$days?> días
                </span>
            <?php else: ?>
                <span class="badge bg-danger">
                    <i class="fa fa-clock"></i> <?=$days?> días
                </span>
            <?php endif; ?>
        <?php else: ?>
            <span class="badge bg-danger">
                <i class="fa fa-times-circle"></i> Expirado
            </span>
        <?php endif; ?>
    </td>
    <td class="status-cell">
        <?php if($status=='blocked'): ?>
            <span class="badge bg-warning">
                <i class="fa fa-ban"></i> Bloqueado
            </span>
        <?php elseif($expired): ?>
            <span class="badge bg-danger">
                <i class="fa fa-times-circle"></i> Expirado
            </span>
        <?php else: ?>
            <span class="badge bg-success">
                <i class="fa fa-check-circle"></i> Activo
            </span>
        <?php endif; ?>
    </td>
    <td>
        <div class="btn-group" role="group">
            <!-- WhatsApp -->
            <?php if ($clientWhatsapp !== 'Sin WhatsApp'): ?>
            <button class="btn btn-sm btn-success" 
                    onclick="sendWhatsApp('<?=htmlspecialchars($c['code'])?>','<?=htmlspecialchars($expRaw)?>','<?=htmlspecialchars($clientWhatsapp)?>','<?=htmlspecialchars($clientName)?>')"
                    title="Enviar por WhatsApp">
                <i class="fab fa-whatsapp"></i>
            </button>
            <?php endif; ?>
            
            <!-- Copiar -->
            <button class="btn btn-sm btn-info" 
                    onclick="copyCode('<?=htmlspecialchars($c['code'])?>')"
                    title="Copiar código">
                <i class="fa fa-copy"></i>
            </button>
            
            <!-- Bloquear / Desbloquear -->
            <?php if($status=='active'): ?>
                <a href="?block=<?=$c['id']?>" 
                   class="btn btn-sm btn-warning" 
                   onclick="return confirm('¿Bloquear este cliente?')"
                   title="Bloquear">
                    <i class="fa fa-ban"></i>
                </a>
            <?php else: ?>
                <a href="?unblock=<?=$c['id']?>" 
                   class="btn btn-sm btn-success" 
                   onclick="return confirm('¿Desbloquear este cliente?')"
                   title="Desbloquear">
                    <i class="fa fa-check"></i>
                </a>
            <?php endif; ?>
            
            <!-- Editar -->
            <a href="editclient.php?id=<?=$c['id']?>" 
               class="btn btn-sm btn-primary"
               title="Editar">
                <i class="fa fa-edit"></i>
            </a>
            
            <!-- Eliminar -->
            <a href="?delete=<?=$c['id']?>" 
               class="btn btn-sm btn-danger" 
               onclick="return confirm('¿Eliminar este cliente? Esta acción no se puede deshacer.')"
               title="Eliminar">
                <i class="fa fa-trash"></i>
            </a>
        </div>
    </td>
</tr>
<?php endforeach; ?>
<?php endif; ?>

</tbody>
</table>
</div>

<!-- Paginación -->
<?php if ($totalPages > 1): ?>
<nav aria-label="Page navigation" class="mt-4">
    <ul class="pagination justify-content-center">
        <!-- Botón Anterior -->
        <li class="page-item <?= $currentPage == 1 ? 'disabled' : '' ?>">
            <a class="page-link bg-dark text-white border-secondary" href="?page=<?= $currentPage - 1 ?>" tabindex="-1">
                <i class="fa fa-chevron-left"></i> Anterior
            </a>
        </li>
        
        <?php
        // Mostrar páginas con lógica de elipsis
        $startPage = max(1, $currentPage - 2);
        $endPage = min($totalPages, $currentPage + 2);
        
        if ($startPage > 1): ?>
            <li class="page-item">
                <a class="page-link bg-dark text-white border-secondary" href="?page=1">1</a>
            </li>
            <?php if ($startPage > 2): ?>
                <li class="page-item disabled"><span class="page-link bg-dark text-white border-secondary">...</span></li>
            <?php endif; ?>
        <?php endif; ?>
        
        <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
            <li class="page-item <?= $i == $currentPage ? 'active' : '' ?>">
                <a class="page-link <?= $i == $currentPage ? 'bg-info border-info' : 'bg-dark text-white border-secondary' ?>" 
                   href="?page=<?= $i ?>">
                    <?= $i ?>
                </a>
            </li>
        <?php endfor; ?>
        
        <?php if ($endPage < $totalPages): ?>
            <?php if ($endPage < $totalPages - 1): ?>
                <li class="page-item disabled"><span class="page-link bg-dark text-white border-secondary">...</span></li>
            <?php endif; ?>
            <li class="page-item">
                <a class="page-link bg-dark text-white border-secondary" href="?page=<?= $totalPages ?>"><?= $totalPages ?></a>
            </li>
        <?php endif; ?>
        
        <!-- Botón Siguiente -->
        <li class="page-item <?= $currentPage == $totalPages ? 'disabled' : '' ?>">
            <a class="page-link bg-dark text-white border-secondary" href="?page=<?= $currentPage + 1 ?>">
                Siguiente <i class="fa fa-chevron-right"></i>
            </a>
        </li>
    </ul>
</nav>
<div class="text-center text-muted small mt-2">
    Mostrando <?= count($codes) ?> de <?= $totalItems ?> clientes | Página <?= $currentPage ?> de <?= $totalPages ?>
</div>
<?php endif; ?>

<?php if ($codes): ?>
<div class="text-muted small mt-3">
    <i class="fa fa-info-circle"></i> 
    Mostrando <?=count($codes)?> cliente(s) en esta página. 
    Los códigos de prueba (trial) no se muestran en esta lista.
</div>
<?php endif; ?>

</div>
</div>
</div>

<!-- MODAL PERSONALIZADO (SOLO PARA MASTER, OCULTO POR DEFECTO) -->
<?php if ($role === 'master'): ?>
<style>
    /* Estilos del modal personalizado */
    .custom-modal-overlay {
        display: none;
        position: fixed;
        z-index: 999999;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.85);
        animation: fadeIn 0.3s;
    }
    
    .custom-modal-container {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 1000000;
        width: 90%;
        max-width: 500px;
    }
    
    .custom-modal-content {
        background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
        border: 2px solid #ffc107;
        border-radius: 15px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.5);
        animation: slideDown 0.3s;
    }
    
    .custom-modal-header {
        padding: 20px;
        border-bottom: 1px solid #ffc107;
        background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        border-radius: 15px 15px 0 0;
        color: white;
    }
    
    .custom-modal-header h5 {
        margin: 0;
        font-size: 1.25rem;
    }
    
    .custom-modal-body {
        padding: 20px;
        color: white;
    }
    
    .custom-modal-footer {
        padding: 15px 20px;
        border-top: 1px solid #333;
        text-align: right;
    }
    
    .custom-modal-footer button {
        padding: 8px 20px;
        margin-left: 10px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: all 0.3s;
        font-weight: bold;
    }
    
    .btn-custom-cancel {
        background-color: #6c757d;
        color: white;
    }
    
    .btn-custom-cancel:hover {
        background-color: #5a6268;
        transform: translateY(-1px);
    }
    
    .btn-custom-danger {
        background-color: #dc3545;
        color: white;
    }
    
    .btn-custom-danger:hover {
        background-color: #c82333;
        transform: translateY(-1px);
    }
    
    .btn-custom-danger:disabled {
        background-color: #6c757d;
        cursor: not-allowed;
        transform: none;
    }
    
    .close-modal-btn {
        float: right;
        font-size: 28px;
        font-weight: bold;
        color: white;
        cursor: pointer;
        background: none;
        border: none;
        position: absolute;
        right: 15px;
        top: 10px;
    }
    
    .close-modal-btn:hover {
        color: #ffc107;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    @keyframes slideDown {
        from {
            transform: translateY(-50px);
            opacity: 0;
        }
        to {
            transform: translateY(0);
            opacity: 1;
        }
    }
</style>

<!-- Overlay del modal (oculto por defecto) -->
<div id="customModalOverlay" class="custom-modal-overlay"></div>

<!-- Contenido del modal (oculto por defecto) -->
<div id="customModalContainer" class="custom-modal-container">
    <div class="custom-modal-content">
        <div class="custom-modal-header">
            <button class="close-modal-btn" onclick="closeCustomModal()">&times;</button>
            <h5>
                <i class="fa fa-exclamation-triangle"></i> 
                Eliminar Códigos Expirados
            </h5>
        </div>
        <div class="custom-modal-body">
            <div class="alert alert-warning" style="background-color: #856404; color: #fff; border: none;">
                <i class="fa fa-warning"></i> 
                <strong>¡Atención!</strong> Esta acción es irreversible.
            </div>
            <p>¿Estás seguro de eliminar <strong>TODOS los códigos expirados</strong>?</p>
            <p class="text-info">
                <i class="fa fa-info-circle"></i> 
                Los códigos bloqueados NO se eliminarán.
            </p>
            <div class="alert alert-dark" style="background-color: #0c5460; border: none; color: #fff;">
                <strong>📊 Estadísticas actuales:</strong><br>
                Códigos expirados: <strong class="text-warning" id="expiredCountDisplay"><?=$expiredClients?></strong>
            </div>
        </div>
        <div class="custom-modal-footer">
            <button class="btn-custom-cancel" onclick="closeCustomModal()">
                <i class="fa fa-times"></i> Cancelar
            </button>
            <form method="POST" id="deleteExpiredForm" style="display: inline-block;">
                <button type="submit" name="delete_all_expired" class="btn-custom-danger" id="confirmDeleteBtn" <?=$expiredClients == 0 ? 'disabled' : ''?>>
                    <i class="fa fa-trash"></i> Eliminar <?=$expiredClients?> expirados
                </button>
            </form>
        </div>
    </div>
</div>

<script>
    // Funciones del modal personalizado
    function openCustomModal() {
        document.getElementById('customModalOverlay').style.display = 'block';
        document.getElementById('customModalContainer').style.display = 'block';
        document.body.style.overflow = 'hidden';
    }
    
    function closeCustomModal() {
        document.getElementById('customModalOverlay').style.display = 'none';
        document.getElementById('customModalContainer').style.display = 'none';
        document.body.style.overflow = 'auto';
    }
    
    // Esperar a que el DOM esté listo
    document.addEventListener('DOMContentLoaded', function() {
        var openBtn = document.getElementById('openModalBtn');
        if (openBtn) {
            openBtn.addEventListener('click', function(e) {
                e.preventDefault();
                openCustomModal();
            });
        }
    });
    
    // Cerrar con tecla ESC
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeCustomModal();
        }
    });
    
    // Cerrar al hacer clic fuera
    document.getElementById('customModalOverlay').addEventListener('click', function() {
        closeCustomModal();
    });
</script>
<?php endif; ?>

<script>
// Función para enviar por WhatsApp
function sendWhatsApp(code, expire, phone, name) {
    if (!phone || phone === 'Sin WhatsApp') {
        alert("Este cliente no tiene WhatsApp registrado");
        return;
    }
    
    const msg = "🎬 *Datos de Acceso MyTube Premium*\n\n" +
                "👤 Cliente: " + name + "\n" +
                "🔑 Código: *" + code + "*\n" +
                "📅 Vencimiento: " + expire + "\n\n" +
                "¡Gracias por tu preferencia!";
    
    const url = "https://wa.me/" + phone.replace(/\D/g, '') + "?text=" + encodeURIComponent(msg);
    window.open(url, "_blank");
}

// Función para copiar código
function copyCode(code) {
    navigator.clipboard.writeText(code).then(function() {
        // Crear notificación temporal
        const notification = document.createElement('div');
        notification.className = 'alert alert-success position-fixed top-0 start-50 translate-middle-x mt-3';
        notification.style.zIndex = '10000';
        notification.style.position = 'fixed';
        notification.style.top = '20px';
        notification.style.left = '50%';
        notification.style.transform = 'translateX(-50%)';
        notification.innerHTML = '<i class="fa fa-check-circle"></i> Código copiado: <strong>' + code + '</strong>';
        document.body.appendChild(notification);
        
        setTimeout(function() {
            notification.remove();
        }, 2000);
    }).catch(function(err) {
        alert("Error al copiar: " + err);
    });
}

// Búsqueda en tiempo real (solo en la página actual)
document.getElementById("searchBox").addEventListener("keyup", function() {
    const value = this.value.toLowerCase();
    const filterStatus = document.getElementById("filterStatus").value;
    
    document.querySelectorAll("#codesTable tbody tr").forEach(function(row) {
        const text = row.innerText.toLowerCase();
        const status = row.getAttribute('data-status');
        
        const matchesSearch = text.includes(value);
        const matchesFilter = !filterStatus || status === filterStatus;
        
        row.style.display = (matchesSearch && matchesFilter) ? "" : "none";
    });
});

// Filtro por estado
document.getElementById("filterStatus").addEventListener("change", function() {
    const searchBox = document.getElementById("searchBox");
    searchBox.dispatchEvent(new Event('keyup'));
});
</script>

<style>
.btn-group {
    display: flex;
    gap: 2px;
}

.btn-group .btn {
    border-radius: 4px !important;
}

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

.badge {
    padding: 6px 12px;
    font-size: 0.85rem;
}

/* Estilos de paginación */
.pagination .page-link {
    transition: all 0.3s ease;
}

.pagination .page-link:hover {
    background-color: #0d6efd !important;
    color: white !important;
    border-color: #0d6efd !important;
}

.pagination .active .page-link {
    background-color: #0dcaf0 !important;
    border-color: #0dcaf0 !important;
    color: #000 !important;
    font-weight: bold;
}

@media (max-width: 768px) {
    .btn-group {
        flex-wrap: wrap;
    }
    
    .table-responsive {
        font-size: 0.85rem;
    }
    
    .pagination {
        flex-wrap: wrap;
    }
}
</style>

<?php require_once __DIR__ . '/includes/footer.php'; ?>