<?php
error_reporting(0);
ini_set('display_errors', 0);
/*
 * 🎵 @ Playlist Manager 
 * 🚀 @ Version: 1.0.0
 * 📅 @ Last Updated: [Data Atual]
 */

include "includes/header.php";
$table_name = "playlist";
$res = $db->select($table_name, "*", "");

// ==============================================
// FUNÇÕES PARA MANIPULAÇÃO DE MENSAGENS
// ==============================================

function getDeviceKeyMessage($mac) {
    global $db;
    $result = $db->select("device_keys", "device_key", "mac_address = :mac_address", "", [":mac_address" => $mac]);
    return $result[0]['device_key'] ?? '';
}

function saveDeviceKeyMessage($mac, $message) {
    global $db;
    
    $existingKey = $db->select("device_keys", "id", "mac_address = :mac_address", "", [":mac_address" => $mac]);
    
    if (!empty($existingKey)) {
        $result = $db->update('device_keys', [
            'device_key' => $message,
            'updated_at' => date('Y-m-d H:i:s')
        ], "mac_address = :mac_address", [":mac_address" => $mac]);
    } else {
        $result = $db->insert('device_keys', [
            'mac_address' => $mac,
            'device_key' => $message,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
    }
    
    return $result;
}

// ==============================================
// PROCESSAMENTO DO FORMULÁRIO DE MENSAGEM
// ==============================================

if (isset($_POST['save_message'])) {
    $mac = $_POST['mac'] ?? '';
    $message = $_POST['message'] ?? '';
    
    if (!empty($mac)) {
        if (saveDeviceKeyMessage($mac, $message)) {
            echo "<script>showNotification('✅ Mensagem salva com sucesso!', 'success');</script>";
        } else {
            echo "<script>showNotification('❌ Erro ao salvar mensagem!', 'error');</script>";
        }
    }
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "'</script>";
    exit;
}

// ==============================================
// CRUD DE USUÁRIOS (PLAYLISTS)
// ==============================================

// Adiciona novo usuário
if (isset($_POST["submit"])) {
    unset($_POST["submit"]);

    if (isset($_POST['type']) && $_POST['type'] === 'm3u') {
        $url = $_POST['url'];

        if (strpos($url, '/get.php') !== false) {
            $dnsUrl = substr($url, 0, strpos($url, '/get.php'));
            $dnsUrl = rtrim($dnsUrl);
        } else {
            $dnsUrl = '';
        }

        parse_str(parse_url($url, PHP_URL_QUERY), $queryParams);
        $username = isset($queryParams['username']) ? $queryParams['username'] : '';
        $password = isset($queryParams['password']) ? $queryParams['password'] : '';

        $dns_id = generateNewDnsId();

        $_POST['username'] = $username;
        $_POST['password'] = $password;
        $_POST['dns_id'] = $dns_id;

        $dnsData = [
            'id' => $dns_id,
            'title' => 'new',
            'url' => $dnsUrl
        ];

        if ($db->insert('dns', $dnsData)) {
            echo "<script>showNotification('🎉 DNS adicionado com sucesso!', 'success');</script>";
        } else {
            echo "<script>showNotification('❌ Erro ao adicionar DNS!', 'error');</script>";
        }
    }

    $db->insert($table_name, $_POST);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=1'</script>";
}

function generateNewDnsId() {
    global $db;
    $result = $db->select('dns', 'MAX(id) as max_id');
    return ($result[0]['max_id'] ?? 0) + 1;
}

// Atualiza usuário
if (isset($_GET["update"])) {
    $resU = $db->select($table_name, "*", "id = :id", "", [":id" => $_GET["update"]]);
    if ($resU) {
        $userData = $resU[0];
    }
}

if (isset($_POST["submitU"])) {
    unset($_POST["submitU"]);
    $updateData = $_POST;
    $db->update($table_name, $updateData, "id = :id", [":id" => $_GET["update"]]);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=1'</script>";
}

// Deleta usuário
if (isset($_GET["delete"])) {
    $db->delete($table_name, "id = :id", [":id" => $_GET["delete"]]);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=2'</script>";
}

// ==============================================
// INTERFACE DO USUÁRIO
// ==============================================

if (isset($_GET["create"]) || isset($_GET["update"])) {
    $action = isset($_GET["update"]) ? '✏️ Editar Usuário' : '➕ Adicionar Usuário';
    echo '<div class="col-12 col-md-8 mx-auto">
            <div class="card-body">
                <div class="card bg-primary text-white">
                    <div class="card-header card-header-warning text-center">
                        <h2><i class="fa fa-music"></i> ' . $action . '</h2>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <div class="form-group">
                                <label class="form-label" for="type">🔘 Selecionar Tipo</label>
                                <select class="form-control" id="type" name="type" onchange="toggleFields()">
                                    <option value="" selected>🔽 Selecionar uma opção</option>
                                    <option value="dns"' . (isset($userData) && $userData["type"] == "dns" ? ' selected' : '') . '>🌐 Selecionar DNS</option>
                                    <option value="m3u"' . (isset($userData) && $userData["type"] == "m3u" ? ' selected' : '') . '>Selecionar M3U</option>
                                </select>
                            </div>';

    echo '<div id="dns-fields" style="display: ' . (isset($userData) && $userData["type"] == "dns" ? 'block' : 'none') . ';">
            <div class="form-group">
                <label class="form-label" for="dns_id">🌐 DNS</label>
                <select class="form-control" name="dns_id">';
    $dnss = $db->select("dns", "*", "title != :title", "", [":title" => "new"]);
    foreach ($dnss as $dns) {
        echo '<option value="' . $dns["id"] . '"' . (isset($userData) && $userData["dns_id"] == $dns["id"] ? ' selected' : '') . '>' . $dns["title"] . '</option>';
    }
    echo '      </select>
            </div>
        </div>';

    echo '<div id="m3u-fields" style="display: ' . (isset($userData) && $userData["type"] == "m3u" ? 'block' : 'none') . ';">
                <div class="form-group">
                    <label class="form-label" for="mac">📶 Endereço MAC</label>
                    <input class="form-control" id="mac" name="mac_address" placeholder="00:1A:2B:3C:4D:5E" type="text" value="' . (isset($userData) ? $userData["mac_address"] : '') . '"/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="url">🔗 URL M3U</label>
                    <input class="form-control" id="url" name="url" placeholder="https://exemplo.com/playlist.m3u" type="text" value="' . (isset($userData) ? $userData["url"] : '') . '"/>
                </div>
            </div>';

    echo '<div id="common-fields" style="display: none;">
                <div class="form-group">
                    <label class="form-label" for="mac">📶 Endereço MAC</label>
                    <input class="form-control" id="mac" name="mac_address" placeholder="00:1A:2B:3C:4D:5E" type="text" value="' . (isset($userData) ? $userData["mac_address"] : '') . '"/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="username">👤 Nome de Usuário</label>
                    <input class="form-control" id="username" name="username" placeholder="usuário123" type="text" value="' . (isset($userData) ? $userData["username"] : '') . '"/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="password">🔑 Senha</label>
                    <input class="form-control" id="password" name="password" placeholder="••••••••" type="text" value="' . (isset($userData) ? $userData["password"] : '') . '"/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="pin">🔒 PIN Parental</label>
                    <input class="form-control" id="pin" name="pin" placeholder="0000" type="text" value="' . (isset($userData) ? $userData["pin"] : '0000') . '"/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="link">🔗 Link</label>
                    <input class="form-control" id="link" name="link" placeholder="https://exemplo.com/link" type="text" value="' . (isset($userData) ? $userData["link"] : '') . '"/>
                </div>
            </div>';

    echo '<div class="form-group text-center mt-4">
                <button class="btn btn-success" name="' . (isset($_GET["update"]) ? 'submitU' : 'submit') . '" type="submit">
                    <i class="fa fa-save"></i> ' . (isset($_GET["update"]) ? '🔄 Atualizar' : '💾 Salvar') . '
                </button>
            </div>
        </form>
    </div>
    </div>
    </div>
    </div>';

    echo '<script>
    function toggleFields() {
        var type = document.getElementById("type").value;
        document.getElementById("common-fields").style.display = type ? "block" : "none"; 

        if (type === "dns") {
            document.getElementById("dns-fields").style.display = "block";
            document.getElementById("m3u-fields").style.display = "none";
            document.getElementById("mac").parentElement.style.display = "block";
            document.getElementById("username").parentElement.style.display = "block";
            document.getElementById("password").parentElement.style.display = "block";
            document.getElementById("pin").parentElement.style.display = "block";
        } else if (type === "m3u") {
            document.getElementById("dns-fields").style.display = "none";
            document.getElementById("m3u-fields").style.display = "block";
            document.getElementById("mac").parentElement.style.display = "none";
            document.getElementById("username").parentElement.style.display = "none";
            document.getElementById("password").parentElement.style.display = "none";
            document.getElementById("pin").parentElement.style.display = "none";
        } else {
            document.getElementById("dns-fields").style.display = "none";
            document.getElementById("m3u-fields").style.display = "none";
        }
    }

    document.addEventListener("DOMContentLoaded", function() {
        toggleFields();
    });
    </script>';

} else {
    echo '<div class="col-12 mx-auto">
        <div class="card-body">
            <div class="card bg-primary text-white">
                <div class="card-header card-header-warning text-center">
                    <h2><i class="fa fa-users"></i> Gerenciamento de Playlists</h2>
                </div>
                <div class="card-body text-center">
                    <a href="' . basename($_SERVER["SCRIPT_NAME"]) . '?create=1" class="btn btn-success" type="button">
                        <i class="fa fa-plus"></i> ➕ Novo Usuário
                    </a>
                    <div class="input-group mt-3 mb-3">
                        <span class="input-group-text">🔍</span>
                        <input type="text" id="search" class="form-control" placeholder="Buscar por MAC Address..." onkeyup="filterTable()">
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover table-striped" id="userTable">
                            <thead class="thead-dark">
                                <tr>
                                    <th>🌐 DNS</th>
                                    <th>📶 MAC Address</th>
                                    <th>👤 Username</th>
                                    <th>🔑 Password</th>
                                    <th>🔒 PIN</th>
                                    <th>🔗 Link</th>
                                    <th>💬 Mensagem</th>
                                    <th>⚙️ Ações</th>
                                </tr>
                            </thead>
                            <tbody>';

    foreach ($res as $row) {
        $hasMessage = !empty(getDeviceKeyMessage($row["mac_address"]));
        echo '<tr>
                <td>' . $row["dns_id"] . '</td>
                <td><code>' . $row["mac_address"] . '</code></td>
                <td>' . $row["username"] . '</td>
                <td><code>' . $row["password"] . '</code></td>
                <td>' . $row["pin"] . '</td>
                <td><a href="' . $row["link"] . '" target="_blank">🔗 Link</a></td>
                <td>
                    <button type="button" class="btn btn-sm ' . ($hasMessage ? 'btn-info' : 'btn-outline-secondary') . '" 
                        data-bs-toggle="modal" data-bs-target="#messageModal" 
                        onclick="prepareMessageModal(\'' . $row["mac_address"] . '\', \'' . htmlspecialchars(getDeviceKeyMessage($row["mac_address"]), ENT_QUOTES) . '\')">
                        <i class="fa fa-comment' . ($hasMessage ? '' : '-alt') . '"></i>
                    </button>
                </td>
                <td>
                    <a href="' . basename($_SERVER["SCRIPT_NAME"]) . '?update=' . $row["id"] . '" class="btn btn-warning btn-sm">
                        <i class="fa fa-edit"></i>
                    </a>
                    <a href="' . basename($_SERVER["SCRIPT_NAME"]) . '?delete=' . $row["id"] . '" class="btn btn-danger btn-sm" onclick="return confirm(\'⚠️ Tem certeza que deseja excluir este usuário?\')">
                        <i class="fa fa-trash"></i>
                    </a>
                </td>
            </tr>';
    }

    echo '        </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>';

    echo '
    <div class="modal fade" id="messageModal" tabindex="-1" aria-labelledby="messageModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="messageModalLabel">Editar Mensagem</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="mac" id="modalMac">
                        <div class="form-group mb-3">
                            <label for="modalMessage" class="form-label">Mensagem para <span id="deviceMac" class="fw-bold"></span>:</label>
                            <textarea class="form-control" id="modalMessage" name="message" rows="5" style="font-family: monospace;"></textarea>
                            <div class="d-flex justify-content-between mt-2">
                                <small class="text-muted">Máx. 500 caracteres</small>
                                <small id="charCount" class="text-muted">0/500</small>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="fa fa-times"></i> Fechar
                        </button>
                        <button type="submit" name="save_message" class="btn btn-primary">
                            <i class="fa fa-save"></i> Salvar
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>';

    echo '
    <script>
    function filterTable() {
        var input = document.getElementById("search");
        var filter = input.value.toLowerCase();
        var table = document.getElementById("userTable");
        var tr = table.getElementsByTagName("tr");

        for (var i = 1; i < tr.length; i++) {
            var td = tr[i].getElementsByTagName("td")[1];
            if (td) {
                var txtValue = td.textContent || td.innerText;
                tr[i].style.display = txtValue.toLowerCase().indexOf(filter) > -1 ? "" : "none";
            }
        }
    }

    function prepareMessageModal(mac, message) {
        document.getElementById("modalMac").value = mac;
        document.getElementById("deviceMac").textContent = mac;
        document.getElementById("modalMessage").value = message;
        updateCharCount();
        
        document.getElementById("modalMessage").addEventListener("input", function() {
            updateCharCount();
            if (this.value.length > 500) {
                this.value = this.value.substring(0, 500);
            }
        });
    }
    
    function updateCharCount() {
        const textarea = document.getElementById("modalMessage");
        const charCount = document.getElementById("charCount");
        const length = textarea.value.length;
        charCount.textContent = length + "/500";
        charCount.className = length > 500 ? "text-danger" : "text-muted";
    }
    </script>';
}

include "includes/footer.php";
?>