<?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="Buscar MAC, Usuário ou Senha" />
            </div>
        </div>
        <div class="card-toolbar">
            <div class="d-flex justify-content-end gap-2">
                <button type="button" class="btn btn-light-warning" onclick="deleteSelectedPlaylists()">Delete Selected</button>
                <button type="button" class="btn btn-light-danger" onclick="deleteAllPlaylists()">Delete All</button>
                <button type="button" class="btn btn-primary" onclick="openAddModal()">
                    <i class="ki-outline ki-plus fs-2"></i>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>ID</th>
                    <th>DNS ID</th>
                    <th>MAC Address</th>
                    <th>Username</th>
                    <th>Password</th>
                    <th>PIN</th>
                    <th class="text-end min-w-100px">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-10">
                    <label class="fs-6 fw-bold mb-2 text-success">Colar Link M3U8 para Extrair Dados</label>
                    <input type="text" class="form-control form-control-solid border-success" id="m3u8_extractor" placeholder="Cole o link .m3u8 aqui...">
                </div>

                <div class="mb-7">
                    <label class="fs-6 fw-semibold mb-2">DNS ID</label>
                    <select class="form-select fw-bold" id="dns_id">
                        <option value="">Select DNS</option>
                    </select>
                </div>
                <div class="mb-7">
                    <label class="fs-6 fw-semibold mb-2">MAC Address</label>
                    <input type="text" class="form-control" id="mac_address" placeholder="00:00:00:00:00:00" maxlength="17">
                </div>
                <div class="mb-7">
                    <label class="fs-6 fw-semibold mb-2">Username</label>
                    <input type="text" class="form-control" id="username">
                </div>
                <div class="mb-7">
                    <label class="fs-6 fw-semibold mb-2">Password</label>
                    <input type="text" class="form-control" id="password">
                </div>
                <div class="mb-7">
                    <label class="fs-6 fw-semibold mb-2">PIN</label>
                    <input type="text" class="form-control" id="pin" value="0000">
                </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" id="btn_save_playlist" onclick="savePlaylist()">
                    <span class="indicator-label">Save</span>
                    <span class="indicator-progress">Please wait... <span class="spinner-border spinner-border-sm align-middle ms-2"></span></span>
                </button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php'; ?>

<script>
let playlistTable;

// Formatar MAC Address automaticamente
document.getElementById('mac_address').addEventListener('input', function (e) {
    let value = e.target.value.toUpperCase().replace(/[^0-9A-F]/g, '');
    let formatted = "";
    for (let i = 0; i < value.length && i < 12; i++) {
        formatted += value[i];
        if ((i + 1) % 2 === 0 && i < 10 && i !== value.length - 1) {
            formatted += ":";
        }
    }
    e.target.value = formatted;
});

// Carregamento da Tabela
function loadPlaylistTable() {
    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 tableBody = document.getElementById("playlist_table_body");
            tableBody.innerHTML = data.data.map(record => `
                <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><span class="badge badge-light-primary fw-bold">${record.mac_address}</span></td>
                    <td>${record.username}</td>
                    <td>${record.password}</td>
                    <td>${record.pin}</td>
                    <td class="text-end">
                        <button class="btn btn-icon btn-bg-light btn-active-color-primary btn-sm me-1" onclick="editPlaylist(${record.id}, ${record.dns_id}, '${record.mac_address}', '${record.username}', '${record.password}', '${record.pin}')">
                            <i class="ki-outline ki-pencil fs-3"></i>
                        </button>
                        <button class="btn btn-icon btn-bg-light btn-active-color-danger btn-sm" onclick="deletePlaylist(${record.id})">
                            <i class="ki-outline ki-trash fs-3"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            if ($.fn.DataTable.isDataTable('#playlist_table')) {
                $('#playlist_table').DataTable().destroy();
            }
            
            // Correção da busca: Garantindo que smart search e busca global estejam ativos
            playlistTable = $('#playlist_table').DataTable({
                info: false,
                order: [[1, 'desc']],
                pageLength: 10,
                search: {
                    smart: true
                },
                columnDefs: [
                    { orderable: false, targets: [0, 7] },
                    { searchable: true, targets: [1, 2, 3, 4, 5] } // Garante que campos chave sejam buscáveis
                ]
            });
        }
    });
}

// Busca em Tempo Real (Corrigida)
document.getElementById("search_playlist").addEventListener("input", function() {
    if (playlistTable) {
        playlistTable.search(this.value.trim()).draw();
    }
});

// Delete TODOS
function deleteAllPlaylists() {
    const allRows = document.querySelectorAll('.row-checkbox');
    if (allRows.length === 0) return Swal.fire("Aviso", "Nenhum registro para deletar.", "info");

    Swal.fire({
        title: "Deletar TODOS os registros?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, apagar tudo!"
    }).then((result) => {
        if (result.isConfirmed) {
            allRows.forEach(cb => {
                const id = cb.value;
                fetch("actions/mac_actions.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ action: "delete", id }),
                }).then(() => {
                    playlistTable.row($(`#row_${id}`)).remove().draw(false);
                });
            });
            toastr.warning("Registros removidos.");
        }
    });
}

// Delete Individual
function deletePlaylist(id) {
    Swal.fire({
        title: "Tem certeza?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, deletar!"
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("actions/mac_actions.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "delete", id }),
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    playlistTable.row($(`#row_${id}`)).remove().draw(false);
                    toastr.success("Deletado!");
                }
            });
        }
    });
}

// Salvar
function savePlaylist() {
    const btn = document.getElementById('btn_save_playlist');
    const id = document.getElementById("playlist_id").value;
    const payload = {
        action: id ? "edit" : "add",
        id: id,
        dns_id: document.getElementById("dns_id").value,
        mac_address: document.getElementById("mac_address").value.trim(),
        username: document.getElementById("username").value.trim(),
        password: document.getElementById("password").value.trim(),
        pin: document.getElementById("pin").value.trim()
    };

    btn.setAttribute('data-kt-indicator', 'on');
    btn.disabled = true;

    fetch("actions/mac_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
    })
    .then(res => res.json())
    .then(data => {
        btn.removeAttribute('data-kt-indicator');
        btn.disabled = false;
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById("playlist_modal")).hide();
            loadPlaylistTable();
            toastr.success("Salvo!");
        }
    });
}

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

document.addEventListener("DOMContentLoaded", () => {
    loadPlaylistTable();
    loadDnsOptions();
});

// Extrator M3U8
document.getElementById('m3u8_extractor')?.addEventListener('input', function(e) {
    const val = e.target.value;
    try {
        if (val.includes('username=') && val.includes('password=')) {
            const url = new URL(val);
            document.getElementById('username').value = url.searchParams.get('username') || "";
            document.getElementById('password').value = url.searchParams.get('password') || "";
            if(url.searchParams.get('mac')) {
                document.getElementById('mac_address').value = url.searchParams.get('mac').toUpperCase();
                document.getElementById('mac_address').dispatchEvent(new Event('input'));
            }
            toastr.success("Dados extraídos!");
        }
    } catch(err) {}
});

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

function openAddModal() {
    document.getElementById("playlist_id").value = "";
    document.getElementById("username").value = "";
    document.getElementById("password").value = "";
    document.getElementById("mac_address").value = "";
    document.getElementById('pin').value = "0000";
    document.getElementById("modal_title").textContent = "Add Playlist";
    new bootstrap.Modal(document.getElementById("playlist_modal")).show();
}

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