<?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 or User" />
            </div>
        </div>
        <div class="card-toolbar">
            <div class="d-flex justify-content-end">
                <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="min-w-50px">ID</th>
                    <th class="min-w-70px">DNS</th>
                    <th class="min-w-125px">MAC Address</th>
                    <th class="min-w-150px">Credentials / M3U</th>
                    <th class="min-w-70px">PIN</th>
                    <th class="min-w-125px text-end">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">Select DNS</label>
                    <select class="form-select fw-bold" id="dns_id" 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 mac-mask" id="mac_address" placeholder="00:00:00:00:00:00" required>
                </div>
                
                <div class="separator separator-dashed my-5"></div>
                
                <div class="mb-7">
                    <label for="m3u" class="fs-6 fw-semibold mb-2 text-primary">M3U8 URL (Extrator Automático)</label>
                    <textarea class="form-control" id="m3u" rows="2" placeholder="Cole o link M3U aqui para extrair usuário e senha..."></textarea>
                </div>

                <div class="row g-9 mb-7">
                    <div class="col-md-6 fv-row">
                        <label for="username" class="fs-6 fw-semibold mb-2">Username</label>
                        <input type="text" class="form-control" id="username" placeholder="Usuário extraído">
                    </div>
                    <div class="col-md-6 fv-row">
                        <label for="password" class="fs-6 fw-semibold mb-2">Password</label>
                        <input type="text" class="form-control" id="password" placeholder="Senha extraída">
                    </div>
                </div>

                <div class="mb-7">
                    <label for="pin" class="fs-6 fw-semibold mb-2">PIN</label>
                    <input type="text" class="form-control text-center fw-bold" id="pin" value="0000" maxlength="4">
                </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 Playlist</button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php'; ?>

<script>
let playlistTable;

// --- LÓGICA DO EXTRATOR (SÓ ISSO QUE ADICIONEI) ---
document.getElementById("m3u").addEventListener("input", function() {
    let urlString = this.value.trim();
    if(!urlString) return;

    try {
        let url = new URL(urlString);
        let user = url.searchParams.get("username") || url.searchParams.get("user");
        let pass = url.searchParams.get("password") || url.searchParams.get("pass");

        if (user) document.getElementById("username").value = user;
        if (pass) document.getElementById("password").value = pass;
        
        // Se for link direto tipo /live/user/pass/
        if (!user || !pass) {
            let parts = url.pathname.split('/');
            if (parts.length >= 4) {
                document.getElementById("username").value = parts[2];
                document.getElementById("password").value = parts[3];
            }
        }
    } catch (e) {
        // Caso não seja uma URL válida, não faz nada
    }
});
// ------------------------------------------------

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>${record.id}</td>
                            <td><span class="badge badge-light-dark">${record.dns_id}</span></td>
                            <td class="fw-bold">${record.mac_address}</td>
                            <td>
                                <div class="text-gray-800 fw-bold">${record.username}</div>
                                <div class="text-muted fs-7">${record.password}</div>
                            </td>
                            <td><span class="badge badge-secondary">${record.pin}</span></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}', '${record.m3u || ""}')">
                                    <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>
                    `;
                });

                if (playlistTable) { playlistTable.destroy(); }
                playlistTable = $('#playlist_table').DataTable({ "info": false, "order": [[0, "desc"]] });
            }
        });
}

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>`;
                });
            }
        });
}

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

function editPlaylist(id, dns_id, mac, user, pass, pin, m3u) {
    document.getElementById("modal_title").textContent = "Edit Playlist";
    document.getElementById("playlist_id").value = id;
    document.getElementById("mac_address").value = mac;
    document.getElementById("username").value = user;
    document.getElementById("password").value = pass;
    document.getElementById("m3u").value = m3u;
    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;
    const mac_address = document.getElementById("mac_address").value.trim().toUpperCase();
    const username = document.getElementById("username").value.trim();
    const password = document.getElementById("password").value.trim();
    const m3u = document.getElementById("m3u").value.trim();
    const pin = document.getElementById("pin").value.trim();

    if (!dns_id || !mac_address || !username || !password) {
        Swal.fire("Error", "DNS, MAC, User and Pass are required!", "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, m3u }),
    })
        .then((response) => response.json())
        .then((data) => {
            if (data.success) {
                Swal.fire("Success", data.message, "success");
                bootstrap.Modal.getInstance(document.getElementById("playlist_modal")).hide();
                loadPlaylistTable();
            } else {
                Swal.fire("Error", data.message, "error");
            }
        });
}

function deletePlaylist(id) {
    Swal.fire({
        title: "Are you sure?",
        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();
                });
        }
    });
}

// Máscara de MAC automática
document.getElementById('mac_address').addEventListener('input', function (e) {
    let v = e.target.value.toUpperCase().replace(/[^0-9A-F]/g, "").slice(0, 12);
    let parts = v.match(/.{1,2}/g);
    e.target.value = parts ? parts.join(":") : v;
});

document.addEventListener("DOMContentLoaded", loadPlaylistTable);
</script>