<?php
session_start();
$dns_file = __DIR__ . '/dns.json';
$config_file = __DIR__ . '/config.json';

if (!isset($_SESSION['logged_in'])) { header("Location: login.php"); exit; }

$config = is_array($c = json_decode(@file_get_contents($config_file), true)) ? $c : ["user" => "admin", "pass" => "pass123"];
$dns_data = is_array($j = json_decode(@file_get_contents($dns_file), true)) ? $j : [];

// --- ACTION: DELETE (With Fix) ---
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    unset($dns_data[$id]);
    // FIX: array_values ensures the JSON indices are reset (0, 1, 2...) so the app doesn't skip entries
    $dns_data = array_values($dns_data); 
    file_put_contents($dns_file, json_encode($dns_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    header("Location: index.php?status=deleted"); exit;
}

// --- ACTION: SAVE / UPDATE (With Fix) ---
if (isset($_POST['save_dns'])) {
    $url = $_POST['url'];
    if (isset($_POST['edit_id']) && $_POST['edit_id'] !== "") {
        $dns_data[$_POST['edit_id']] = $url;
    } else {
        $dns_data[] = $url;
    }
    // FIX: Force re-indexing before saving to prevent gaps like [0, 2, 4]
    $dns_data = array_values($dns_data); 
    file_put_contents($dns_file, json_encode($dns_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    header("Location: index.php?status=success"); exit;
}

if (isset($_POST['update_creds'])) {
    $config = ["user" => $_POST['new_user'], "pass" => $_POST['new_pass']];
    file_put_contents($config_file, json_encode($config));
}

if (isset($_FILES['image_file'])) {
    $target = ($_POST['upload_type'] == "logo") ? "logo.png" : "bg.jpg";
    move_uploaded_file($_FILES['image_file']['tmp_name'], __DIR__ . '/' . $target);
    header("Location: index.php"); exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Neutro Premium | Admin</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        :root { --primary: #007bff; --accent: #00d4ff; --bg: #0b0e14; --card-bg: #151921; }
        body { background-color: var(--bg); color: #fff; font-family: 'Inter', sans-serif; overflow-x: hidden; }
        #net-canvas { position: fixed; width: 100%; height: 100%; z-index: -1; top: 0; }
        
        #sidebar-wrapper { min-height: 100vh; width: 260px; background: #000; border-right: 1px solid #222; z-index: 100; transition: margin .25s ease-out; }
        .sidebar-heading { padding: 40px 20px; text-align: center; border-bottom: 1px solid #222; }
        .sidebar-logo img { max-width: 160px; filter: drop-shadow(0 0 8px var(--primary)); }
        .panel-ver { display: block; color: #fff; font-weight: bold; margin-top: 10px; letter-spacing: 1px; font-size: 14px; }
        
        .list-group-item { background: transparent; color: #888; border: none; padding: 15px 30px; transition: 0.3s; }
        .list-group-item:hover { color: var(--accent); background: rgba(0, 123, 255, 0.05); }
        .list-group-item.active { background: linear-gradient(90deg, var(--primary), transparent); color: #fff; border-left: 4px solid var(--accent); }
        
        .ctnav { background: rgba(0,0,0,0.8); backdrop-filter: blur(10px); border-bottom: 1px solid #222; }
        .card { background: var(--card-bg); border: 1px solid #2d343f; border-radius: 12px; }
        .card-header { background: transparent; border-bottom: 1px solid #2d343f; padding: 20px; }
        .form-control { background: #0b0e14; border: 1px solid #2d343f; color: #fff; border-radius: 8px; }
        .form-control:focus { background: #000; border-color: var(--primary); color: #fff; box-shadow: none; }
        
        .url-text { font-family: 'Courier New', monospace; color: var(--accent); }
    </style>
</head>
<body>
    <div id="net-canvas"></div> 
    <div class="d-flex" id="wrapper">
        <div id="sidebar-wrapper">
            <div class="sidebar-heading">
                <div class="sidebar-logo">
                    <img src="logo.png" onerror="this.src='https://via.placeholder.com/150x50/000/fff?text=NEUTRO'" alt="logo">
                    <span class="panel-ver">NEUTRO 7.5</span>
                </div>
            </div>
            <div class="list-group list-group-flush mt-3">
                <a class="list-group-item active" href="index.php"><i class="fa fa-server"></i>&nbsp;&nbsp; DNS Manager</a>
                <a class="list-group-item" href="#brandingModal" data-toggle="modal"><i class="fa fa-paint-brush"></i>&nbsp;&nbsp; Branding</a>
                <a class="list-group-item" href="#settingsModal" data-toggle="modal"><i class="fa fa-cog"></i>&nbsp;&nbsp; Settings</a>
                <a class="list-group-item text-danger" href="logout.php"><i class="fa fa-power-off"></i>&nbsp;&nbsp; Logout</a>
            </div>
        </div>

        <div id="page-content-wrapper" class="w-100">
            <nav class="navbar navbar-expand-lg navbar-dark ctnav">
                <button class="btn btn-outline-secondary btn-sm" id="menu-toggle"><i class="fa fa-bars"></i></button>
                <span class="ml-3 text-uppercase small" style="letter-spacing: 2px;">Management Portal</span>
            </nav>

            <div class="container-fluid py-4">
                <div class="row">
                    <div class="col-lg-10 mx-auto">
                        
                        <div class="card mb-4 shadow-sm">
                            <div class="card-header"><h5 class="mb-0" id="form-title">Add New DNS</h5></div>
                            <div class="card-body">
                                <form method="POST" id="dns-form">
                                    <input type="hidden" name="edit_id" id="edit_id">
                                    <div class="row align-items-end">
                                        <div class="col-md-9 mb-2">
                                            <label class="small text-muted">Portal Endpoint URL</label>
                                            <input type="url" name="url" id="dns_url" class="form-control" placeholder="http://domain.com:8080" required>
                                        </div>
                                        <div class="col-md-3 mb-2">
                                            <button name="save_dns" id="save-btn" class="btn btn-primary btn-block">Save Server</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <div class="card shadow-sm">
                            <div class="card-header d-flex justify-content-between">
                                <h5 class="mb-0">Active DNS List</h5>
                                <span class="badge badge-primary"><?php echo count($dns_data); ?> Saved</span>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover mb-0" style="color: #ccc;">
                                    <thead class="thead-dark">
                                        <tr>
                                            <th width="80">ID</th>
                                            <th>Server Endpoint</th>
                                            <th class="text-right">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($dns_data as $id => $item): 
                                            $url = is_array($item) ? ($item['url'] ?? '') : $item;
                                        ?>
                                        <tr>
                                            <td class="align-middle text-muted"><?php echo ($id + 1); ?></td>
                                            <td class="align-middle url-text"><?php echo htmlspecialchars($url); ?></td>
                                            <td class="text-right">
                                                <button class="btn btn-dark btn-sm text-info mr-2" onclick="editEntry('<?php echo $id; ?>', '<?php echo addslashes($url); ?>')">
                                                    <i class="fa fa-edit"></i>
                                                </button>
                                                <a href="index.php?delete=<?php echo $id; ?>" class="btn btn-dark btn-sm text-danger" onclick="return confirm('Remove DNS?')">
                                                    <i class="fa fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

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

    <div class="modal fade" id="brandingModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content bg-dark border-secondary">
                <div class="modal-header border-secondary"><h5>App Assets</h5></div>
                <div class="modal-body">
                    <form method="POST" enctype="multipart/form-data">
                        <label class="small text-muted">Upload Logo (.png)</label>
                        <input type="hidden" name="upload_type" value="logo">
                        <input type="file" name="image_file" class="form-control mb-3" required>
                        <button class="btn btn-primary btn-sm w-100 mb-4">Update Logo</button>
                    </form>
                    <form method="POST" enctype="multipart/form-data">
                        <label class="small text-muted">Upload Background (.jpg)</label>
                        <input type="hidden" name="upload_type" value="bg">
                        <input type="file" name="image_file" class="form-control mb-3" required>
                        <button class="btn btn-primary btn-sm w-100">Update Background</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="settingsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content bg-dark border-secondary">
                <form method="POST">
                    <div class="modal-header border-secondary"><h5>Panel Access</h5></div>
                    <div class="modal-body">
                        <input type="text" name="new_user" class="form-control mb-3" value="<?php echo htmlspecialchars($config['user']); ?>">
                        <input type="text" name="new_pass" class="form-control" value="<?php echo htmlspecialchars($config['pass']); ?>">
                    </div>
                    <div class="modal-footer border-secondary">
                        <button name="update_creds" class="btn btn-primary btn-block">Update Credentials</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r121/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vanta@latest/dist/vanta.net.min.js"></script>
    <script>
        VANTA.NET({
            el: "#net-canvas",
            mouseControls: true, touchControls: true,
            minHeight: 200.00, minWidth: 200.00,
            scale: 1.00, scaleMobile: 1.00,
            color: 0x007bff, backgroundColor: 0x0b0e14,
            points: 10.00, maxDistance: 20.00, spacing: 18.00
        });

        $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); });

        function editEntry(id, url) {
            $("#edit_id").val(id);
            $("#dns_url").val(url);
            $("#form-title").text("Edit DNS Entry");
            $("#save-btn").text("Update DNS").removeClass("btn-primary").addClass("btn-info");
            window.scrollTo({top: 0, behavior: 'smooth'});
        }
    </script>
</body>
</html>