<?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';

// Configuración para mensajes MAC
$keyFilePath = __DIR__ . '/api/key.json';
$keys = [];
if (file_exists($keyFilePath)) {
    $keys = json_decode(file_get_contents($keyFilePath), true);
    if ($keys === null) {
        $keys = []; // Inicializar como array si hay error en el JSON
    }
}

// Procesamiento de acciones para MAC Messages
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // Solo procesamos acciones MAC aquí, las de Notes van a note_actions.php
    if (strpos($action, 'mac_') === 0) {
        header('Content-Type: application/json');
        
        try {
            $macAddress = strtoupper(trim($_POST['mac_address'] ?? ''));
            $message = trim($_POST['message'] ?? '');

            if ($action === 'mac_add' || $action === 'mac_edit') {
                if (empty($macAddress) || empty($message)) {
                    throw new Exception('MAC Address and Message are required');
                }
                
                $keys[$macAddress] = [
                    'key' => $keys[$macAddress]['key'] ?? bin2hex(random_bytes(8)),
                    'message' => $message
                ];
                file_put_contents($keyFilePath, json_encode($keys, JSON_PRETTY_PRINT));
                echo json_encode(['success' => true, 'message' => 'Message saved successfully']);
                
            } elseif ($action === 'mac_delete') {
                if (isset($keys[$macAddress])) {
                    unset($keys[$macAddress]);
                    file_put_contents($keyFilePath, json_encode($keys, JSON_PRETTY_PRINT));
                    echo json_encode(['success' => true, 'message' => 'Message deleted successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'MAC address not found']);
                }
            }
            exit;
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
            exit;
        }
    }
}

$page_title = "System Settings";

$page_content = '
<!-- Notes Table -->
<div class="card mb-5">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <h3>Nota general Servidores Linea 2</h3>
        </div>
    </div>
    <div class="card-body pt-0">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="notes_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-125px">Texto</th>
                    <th class="min-w-125px d-none">Content</th> <!-- Oculto -->
                    <th class="min-w-70px">Actions</th>
                </tr>
            </thead>
            <tbody id="notes_table_body"></tbody>
        </table>
    </div>
</div>

<!-- MAC Messages Table -->
<div class="card">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <h3>Mensaje para cada MAC Linea 1</h3>
        </div>
        <div class="card-toolbar">
            <button type="button" class="btn btn-primary" onclick="openMacAddModal()">Add Message</button>
        </div>
    </div>
    <div class="card-body pt-0">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="mac_table">
            <thead>
                <tr class="text-start text-gray-500 fw-bold fs-7 text-uppercase gs-0">
                    <th class="min-w-125px">MAC Address</th>
                    <th class="min-w-125px">Message</th>
                    <th class="min-w-70px">Actions</th>
                </tr>
            </thead>
            <tbody id="mac_table_body"></tbody>';

// Mostrar mensajes MAC existentes
foreach ($keys as $mac => $data) {
    $page_content .= '
        <tr data-mac="'.htmlspecialchars($mac, ENT_QUOTES).'">
            <td>'.htmlspecialchars($mac, ENT_QUOTES).'</td>
            <td>'.htmlspecialchars($data['message'] ?? '', ENT_QUOTES).'</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="openMacEditModal(\''.htmlspecialchars($mac, ENT_QUOTES).'\')">Edit</button>
                <button class="btn btn-sm btn-danger" onclick="deleteMacMessage(\''.htmlspecialchars($mac, ENT_QUOTES).'\')">Delete</button>
            </td>
        </tr>';
}

$page_content .= '
            </tbody>
        </table>
    </div>
</div>

<!-- Modal para Notes -->
<div class="modal fade" id="note_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="note_modal_title" class="fw-bold">Update Note</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="note_id">
                <div class="mb-7">
                    <label for="modal_note_title" class="fs-6 fw-semibold mb-2">Title</label>
                    <input type="text" class="form-control" id="modal_note_title" placeholder="Enter Title" required>
                </div>
                <!-- Campo oculto (NO se mostrará pero sí se usará internamente) -->
                <div class="mb-7 d-none">
                    <label for="modal_note_content" class="fs-6 fw-semibold mb-2">Content</label>
                    <textarea class="form-control" id="modal_note_content" placeholder="Enter Content" required></textarea>
                </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="updateNote()">Update</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal para MAC Messages -->
<div class="modal fade" id="mac_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="mac_modal_title" class="fw-bold">Add MAC Message</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-7">
                    <label for="modal_mac_address" class="fs-6 fw-semibold mb-2">MAC Address</label>
                    <input type="text" class="form-control" id="modal_mac_address" placeholder="Enter MAC Address" required>
                </div>
                <div class="mb-7">
                    <label for="modal_mac_message" class="fs-6 fw-semibold mb-2">Message</label>
                    <input type="text" class="form-control" id="modal_mac_message" placeholder="Enter Message" 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="saveMacMessage()">Save</button>
            </div>
        </div>
    </div>
</div>';

include 'includes/layout.php';
?>

<script>
// Variables globales
let notesTable, macTable;
let currentMacAction = 'add'; // 'add' o 'edit'

// Inicialización
document.addEventListener("DOMContentLoaded", function () {
    loadNotes();
    initMacTable();
});

function loadNotes() {
    fetch("actions/note_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "view" }),
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then((data) => {
        if (data.success) {
            const tableBody = document.getElementById("notes_table_body");
            tableBody.innerHTML = "";

            data.data.forEach((setting) => {
                tableBody.innerHTML += `
                    <tr id="row_${setting.id}">
                        <td>${setting.id}</td>
                        <td>${escapeHtml(setting.note_title)}</td>
                        <td class="d-none">${escapeHtml(setting.note_content)}</td>
                        <td>
                            <button class="btn btn-sm btn-warning" 
                                onclick="openNoteEditModal(${setting.id}, '${escapeJs(setting.note_title)}', '${escapeJs(setting.note_content)}')">
                                Edit
                            </button>
                        </td>
                    </tr>
                `;
            });

            if (window.notesTable && typeof notesTable.destroy === 'function') {
                notesTable.destroy();
            }

            notesTable = $("#notes_table").DataTable({
                columnDefs: [
                    { targets: 2, visible: false }
                ]
            });
            
        } else {
            console.error("Error loading notes:", data.message);
            Swal.fire("Error", "Failed to load notes: " + data.message, "error");
        }
    })
    .catch((error) => {
        console.error("Error loading notes:", error);
        Swal.fire("Error", "Failed to load notes: " + error.message, "error");
    });
}

function openNoteEditModal(id, title, content) {
    document.getElementById("note_modal_title").textContent = "Edit Note";
    document.getElementById("note_id").value = id;
    document.getElementById("modal_note_title").value = title;
    document.getElementById("modal_note_content").value = content;

    new bootstrap.Modal(document.getElementById("note_modal")).show();
}

function updateNote() {
    const id = document.getElementById("note_id").value;
    const note_title = document.getElementById("modal_note_title").value.trim();
    const note_content = document.getElementById("modal_note_content").value.trim();

    if (!note_title || !note_content) {
        Swal.fire("Error", "Title and Content are required!", "error");
        return;
    }

    fetch("actions/note_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "edit", id, note_title, note_content }),
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then((data) => {
        if (data.success) {
            Swal.fire("Success", data.message, "success");

            // Cerrar modal
            const modal = bootstrap.Modal.getInstance(document.getElementById("note_modal"));
            modal.hide();

            // Actualizar fila
            const row = document.querySelector(`#row_${id}`);
            if (row) {
                row.innerHTML = `
                    <td>${id}</td>
                    <td>${escapeHtml(note_title)}</td>
                    <td class="d-none">${escapeHtml(note_content)}</td>
                    <td>
                        <button class="btn btn-sm btn-warning" 
                            onclick="openNoteEditModal(${id}, '${escapeJs(note_title)}', '${escapeJs(note_content)}')">
                            Edit
                        </button>
                    </td>
                `;
            }
        } else {
            Swal.fire("Error", data.message, "error");
        }
    })
    .catch((error) => {
        console.error("Error updating note:", error);
        Swal.fire("Error", "An unexpected error occurred.", "error");
    });
}

// Funciones para MAC Messages
function initMacTable() {
    if ($.fn.DataTable.isDataTable('#mac_table')) {
        macTable.destroy();
    }
    
    macTable = $("#mac_table").DataTable({
        responsive: {
            details: false
        },
        scrollX: true,  // Habilita scroll horizontal
        autoWidth: false, // Desactiva auto-ancho
        columnDefs: [
            {
                targets: 2, // Columna de acciones
                width: "120px" // Ancho fijo para columna de acciones
            },
            {
                targets: [0, 1], // Columnas MAC y Mensaje
                render: function(data, type, row) {
                    // Acorta el texto en móviles
                    if (type === 'display' && window.innerWidth < 768) {
                        return data.length > 15 ? 
                            data.substr(0, 12) + '...' : data;
                    }
                    return data;
                }
            }
        ],
        language: {
            lengthMenu: "Mostrar _MENU_ registros",
            search: "Buscar:",
            info: "Mostrando _START_ a _END_ de _TOTAL_",
            paginate: {
                first: "Primero",
                last: "Último",
                next: "Siguiente",
                previous: "Anterior"
            }
        }
    });

    // Ajustar tabla al cambiar tamaño/orientación
    $(window).on('resize orientationchange', function() {
        macTable.columns.adjust();
    });
}

function openMacAddModal() {
    currentMacAction = 'add';
    document.getElementById("mac_modal_title").textContent = "Add MAC Message";
    document.getElementById("modal_mac_address").value = "";
    document.getElementById("modal_mac_address").readOnly = false;
    document.getElementById("modal_mac_message").value = "";
    new bootstrap.Modal(document.getElementById("mac_modal")).show();
}

function openMacEditModal(mac) {
    currentMacAction = 'edit';
    document.getElementById("mac_modal_title").textContent = "Edit MAC Message";
    document.getElementById("modal_mac_address").value = mac;
    document.getElementById("modal_mac_address").readOnly = true;
    
    // Obtener mensaje actual de la tabla
    const row = document.querySelector(`#mac_table_body tr[data-mac="${mac}"]`);
    if (row) {
        const message = row.querySelector("td:nth-child(2)").textContent;
        document.getElementById("modal_mac_message").value = message.trim();
    }
    
    new bootstrap.Modal(document.getElementById("mac_modal")).show();
}

function saveMacMessage() {
    const macAddress = document.getElementById("modal_mac_address").value.trim().toUpperCase();
    const message = document.getElementById("modal_mac_message").value.trim();

    if (!macAddress || !message) {
        Swal.fire("Error", "MAC Address and Message are required!", "error");
        return;
    }

    // Validación básica de formato MAC
    if (!/^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/.test(macAddress)) {
        Swal.fire("Error", "Please enter a valid MAC address format (e.g., 00:1A:2B:3C:4D:5E)", "error");
        return;
    }

    const action = currentMacAction === 'add' ? 'mac_add' : 'mac_edit';
    
    fetch(window.location.href, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({
            action: action,
            mac_address: macAddress,
            message: message
        }),
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then((data) => {
        if (data.success) {
            Swal.fire("Success", data.message, "success")
                .then(() => location.reload());
        } else {
            Swal.fire("Error", data.message, "error");
        }
    })
    .catch((error) => {
        console.error("Error saving MAC message:", error);
        Swal.fire("Error", "An unexpected error occurred.", "error");
    });
}

function deleteMacMessage(mac) {
    Swal.fire({
        title: "Are you sure?",
        text: `You are about to delete the message for MAC: ${mac}`,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#d33",
        cancelButtonColor: "#3085d6",
        confirmButtonText: "Yes, delete it!"
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(window.location.href, {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: new URLSearchParams({
                    action: 'mac_delete',
                    mac_address: mac
                }),
            })
            .then((response) => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then((data) => {
                if (data.success) {
                    Swal.fire("Deleted!", data.message, "success")
                        .then(() => location.reload());
                } else {
                    Swal.fire("Error", data.message, "error");
                }
            })
            .catch((error) => {
                console.error("Error deleting MAC message:", error);
                Swal.fire("Error", "An unexpected error occurred.", "error");
            });
        }
    });
}

// Funciones auxiliares
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe.toString()
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

function escapeJs(unsafe) {
    if (!unsafe) return '';
    return unsafe.toString()
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/"/g, '\\"')
        .replace(/\n/g, '\\n');
}
</script>