<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Opciones de items por página
$items_per_page_options = [5, 10, 20, 50, 100];
$default_items_per_page = 15;

// Obtener el valor seleccionado de items por página
if (isset($_GET['per_page']) && in_array($_GET['per_page'], $items_per_page_options)) {
    $results_per_page = (int)$_GET['per_page'];
} else {
    $results_per_page = $default_items_per_page;
}

if (isset($_GET['view'])) {
    $page = (int)$_GET['view'];
} else {
    $page = 1;
}

$start_from = ($page - 1) * $results_per_page;
$db1 = new SQLite3('./api/.db.db');

// Search functionality
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$searchQuery = '';
if (!empty($searchTerm)) {
    $searchQuery = "WHERE mac_address LIKE '%$searchTerm%' OR title LIKE '%$searchTerm%'";
}

$result = $db1->query("SELECT COUNT(id) AS total FROM ibo $searchQuery");
$rownew = $result->fetchArray();
$totaleview = $rownew['total'];
$total_pages = ceil($rownew['total'] / $results_per_page);
$res1 = $db1->query("SELECT * FROM ibo $searchQuery ORDER BY id ASC LIMIT $start_from, $results_per_page");

if (isset($_GET['delete_expired']) && $_GET['delete_expired'] == 'true') {
    $today = date('Y-m-d');
    
    // Primero obtener las MACs de los usuarios vencidos
    $result = $db1->query("SELECT mac_address FROM ibo WHERE expire_date < '$today'");
    $macs = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $macs[] = SQLite3::escapeString($row['mac_address']);
    }
    
    // Eliminar de ibo
    $db1->exec("DELETE FROM ibo WHERE expire_date < '$today'");
    
    // Eliminar de subscription para las MACs vencidas
    if (!empty($macs)) {
        $macs_list = "'" . implode("','", $macs) . "'";
        $db1->exec("DELETE FROM subscription WHERE mac_address IN ($macs_list)");
    }
    
    header('Location: users.php');
    exit();
}
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    
    // Obtener la MAC antes de eliminar
    $stmt = $db1->prepare("SELECT mac_address FROM ibo WHERE id = :id");
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $result = $stmt->execute();
    $row = $result->fetchArray(SQLITE3_ASSOC);
    
    if ($row) {
        $mac = $row['mac_address'];
        
        // Eliminar de ibo
        $db1->exec("DELETE FROM ibo WHERE id = $id");

        // También eliminar de subscription por MAC
        $db1->exec("DELETE FROM subscription WHERE mac_address = '" . SQLite3::escapeString($mac) . "'");
    }

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

include 'includes/header.php';
?>
<style>
  .pagination-gap {
    margin-left: 2px; 
    margin-right: 2px; 
    background-color: red; 
    color: white; 
    padding: 5px 10px;
  }

  .pagination-red {
    margin-left: 2px; 
    margin-right: 2px; 
    background-color: red; 
    color: white; 
    text-align: center; 
    padding: 5px 10px;
  }
  .text-color{
    color: white;
  }
  .page-item.active .page-link {
    background-color: darkred;
    border-color: red;
  }
  .per-page-selector {
    width: 80px;
    display: inline-block;
    margin-right: 10px;
  }
@media (max-width: 576px) {
  .modal-dialog.modal-custom {
    max-width: 50% !important;
    margin: 1rem auto;
    margin-left: 0;
    top: 0;
    transform: none !important;
  }
}
</style>
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Confirmar</h2>
            </div>
            <div class="modal-body">
                Realmente deseas eliminar este usuario?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Eliminar</a>
            </div>
        </div>
    </div>
</div>
<div class="col-md-12 mx-auto">
<div class="mx-auto w-100" style="max-width: 1200px;">
    <div class="">
        <div class="chartjs-size-monitor" style="position:absolute ; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;">
            <div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
                <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div>
            </div>
            <div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
                <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div>
            </div>
        </div>
        <div id="main">
    <!-- Content Row -->
    <div class="row">
        <!-- First Column -->
        <div class="col-lg-12">
            <!-- Custom codes -->
            <div class="card border-left-primary shadow h-100 card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="card-title-dark"><i class="fa fa-fw fa-user-plus"></i>Usuarios Clientes</h6>
                </div>
                <div class="card-body">
                    <form method="get" class="mb-3">
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" name="search" class="form-control" placeholder="Buscar por Nombre o por Mac" value="<?= htmlspecialchars($searchTerm) ?>">
                                <div class="input-group-append">
                                    <button type="submit" class="btn btn-primary">Buscar</button>
                                </div>
                            </div>
                        </div>
                    </form>
                    <div class="form-group">
                        <div class="input-group">
                            <a href="./users_create.php" class="btn btn-primary btn-icon-split">
                                <span class="icon text-white-50"><i class="fas fa-check"></i></span>
                                <span class="text">Registrar Nuevo</span>
                            </a>
                            <a href="users.php?delete_expired=true&per_page=<?= $results_per_page ?><?= !empty($searchTerm) ? '&search='.urlencode($searchTerm) : '' ?>" class="btn btn-danger btn-icon-split ml-2" onclick="return confirm('¿Estás seguro de eliminar todos los usuarios vencidos?');">
                                <span class="icon text-white-50"><i class="fas fa-trash"></i></span>
                                <span class="text">Eliminar Vencidos</span>
                            </a>
                        </div>
                    </div>
                    <br>
                    <div class="table-responsive">
                        <table class="table table-striped table-sm">
                            <thead class="text-color">
                                <tr>
                                    <th>Nombre</th>
                                    <th>Mac Address</th>
                                    <th>Usuario</th>
                                    <th>Expiración</th>
                                    <th>DNS</th>
                                    <th>Editar</th>
                                    <th>Eliminar</th>
                                    <th>Estado</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($row1 = $res1->fetchArray()) { ?>
                                    <tr>
                                        <?php
                                        $users_id = $row1['id'];
                                        $user_mac = $row1['mac_address'];
                                        $user_username = $row1['username'];
                                        $user_expire_date = $row1['expire_date'];
                                        $user_url = $row1['url'];
                                        $user_title = $row1['title'];
                                        $user_whatsapp = $row1['whatsapp'] ?? ''; // Asegurarse de que existe este campo
                                        ?>
                                        <td><?php echo htmlspecialchars($user_title); ?></td>
                                        <td><?php echo htmlspecialchars($user_mac); ?></td>
                                        <td><?php echo htmlspecialchars($user_username); ?></td>
                                        <td><?php echo htmlspecialchars($user_expire_date); ?></td>
                                        <td><?php echo htmlspecialchars($user_url); ?></td>
                                        <td>
                                            <a class="btn btn-icon" href="./users_update.php?update=<?php echo $users_id; ?>">
                                                <span class="icon text-white-50"><i class="fa fa-pencil-square" style="font-size:24px;color:blue"></i></span>
                                            </a>
                                        </td>
                                        <td>
                                            <a class="btn btn-icon delete-btn" href="#" data-href="./users.php?delete=<?php echo $users_id; ?>&per_page=<?= $results_per_page ?><?= !empty($searchTerm) ? '&search='.urlencode($searchTerm) : '' ?>" data-toggle="modal" data-target="#confirm-delete">
                                                <span class="icon text-white-50"><i class="fa fa-ban" style="font-size:24px;color:red"></i></span>
                                            </a>
                                        </td>
                                        <td>
                                            <?php
                                            $today = date('Y-m-d');
                                            $expire_date = new DateTime($user_expire_date);
                                            $current_date = new DateTime($today);
                                            $days_remaining = $current_date->diff($expire_date)->days;
                                            
                                            if ($user_expire_date < $today) {
                                                echo '<span style="color:red;">❌Vencido</span>';
                                            } elseif ($days_remaining <= 3) {
                                                echo '<span style="color:orange;">⚠️Por Vencer ('.$days_remaining.' días)</span>';
                                                // Mostrar botón de recordatorio solo si tiene WhatsApp y está por vencer
                                                if (!empty($user_whatsapp)) {
                                                    echo '<br><a href="#" class="btn btn-sm btn-warning send-reminder" 
                                                          data-whatsapp="'.htmlspecialchars($user_whatsapp).'" 
                                                          data-name="'.htmlspecialchars($user_title).'" 
                                                          data-days="'.$days_remaining.'" 
                                                          data-expire="'.htmlspecialchars($user_expire_date).'">
                                                          <i class="fa fa-bell"></i> Recordatorio
                                                      </a>';
                                                }
                                            } else {
                                                echo '<span style="color:green;">✅Activo <!--('.$days_remaining.' días)--></span>';
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <!-- Selector de items por página y paginación -->
                    <div class="row">
                        <div class="col-md-6">
                            <form method="get" class="form-inline">
                                <?php if (!empty($searchTerm)): ?>
                                    <input type="hidden" name="search" value="<?= htmlspecialchars($searchTerm) ?>">
                                <?php endif; ?>
                                <label for="per_page" class="mr-2">Items por página:</label>
                                <select name="per_page" id="per_page" class="form-control per-page-selector" onchange="this.form.submit()">
                                    <?php foreach ($items_per_page_options as $option): ?>
                                        <option value="<?= $option ?>" <?= $results_per_page == $option ? 'selected' : '' ?>><?= $option ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </form>
                        </div>
                        <div class="col-md-6">
                            <?php if ($total_pages > 1): ?>
                            <nav aria-label="Page navigation" class="float-right">
                                <ul class="pagination">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link pagination-red" href="?view=<?= ($page - 1) ?>&per_page=<?= $results_per_page ?><?= !empty($searchTerm) ? '&search='.urlencode($searchTerm) : '' ?>" aria-label="Previous">
                                                <span aria-hidden="true">&laquo;</span>
                                            </a>
                                        </li>
                                    <?php endif; ?>

                                    <?php 
                                    // Mostrar siempre la primera página
                                    if ($page != 1): ?>
                                        <li class="page-item">
                                            <a class="page-link pagination-gap <?= ($page == 1) ? 'active' : '' ?>" href="?view=1&per_page=<?= $results_per_page ?><?= !empty($searchTerm) ? '&search='.urlencode($searchTerm) : '' ?>">1</a>
                                        </li>
                                        <?php if ($page > 3): ?>
                                            <li class="page-item disabled"><span class="page-link pagination-gap">...</span></li>
                                        <?php endif; ?>
                                    <?php endif; ?>

                                    <?php 
                                    // Mostrar páginas alrededor de la actual
                                    $start = max(2, $page - 2);
                                    $end = min($total_pages - 1, $page + 2);
                                    
                                    for ($i = $start; $i <= $end; $i++): ?>
                                        <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                                            <a class="page-link pagination-gap" href="?view=<?= $i ?>&per_page=<?= $results_per_page ?><?= !empty($searchTerm) ? '&search='.urlencode($searchTerm) : '' ?>"><?= $i ?></a>
                                        </li>
                                    <?php endfor; ?>

                                    <?php 
                                    // Mostrar siempre la última página
                                    if ($total_pages > 1 && $page != $total_pages): ?>
                                        <?php if ($page < $total_pages - 2): ?>
                                            <li class="page-item disabled"><span class="page-link pagination-gap">...</span></li>
                                        <?php endif; ?>
                                        <li class="page-item">
                                            <a class="page-link pagination-gap <?= ($page == $total_pages) ? 'active' : '' ?>" href="?view=<?= $total_pages ?>&per_page=<?= $results_per_page ?><?= !empty($searchTerm) ? '&search='.urlencode($searchTerm) : '' ?>"><?= $total_pages ?></a>
                                        </li>
                                    <?php endif; ?>

                                    <?php if ($page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link pagination-red" href="?view=<?= ($page + 1) ?>&per_page=<?= $results_per_page ?><?= !empty($searchTerm) ? '&search='.urlencode($searchTerm) : '' ?>" aria-label="Next">
                                                <span aria-hidden="true">&raquo;</span>
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modal -->
<div class="modal fade" id="avisoModal" tabindex="-1" role="dialog" aria-labelledby="avisoModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-custom" role="document">

    <div class="modal-content border-secondary">
      <div class="modal-header bg-light text-dark border-bottom border-secondary">
        <h5 class="modal-title" id="avisoModalLabel">ℹ️ IMPORTANTE</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body text-dark">
        <ol class="mb-0 pl-3 small">
          <li>
            Si creas varias activaciones para la misma <strong>MAC</strong>, asegúrate de eliminar las activaciones vencidas.<br>
            Cuando una cuenta está <strong>vencida</strong>, <u>la app no se podrá usar</u>.
          </li>
          <li>
            Usa el botón de <strong>Eliminar vencidos</strong> o la función de <strong>modo automático</strong> en <em>Limpieza del Sistema</em>.
          </li>
          <li>
            Las activaciones por <strong>código</strong> no mostrarán botón de recordatorio de vencimiento.<br>
            Para que se muestre, usa Editar y agrega el <strong>WhatsApp del cliente</strong> a notificar.
          </li>
        </ol>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-warning btn-sm" data-dismiss="modal">Entendido</button>
      </div>
    </div>
  </div>
</div>


<!-- Mostrar modal automáticamente al cargar -->
<script>
  $(document).ready(function() {
    $('#avisoModal').modal('show');
  });
</script>
<script>
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
    
    // Función para enviar el formulario cuando cambia el selector
    document.getElementById('per_page').addEventListener('change', function() {
        this.form.submit();
    });
</script>
<?php include 'includes/footer.php'; ?>