<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$results_per_page = 100;

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

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

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

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

if (isset($_GET['delete'])) {
    $ids_to_delete = explode(',', $_GET['delete']);
    foreach ($ids_to_delete as $id) {
        // Get the usuario of the revenda being deleted
        $revenda_result = $db1->query("SELECT usuario FROM revenda WHERE id = $id");
        $revenda_row = $revenda_result->fetchArray();
        $usuario = $revenda_row['usuario'];

        // Delete the revenda from the database
        $db1->exec("DELETE FROM revenda WHERE id = $id");

        // Remove associated files
        @unlink("a/rtx/Setting_$usuario.json");
        @unlink("a/rtx/logo_filenames_$usuario.json");
        @unlink("a/rtx/image_filenames_$usuario.json");
        @unlink("a/note_$usuario.json");
        @unlink("api/theme_$usuario.json");

        // 🔁 ALTERAÇÃO: exclui permanentemente os usuários vinculados à revenda
        $db1->exec("DELETE FROM ibo WHERE seller = '$usuario'");

        // Remove ads e intro associados
        $db2 = new SQLite3("api/.adb.db");
        $db2->exec("DELETE FROM ads WHERE owner = '$usuario'");
        $db3 = new SQLite3("api/intro.db");
        $db3->exec("DELETE FROM intro WHERE owner = '$usuario'");
    }
    header('Location: revenda.php');
    exit();
}

include 'includes/header.php';
?>

<script>
  document.addEventListener("DOMContentLoaded", function() {
        document.getElementById("selecionarTodos").addEventListener("click", function() {
            var checkboxes = document.querySelectorAll("input[name='delete_check[]']");
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = true;
            });
        });

        document.getElementById("excluirSelecionados").addEventListener("click", function() {
            var selectedIds = [];
            var checkboxes = document.querySelectorAll("input[name='delete_check[]']");
            checkboxes.forEach(function(checkbox) {
                if (checkbox.checked) {
                    selectedIds.push(checkbox.value);
                }
            });
            if (selectedIds.length > 0) {
                var confirmation = confirm("Tem certeza de que deseja excluir os itens selecionados?");
                if (confirmation) {
                    window.location.href = 'revenda.php?delete=' + selectedIds.join(',');
                }
            } else {
                alert("Por favor, selecione pelo menos um item para excluir.");
            }
        });

        var deleteButtons = document.querySelectorAll(".delete-btn");
        deleteButtons.forEach(function(button) {
            button.addEventListener("click", function() {
                var deleteUrl = button.getAttribute("data-href");
                document.getElementById("delete-confirm-btn").setAttribute("href", deleteUrl);
            });
        });
    });
</script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<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">
                Você realmente deseja excluir este revenda?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok" id="delete-confirm-btn">Deletar</a>
            </div>
        </div>
    </div>
</div>

<main role="main" class="col-15 pt-4 px-5">
    <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="m-0 font-weight-bold text-primary2"><i class="fas fa-fw fa-user-plus"></i> Revendas</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="Pesquise por nome ou usuario">
                                        <div class="input-group-append">
                                            <button type="submit" class="btn btn-primary">Pesquisar</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                            <div class="form-group">
                                <div class="input-group">
                                    <a href="./revenda_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">Criar</span>
                                    </a>
                                    <button type="button" class="btn btn-danger ml-2" id="excluirSelecionados">Excluir Selecionados</button>
                                </div>
                            </div>
                            <br>
                            <div class="table-responsive">
                                <table class="table table-striped table-sm">
                                    <thead class="text-primary">
                                        <tr>
                                            <th><input type="checkbox" id="selecionarTodos" onclick="selecionarTodos()"></th>
                                            <th>Ref.ID</th>
                                            <th>Nome</th>
                                            <th>Usuario</th>
                                            <th>Senha</th>
                                            <th>Registro</th>
                                            <th>MACs</th>
                                            <th>Extra</th>
                                            <th>Editar</th>
                                            <th>Deletar</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($row1 = $res1->fetchArray()) { ?>
                                            <tr>
                                                <?php
                                                $revenda_id = $row1['id'];
                                                $revenda_rid = $row1['id_ref'];
                                                $revenda_nome = $row1['nome'];
                                                $revenda_usuario = $row1['usuario'];
                                                $revenda_senha = $row1['senha'];
                                                $revenda_registro = $row1['registro'];
                                                $revenda_macs = $row1['macs'];
                                                ?>
                                                <td><input type="checkbox" name="delete_check[]" value="<?php echo $revenda_id; ?>"></td>
                                                <td><?php echo $revenda_rid; ?></td>
                                                <td><?php echo $revenda_nome; ?></td>
                                                <td><?php echo $revenda_usuario; ?></td>
                                                <td><?php echo $revenda_senha; ?></td>
                                                <td><?php echo $revenda_registro; ?></td>
                                                <td><?php echo $revenda_macs; ?></td>
                                                <td><?php echo $row1['extra']; ?></td>
                                                <td>
                                                    <a class="btn btn-icon" href="./revenda_update.php?update=<?php echo $revenda_id; ?>">
                                                        <span class="icon text-white-50"><i class="fa fa-pencil-square" style="font-size:24px;color:white"></i></span>
                                                    </a>
                                                </td>
                                                <td>
                                                    <a class="btn btn-icon delete-btn" href="#" data-href="./revenda.php?delete=<?php echo $revenda_id; ?>" 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>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php if ($results_per_page < $totaleview) { ?>
                                <div class="pagination">
                                    <?php if ($page > 1) { ?>
                                        <a class="pagination pagination-gap" href='revenda.php?view=<?php echo ($page - 1); ?>'>&lt; Previous</a>
                                    <?php } ?>
                                    <?php for ($i = 1; $i <= $total_pages; $i++) { ?>
                                        <?php if ($i == $page) { ?>
                                            <a class="active pagination pagination-red" href='revenda.php?view=<?php echo $i; ?>'>[<?php echo $i; ?>]</a>
                                        <?php } else { ?>
                                            <a class="pagination pagination-gap" href='revenda.php?view=<?php echo $i; ?>'><?php echo $i; ?></a>
                                        <?php } ?>
                                    <?php } ?>
                                    <?php if ($page < $total_pages) { ?>
                                        <a class="pagination pagination-gap" href='revenda.php?view=<?php echo ($page + 1); ?>'>Next &gt;</a>
                                    <?php } ?>
                                </div>
                            <?php } ?>
                            <?php include 'includes/footer.php'; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>