<?php

session_start(); // Inicia a sessão

$db = new SQLite3('./api/.boxbrdb.db');
$db->exec('CREATE TABLE IF NOT EXISTS dns(id INTEGER PRIMARY KEY NOT NULL, dns_title VARCHAR(25), url VARCHAR(25))');
$res = $db->query('SELECT * FROM dns');

// Deletar registro direto
if (isset($_GET['delete'])) {
    $db->exec('DELETE FROM dns WHERE id=' . $_GET['delete']);
    $db->close();
    header('Location: dns.php');
    exit;
}

// Atualizar ID
if (isset($_POST['submit_id_change'])) {
    $new_id = intval($_POST['new_id']);
    $current_id = intval($_POST['current_id']);

    if ($new_id != $current_id) {
        // Verifica se o novo ID já existe
        $stmt = $db->prepare("SELECT COUNT(*) FROM dns WHERE id = :id");
        $stmt->bindValue(':id', $new_id, SQLITE3_INTEGER);
        $count = $stmt->execute()->fetchArray()[0];

        if ($count == 0) {
            // Atualiza o ID no banco de dados
            $stmt = $db->prepare("UPDATE dns SET id = :new_id WHERE id = :current_id");
            $stmt->bindValue(':new_id', $new_id, SQLITE3_INTEGER);
            $stmt->bindValue(':current_id', $current_id, SQLITE3_INTEGER);
            $stmt->execute();

            // Redireciona para a página com o novo ID
            header('Location: dns.php');
            exit;
        } else {
            echo "<script>alert('ID já existe!');</script>";
        }
    } else {
        echo "<script>alert('Novo ID não pode ser igual ao atual!');</script>";
    }
}


?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DNS Dashboard</title>
    <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body, html {
            height: 100%;
            margin: 0;
            font-family: sans-serif;
            background-color: #000;
            position: relative;
        }

        #particles-js {
            position: fixed; /* Alterado para fixed para cobrir toda a tela */
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
        }

        .dashboard-container {
            position: relative;
            z-index: 1;
            background: rgba(50, 50, 50, 0.8);
            color: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
            text-align: center;
            margin-top: 50px;
            width: 80%;
            max-width: 900px;
            margin-left: auto; /* Centralizar o container */
            margin-right: auto; /* Centralizar o container */
        }

        h2 {
            color: #1cc88a;
            margin-bottom: 20px;
        }

        .action-bar {
            display: flex;
            justify-content: center; /* Centraliza os itens horizontalmente */
            align-items: center;
            margin-bottom: 20px;
            padding: 0 20px;
        }

        .action-bar > * {
            margin: 0 10px; /* Adiciona espaço entre os itens */
        }

        .action-bar a.btn-success {
            background-color: #1cc88a;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            transition: background-color 0.3s ease, transform 0.2s ease-in-out;
        }

        .action-bar a.btn-success:hover {
            background-color: #14855c;
            transform: scale(1.1); /* Adiciona o efeito de crescimento */
        }

        .search-input {
            display: flex;
            align-items: center;
            background-color: #444;
            border-radius: 8px;
            padding: 8px;
        }

        .search-input i {
            color: #1cc88a;
            font-size: 20px;
            margin-right: 10px;
        }

        .search-input input[type="text"] {
            background: none;
            border: none;
            color: white;
            padding: 8px;
            width: 250px;
        }

        .search-input input[type="text"]::placeholder {
            color: #ccc;
        }

        .dns-table-wrapper {
            width: 100%;
            box-sizing: border-box;
            padding: 0 20px;
            display: flex;
            justify-content: center; /* Centralizar a tabela dentro do wrapper */
        }

        .dns-table {
            width: auto; /* A tabela se ajusta ao conteúdo */
            border-collapse: collapse;
            margin-top: 20px;
        }

        .dns-table th, .dns-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #555;
        }

        .dns-table th {
            background-color: #333;
            color: #eee;
        }

        .dns-table tbody tr:hover {
            background-color: #444;
            transition: background-color 0.3s ease;
        }

        .dns-table tbody tr td {
            transition: transform 0.2s ease-in-out;
        }

        .dns-table tbody tr:hover td {
            transform: scale(1.02);
        }

        .btn-primary, .delete-btn { /* Renomeei a classe para evitar conflitos */
            background-color: #007bff;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            text-decoration: none;
            margin-right: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s ease-in-out;
        }

        .delete-btn {
            background-color: #dc3545;
            text-decoration: none !important; /* Remove o sublinhado */
        }

        .btn-warning {
            background-color: #ffc107;
            color: #333;
        }

        .btn-primary:hover, .delete-btn:hover, .btn-warning:hover {
            transform: scale(1.1);
        }

        .change-id-form {
            display: flex;
            align-items: center;
        }

        .change-id-form input[type="number"] {
            width: 70px;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
            background-color: #eee;
            color: #333;
        }

        .change-id-form button {
            background-color: #ffc107;
            color: #333;
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s ease-in-out;
        }

        .change-id-form button:hover {
            transform: scale(1.1);
            background-color: #e0a800;
        }
    </style>
</head>
<body>

    <div id="particles-js"></div> <?php include 'includes/header.php'; ?>

    <div class="dashboard-container">
        <h2>DNS Dashboard</h2>

        <div class="action-bar">
            <a href="./dns_create.php" class="btn btn-success">
                <i class="fas fa-plus"></i> Create
            </a>
            <div class="search-input">
                <i class="fas fa-search"></i>
                <input type="text" id="search" placeholder="Search Title / DNS" name="search_value"/>
            </div>
        </div>

        <div class="dns-table-wrapper">
            <table class="dns-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Change ID</th>
                        <th>DNS</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $db = new SQLite3('./api/.boxbrdb.db');
                    $res = $db->query('SELECT * FROM dns');
                    while ($row = $res->fetchArray()):
                        $id = $row['id'];
                        $url = $row['url'];
                    ?>
                        <tr>
                            <td><?php echo $id; ?></td>
                            <td>
                                <form method="post" class="change-id-form">
                                    <input type="hidden" name="current_id" value="<?php echo $id; ?>" />
                                    <input type="number" name="new_id" value="<?php echo $id; ?>" required />
                                    <button type="submit" name="submit_id_change">
                                        <i class="fa fa-refresh"></i> Change
                                    </button>
                                </form>
                            </td>
                            <td><?php echo $url; ?></td>
                            <td>
                                <a href="./dns_update.php?update=<?php echo $id; ?>" class="btn btn-primary">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="./dns.php?delete=<?php echo $id; ?>" class="delete-btn">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </td>
                        </tr>
                    <?php endwhile; $db->close(); ?>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        particlesJS('particles-js', {
            "particles": {
                "number": {
                    "value": 80,
                    "density": {
                        "enable": true,
                        "value_area": 800
                    }
                },
                "color": {
                    "value": "#1cc88a"
                },
                "shape": {
                    "type": "circle",
                    "stroke": {
                        "width": 0,
                        "color": "#000000"
                    }
                },
                "opacity": {
                    "value": 0.5,
                    "random": true,
                    "anim": {
                        "enable": true,
                        "speed": 1,
                        "opacity_min": 0.1
                    }
                },
                "size": {
                    "value": 3,
                    "random": true,
                    "anim": {
                        "enable": true,
                        "speed": 40,
                        "size_min": 0.1
                    }
                },
                "line_linked": {
                    "enable": true,
                    "distance": 150,
                    "color": "#1cc88a",
                    "opacity": 0.4,
                    "width": 1
                },
                "move": {
                    "enable": true,
                    "speed": 6,
                    "direction": "none",
                    "random": false,
                    "straight": false,
                    "out_mode": "out",
                    "attract": {
                        "enable": false,
                        "rotateX": 600,
                        "rotateY": 600
                    }
                }
            },
            "interactivity": {
                "detect_on": "canvas",
                "events": {
                    "onhover": {
                        "enable": true,
                        "mode": "repulse"
                    },
                    "onclick": {
                        "enable": true,
                        "mode": "push"
                    }
                }
            },
            "retina_detect": true
        });

        $("#search").keyup(function () {
            var value = this.value.toLowerCase().trim();

            $("table tbody tr").each(function (index) {
                if (!index) return;
                var found = false;
                $(this).find("td").each(function () {
                    var cellText = $(this).text().toLowerCase().trim();
                    if (cellText.indexOf(value) >= 0) {
                        found = true;
                        return false;
                    }
                });
                $(this).toggle(found);
            });
        });
    </script>

</body>
</html>