<?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 Playlist" />
            </div>
        </div>
        <div class="card-toolbar">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn btn-warning me-3" onclick="deleteSelectedPlaylists()">Delete Selected</button>
                <button type="button" class="btn btn-danger me-3" onclick="deleteAllPlaylists()">Delete All</button>
                <button type="button" class="btn btn-primary" onclick="openAddModal()">Add Playlist</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="w-10px pe-2">
                        <div class="form-check form-check-sm form-check-custom form-check-solid">
                            <input class="form-check-input" type="checkbox" id="checkAll" onclick="toggleAllCheckboxes(this)" />
                        </div>
                    </th>
                    <th class="min-w-125px">ID</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-125px">PIN</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 Playlist</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="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" 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>
                    <input type="password" class="form-control" id="password" placeholder="Enter Password" required>
                </div>
                <div class="mb-7">
                    <label for="pin" class="fs-6 fw-semibold mb-2">PIN</label>
                    <input type="text" class="form-control" id="pin" placeholder="Enter PIN" required>
                </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) => {
                    tableBody.innerHTML += `
                        <tr id="row_${record.id}">
                            <td>
                                <div class="form-check form-check-sm form-check-custom form-check-solid">
                                    <input class="form-check-input row-checkbox" type="checkbox" value="${record.id}" />
                                </div>
                            </td>
                            <td>${record.id}</td>
                            <td>${record.dns_id}</td>
                            <td>${record.mac_address}</td>
                            <td>${record.username}</td>
                            <td>${record.password}</td>
                            <td>${record.pin}</td>
                            <td class="">
                                <button class="btn btn-sm btn-warning" onclick="editPlaylist(${record.id}, ${record.dns_id}, '${record.mac_address}', '${record.username}', '${record.password}', '${record.pin}')">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({
                    columnDefs: [{ orderable: false, targets: 0 }] // Remove a ordenação da coluna do checkbox
                });

                // Resetar o checkbox "checkAll" se estivesse marcado
                const checkAll = document.getElementById('checkAll');
                if(checkAll) checkAll.checked = false;
            }
        })
        .catch((error) => console.error("Error loading playlist table:", error));
}

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 Playlist";
    document.getElementById("playlist_id").value = "";
    document.getElementById("dns_id").value = "";
    document.getElementById("mac_address").value = "";
    document.getElementById("username").value = "";
    document.getElementById("password").value = "";
    document.getElementById("pin").value = "";
    loadDnsOptions();
    new bootstrap.Modal(document.getElementById("playlist_modal")).show();
}

function editPlaylist(id, dns_id, mac_address, username, password, pin) {
    document.getElementById("modal_title").textContent = "Edit Playlist";
    document.getElementById("playlist_id").value = id;
    document.getElementById("mac_address").value = mac_address;
    document.getElementById("username").value = username;
    document.getElementById("password").value = password;
    document.getElementById("pin").value = pin;
    loadDnsOptions(dns_id);
    new bootstrap.Modal(document.getElementById("playlist_modal")).show();
}

function savePlaylist() {
    const id = document.getElementById("playlist_id").value;
    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 pin = document.getElementById("pin").value.trim();

    if (!dns_id || !mac_address || !username || !password || !pin) {
        Swal.fire("Error", "All fields are required!", "error");
        return;
    }

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

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

    fetch("actions/mac_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action, id, dns_id, mac_address, username, password, pin }),
    })
        .then((response) => response.json())
        .then((data) => {
            Swal.fire(data.success ? "Success" : "Error", data.message, data.success ? "success" : "error");
            const modal = bootstrap.Modal.getInstance(document.getElementById("playlist_modal"));
            modal.hide();

            if (data.success) {
                if (id) {
                    const row = playlistTable.row(function(idx, data, node) {
                        return data[1] == id; // Mudou para data[1] por causa da coluna do checkbox
                    });

                    if (row.node()) {
                        row.data([
                            `<div class="form-check form-check-sm form-check-custom form-check-solid"><input class="form-check-input row-checkbox" type="checkbox" value="${id}" /></div>`,
                            id,
                            dns_id,
                            mac_address,
                            username,
                            password,
                            pin,
                            `
                            <button class="btn btn-sm btn-warning" onclick="editPlaylist(${id}, ${dns_id}, '${mac_address}', '${username}', '${password}', '${pin}')">Edit</button>
                            <button class="btn btn-sm btn-danger" onclick="deletePlaylist(${id})">Delete</button>
                            `
                        ]).draw(false);
                    } else {
                        console.error(`Row with ID ${id} not found.`);
                    }
                } else {
                    playlistTable.row.add([
                        `<div class="form-check form-check-sm form-check-custom form-check-solid"><input class="form-check-input row-checkbox" type="checkbox" value="${data.new_id}" /></div>`,
                        data.new_id,
                        dns_id,
                        mac_address,
                        username,
                        password,
                        pin,
                        `
                        <button class="btn btn-sm btn-warning" onclick="editPlaylist(${data.new_id}, ${dns_id}, '${mac_address}', '${username}', '${password}', '${pin}')">Edit</button>
                        <button class="btn btn-sm btn-danger" onclick="deletePlaylist(${data.new_id})">Delete</button>
                        `
                    ]).draw(false);
                }
            }
        })
        .catch((error) => console.error("Error saving playlist:", 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");
                    playlistTable.row(`#row_${id}`).remove().draw(false);
                })
                .catch((error) => console.error("Error deleting playlist:", error));
        }
    });
}

function toggleAllCheckboxes(source) {
    const checkboxes = document.querySelectorAll('.row-checkbox');
    checkboxes.forEach(cb => cb.checked = source.checked);
}

function deleteSelectedPlaylists() {
    const selectedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
    
    if (selectedCheckboxes.length === 0) {
        Swal.fire("Info", "Please select at least one record to delete.", "info");
        return;
    }

    const idsToDelete = Array.from(selectedCheckboxes).map(cb => cb.value);

    Swal.fire({
        title: "Delete Selected?",
        text: `Are you sure you want to delete ${idsToDelete.length} record(s)?`,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#f1416c",
        confirmButtonText: "Yes, delete selected!",
        cancelButtonText: "Cancel"
    }).then((result) => {
        if (result.isConfirmed) {
            const deletePromises = idsToDelete.map(id => {
                return fetch("actions/mac_actions.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ action: "delete", id: id }),
                }).then(res => res.json());
            });

            Promise.all(deletePromises)
            .then(() => {
                Swal.fire("Deleted!", "Selected records have been successfully removed.", "success").then(() => {
                    loadPlaylistTable();
                });
            })
            .catch(() => {
                Swal.fire("Error", "An error occurred while deleting some records.", "error");
            });
        }
    });
}

function deleteAllPlaylists() {
    Swal.fire({
        title: "Delete ALL records?",
        text: "This action will delete all playlists. It cannot be undone!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#d33",
        confirmButtonText: "Yes, delete everything!",
        cancelButtonText: "Cancel"
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("actions/mac_actions.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "view" }),
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    const recordsToDelete = data.data;
                    
                    if (recordsToDelete.length === 0) {
                        Swal.fire("Info", "There are no records to delete.", "info");
                        return;
                    }

                    const deletePromises = recordsToDelete.map(record => {
                        return fetch("actions/mac_actions.php", {
                            method: "POST",
                            headers: { "Content-Type": "application/json" },
                            body: JSON.stringify({ action: "delete", id: record.id }),
                        }).then(res => res.json());
                    });

                    Promise.all(deletePromises)
                    .then(() => {
                        Swal.fire("Deleted!", "All records have been successfully removed.", "success").then(() => {
                            loadPlaylistTable();
                        });
                    })
                    .catch(() => {
                        Swal.fire("Error", "An error occurred while deleting some records.", "error");
                    });
                } else {
                    Swal.fire("Error", "Failed to fetch the list of playlists to delete.", "error");
                }
            });
        }
    });
}

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

document.addEventListener("DOMContentLoaded", loadPlaylistTable);

</script>