<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = "MAC Users";

$page_content = '
<div class="card">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <div class="d-flex align-items-center position-relative my-1">
                <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i>
                <input type="text" id="search_playlist" class="form-control form-control-solid w-250px ps-12" placeholder="Search MAC Users..." />
            </div>
        </div>
        <div class="card-toolbar">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn btn-primary" onclick="openAddModal()">Add MAC User</button>
            </div>
        </div>
    </div>
    <div class="card-body pt-0">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="playlist_table">
            <thead>
                <tr class="text-start text-gray-500 fw-bold fs-7 text-uppercase gs-0">
                    <th class="min-w-125px">ID</th>
                    <th class="min-w-150px">Cliente</th>
                    <th class="min-w-125px">DNS ID</th>
                    <th class="min-w-125px">MAC Address</th>
                    <th class="min-w-125px">Username</th>
                    <th class="min-w-125px">Password</th>
                    <th class="min-w-200px">Link</th>
                    <th class="min-w-125px">Actions</th>
                </tr>
            </thead>
            <tbody id="playlist_table_body" class="fw-semibold text-gray-600"></tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="playlist_modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-650px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal_title" class="fw-bold">Add MAC User</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="playlist_id">
                <div class="mb-7">
                    <label for="cliente" class="fs-6 fw-semibold mb-2">Cliente</label>
                    <input type="text" class="form-control" id="cliente" placeholder="Enter Cliente Name" required>
                </div>
                <div class="mb-7">
                    <label for="dns_id" class="fs-6 fw-semibold mb-2">DNS ID</label>
                    <select class="form-select fw-bold" id="dns_id" data-control="select2" data-placeholder="Select a DNS..." required>
                        <option value="">Select DNS</option>
                    </select>
                </div>
                <div class="mb-7">
                    <label for="mac_address" class="fs-6 fw-semibold mb-2">MAC Address</label>
                    <input type="text" class="form-control" id="mac_address" placeholder="Enter MAC Address (XX:XX:XX:XX:XX:XX)" required>
                </div>
                <div class="mb-7">
                    <label for="username" class="fs-6 fw-semibold mb-2">Username</label>
                    <input type="text" class="form-control" id="username" placeholder="Enter Username" required>
                </div>
                <div class="mb-7">
                    <label for="password" class="fs-6 fw-semibold mb-2">Password</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="password" placeholder="Enter Password" required>
                        <button class="btn btn-icon btn-secondary" type="button" onclick="togglePasswordVisibility()" title="Toggle password visibility">
                            <i class="ki-outline ki-eye fs-2"></i>
                        </button>
                    </div>
                    <small class="text-muted">Password is visible for editing purposes</small>
                </div>
                <div class="mb-7">
                    <label for="link" class="fs-6 fw-semibold mb-2">Link (Optional)</label>
                    <input type="url" class="form-control" id="link" placeholder="Enter Link URL (https://...) - Optional">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="savePlaylist()">Save</button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php'; ?>

<script>
let playlistTable;

function loadPlaylistTable() {
    fetch("actions/mac_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "view" }),
    })
        .then((response) => response.json())
        .then((data) => {
            if (data.success) {
                const tableBody = document.getElementById("playlist_table_body");
                tableBody.innerHTML = "";

                data.data.forEach((record) => {
                    // Escape special characters for JavaScript strings
                    const escapedCliente = record.cliente ? record.cliente.replace(/'/g, "\\'") : '';
                    const escapedMac = record.mac_address.replace(/'/g, "\\'");
                    const escapedUsername = record.username.replace(/'/g, "\\'");
                    const escapedPassword = record.password.replace(/'/g, "\\'");
                    const escapedLink = record.link ? record.link.replace(/'/g, "\\'") : '';
                    
                    // Format link display
                    let linkDisplay = '';
                    if (record.link && record.link.trim() !== '') {
                        linkDisplay = `<a href="${record.link}" target="_blank" class="text-primary" title="${record.link}">${truncateUrl(record.link)}</a>`;
                    } else {
                        linkDisplay = '<span class="text-muted">No link</span>';
                    }
                    
                    tableBody.innerHTML += `
                        <tr id="row_${record.id}">
                            <td>${record.id}</td>
                            <td>${record.cliente || ''}</td>
                            <td>${record.dns_id}</td>
                            <td>${record.mac_address}</td>
                            <td>${record.username}</td>
                            <td>${record.password}</td>
                            <td>${linkDisplay}</td>
                            <td class="">
                                <button class="btn btn-sm btn-warning" onclick="editPlaylist(${record.id}, '${escapedCliente}', ${record.dns_id}, '${escapedMac}', '${escapedUsername}', '${escapedPassword}', '${escapedLink}')">Edit</button>
                                <button class="btn btn-sm btn-danger" onclick="deletePlaylist(${record.id})">Delete</button>
                            </td>
                        </tr>
                    `;
                });

                if (playlistTable) {
                    playlistTable.destroy();
                }

                playlistTable = $('#playlist_table').DataTable({
                    "pageLength": 10,
                    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                    "order": [[0, "desc"]]
                });
            }
        })
        .catch((error) => console.error("Error loading playlist table:", error));
}

// Helper function to truncate long URLs
function truncateUrl(url, maxLength = 50) {
    if (!url || url.length <= maxLength) return url;
    return url.substring(0, maxLength) + '...';
}

// Function to toggle password visibility
function togglePasswordVisibility() {
    const passwordField = document.getElementById("password");
    const icon = event.currentTarget.querySelector('i');
    
    if (passwordField.type === "password") {
        passwordField.type = "text";
        icon.classList.remove('ki-eye');
        icon.classList.add('ki-eye-slash');
    } else {
        passwordField.type = "password";
        icon.classList.remove('ki-eye-slash');
        icon.classList.add('ki-eye');
    }
}

document.getElementById("search_playlist").addEventListener("input", function () {
    if (playlistTable) {
        playlistTable.search(this.value).draw();
    }
});

function loadDnsOptions(selectedValue = "") {
    fetch("actions/mac_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "get_dns_options" }),
    })
        .then((response) => response.json())
        .then((data) => {
            if (data.success) {
                const dnsDropdown = document.getElementById("dns_id");
                dnsDropdown.innerHTML = '<option value="">Select DNS</option>';
                data.data.forEach((dns) => {
                    const selected = dns.id == selectedValue ? "selected" : "";
                    dnsDropdown.innerHTML += `<option value="${dns.id}" ${selected}>${dns.title}</option>`;
                });
            }
        })
        .catch((error) => console.error("Error loading DNS options:", error));
}

function openAddModal() {
    document.getElementById("modal_title").textContent = "Add MAC User";
    document.getElementById("playlist_id").value = "";
    document.getElementById("cliente").value = "";
    document.getElementById("dns_id").value = "";
    document.getElementById("mac_address").value = "";
    document.getElementById("username").value = "";
    document.getElementById("password").value = "";
    document.getElementById("link").value = "";
    
    // Reset password field to text mode for new entries
    const passwordField = document.getElementById("password");
    passwordField.type = "text";
    
    loadDnsOptions();
    new bootstrap.Modal(document.getElementById("playlist_modal")).show();
}

function editPlaylist(id, cliente, dns_id, mac_address, username, password, link) {
    document.getElementById("modal_title").textContent = "Edit MAC User";
    document.getElementById("playlist_id").value = id;
    document.getElementById("cliente").value = cliente;
    document.getElementById("mac_address").value = mac_address;
    document.getElementById("username").value = username;
    document.getElementById("password").value = password;
    document.getElementById("link").value = link;
    
    // Ensure password field is set to text to show the actual password
    const passwordField = document.getElementById("password");
    passwordField.type = "text";
    
    loadDnsOptions(dns_id);
    new bootstrap.Modal(document.getElementById("playlist_modal")).show();
}

function savePlaylist() {
    const id = document.getElementById("playlist_id").value;
    const cliente = document.getElementById("cliente").value.trim();
    const dns_id = document.getElementById("dns_id").value.trim();
    const mac_address = document.getElementById("mac_address").value.trim();
    const username = document.getElementById("username").value.trim();
    const password = document.getElementById("password").value.trim();
    const link = document.getElementById("link").value.trim();

    // Validar campos obrigatórios (link não é mais obrigatório)
    if (!cliente || !dns_id || !mac_address || !username || !password) {
        Swal.fire("Error", "Cliente, DNS ID, MAC Address, Username and Password are required!", "error");
        return;
    }

    if (!validateMACAddress(mac_address)) {
        Swal.fire("Error", "Invalid MAC Address! Use format XX:XX:XX:XX:XX:XX", "error");
        return;
    }

    // Validar URL apenas se foi preenchida
    if (link && link !== '' && !isValidURL(link)) {
        Swal.fire("Error", "Invalid URL format! Please enter a valid URL (e.g., https://example.com)", "error");
        return;
    }

    const action = id ? "edit" : "add";

    fetch("actions/mac_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action, id, cliente, dns_id, mac_address, username, password, link }),
    })
        .then((response) => response.json())
        .then((data) => {
            Swal.fire(data.success ? "Success" : "Error", data.message, data.success ? "success" : "error");
            
            if (data.success) {
                const modal = bootstrap.Modal.getInstance(document.getElementById("playlist_modal"));
                modal.hide();
                loadPlaylistTable(); // Recarregar a tabela inteira para garantir consistência
            }
        })
        .catch((error) => {
            console.error("Error saving playlist:", error);
            Swal.fire("Error", "An error occurred while saving", "error");
        });
}

function deletePlaylist(id) {
    Swal.fire({
        title: "Are you sure?",
        text: "This will delete the playlist entry!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, delete it!",
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("actions/mac_actions.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "delete", id }),
            })
                .then((response) => response.json())
                .then((data) => {
                    Swal.fire("Deleted!", data.message, "success");
                    loadPlaylistTable(); // Recarregar a tabela
                })
                .catch((error) => console.error("Error deleting playlist:", error));
        }
    });
}

function validateMACAddress(mac) {
    const regex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
    return regex.test(mac);
}

function isValidURL(url) {
    try {
        new URL(url);
        return true;
    } catch {
        return false;
    }
}

document.addEventListener("DOMContentLoaded", loadPlaylistTable);

</script>