<?php
session_start();

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: index.php');
    exit;
}

include('includes/header.php');

// Normalize MAC address: decode, strip, format to lowercase colon-separated hex
function normalise_mac(string $raw): string {
    $dec = base64_decode($raw, true);
    if ($dec !== false) $raw = $dec;

    $raw = trim($raw);
    if (strpos($raw, '00:') === 0) $raw = substr($raw, 3);

    $hex = preg_replace('/[^0-9a-fA-F]/', '', $raw);
    $pairs = array_filter(str_split($hex, 2), fn($p) => strlen($p) === 2);

    return strtoupper(implode(':', $pairs));
}

$table_name = "playlist";

// Procesar eliminación múltiple
if (isset($_POST['delete_selected']) && !empty($_POST['selected_ids'])) {
    $ids = explode(',', $_POST['selected_ids']);
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $db->delete($table_name, "id IN ($placeholders)", $ids);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=3'</script>";
    exit;
}

$res = $db->select($table_name, '*', '', '');

if (isset($_POST['submit'])) {
    unset($_POST['submit']);

    // Normalize MAC address before insert
    if (isset($_POST['mac_address'])) {
        $_POST['mac_address'] = normalise_mac($_POST['mac_address']);
    }

    // VERIFICAR DUPLICADO: Misma MAC + mismo DNS
$mac_address = $_POST['mac_address'];
$dns_id = $_POST['dns_id'];

$existing = $db->select($table_name, '*', 'mac_address = :mac AND dns_id = :dns_id', '', [
    ':mac' => $mac_address,
    ':dns_id' => $dns_id
]);

if (!empty($existing)) {
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=4';</script>";
    exit;
}

    // Generate device key if not provided
    if (empty($_POST['device_key'])) {
        $chars = '1234567890';
        $deviceKey = '';
        for ($i = 0; $i < 8; $i++) {
            $deviceKey .= $chars[random_int(0, strlen($chars) - 1)];
        }
        $_POST['device_key'] = $deviceKey;
    }

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

// Procesar actualización desde modal
if (isset($_POST['submitU'])) {
    unset($_POST['submitU']);
    
    // Obtener el ID del campo oculto
    $update_id = $_POST['update_id'];
    unset($_POST['update_id']); // Remover para que no se incluya en la actualización
    
    $updateData = $_POST;

    // Normalize incoming MAC address (if present)
    if (isset($updateData['mac_address'])) {
        $updateData['mac_address'] = normalise_mac($updateData['mac_address']);
    }

    // Get current MAC address from DB for matching
    $current = $db->select($table_name, '*', 'id = :id', '', [':id' => $update_id]);
    $mac = isset($current[0]['mac_address']) ? normalise_mac($current[0]['mac_address']) : '';

    // Update all rows with the same MAC's PIN
    if (!empty($mac) && isset($updateData['pin'])) {
        $db->update($table_name, ['pin' => $updateData['pin']], 'LOWER(mac_address) = :mac', [':mac' => strtolower($mac)]);
    }

    // Update remaining fields for this record only
    unset($updateData['pin']);
    $db->update($table_name, $updateData, 'id = :id', [':id' => $update_id]);

    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=1'</script>";
    exit;
}

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>";
    exit;
}

$dnss = $db->select('dns', '*', '', '');
$dnsTitles = [];
foreach ($dnss as $dns) {
    $dnsTitles[$dns['id']] = $dns['title'];
}
?>

<!-- Modal para confirmar eliminación individual -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Confirm</h2>
            </div>
            <div class="modal-body">
                Realmente deseas eliminar?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Eliminar</a>
            </div>
        </div>
    </div>
</div>

<!-- Modal para agregar usuario -->
<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="addUserModalLabel">+ Add User</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" id="addUserForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label " for="title">DNS</label>
                        <select class="form-control" name="dns_id" required>
                            <option value="" selected disabled>Seleccionar DNS</option>
                            <?php foreach($dnss as $dns) { ?>
                            <option value="<?=$dns['id']?>"><?=$dns['title'] ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label " for="dns">MAC Address (will auto format)</label>
                        <input class="form-control" id="mac" name="mac_address" placeholder="MAC Address" type="text" required/>
                    </div>
                    <div class="form-group">
                        <label class="form-label " for="title">Username</label>
                        <input class="form-control" id="username" name="username" placeholder="Username" type="text" required/>
                    </div>
                    <div class="form-group">
                        <label class="form-label " for="dns">Password</label>
                        <input class="form-control" id="password" name="password" placeholder="Password" type="text" required/>
                    </div>
                    <div class="form-group">
                        <label class="form-label " for="dns">Parental Pin</label>
                        <input class="form-control" id="pin" name="pin" placeholder="Parental Pin" type="text" value="0000" required/>
                    </div>
                    <input type="hidden" name="device_key" value="">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary" name="submit">Guardar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal para editar usuario -->
<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="editUserModalLabel">Editar User</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" id="editUserForm">
                <input type="hidden" name="update_id" id="update_id">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label" for="edit_dns_id">DNS</label>
                        <select class="form-control" name="dns_id" id="edit_dns_id" required>
                            <?php foreach($dnss as $dns) { ?>
                            <option value="<?=$dns['id']?>"><?=$dns['title'] ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label " for="edit_mac_address">MAC Address</label>
                        <input class="form-control" id="edit_mac_address" name="mac_address" type="text" required/>
                    </div>
                    <div class="form-group">
                        <label class="form-label " for="edit_username">Username</label>
                        <input class="form-control" id="edit_username" name="username" type="text" required/>
                    </div>
                    <div class="form-group">
                        <label class="form-label " for="edit_password">Password</label>
                        <input class="form-control" id="edit_password" name="password" type="text" required/>
                    </div>
                    <div class="form-group">
                        <label class="form-label " for="edit_pin">Parental Pin</label>
                        <input class="form-control" id="edit_pin" name="pin" type="text" required/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary" name="submitU">Actualizar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="col-md-12 mx-auto">
    <div class="card-body">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning">
                <center><h2><i class="icon icon-commenting"></i> Lista de Usuarios</h2></center>
            </div>
            <div class="card-body">
                <?php if (isset($_GET['status'])): ?>
                    <div class="alert alert-<?= $_GET['status'] == 1 || $_GET['status'] == 3 ? 'success' : 'danger' ?> alert-dismissible fade show" role="alert">
                        <?php
                        switch ($_GET['status']) {
                            case 1: echo "Operation completed successfully!"; break;
                            case 2: echo "User deleted successfully!"; break;
                            case 3: echo "Selected users deleted successfully!"; break;
                           case 4: echo "Error: MAC address already exists with this DNS server!"; break;
                            default: echo "Operation completed!";
                        }
                        ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                <?php endif; ?>
                
                <div class="col-12 d-flex justify-content-between mb-3">
                    <button type="button" class="btn btn-info" data-toggle="modal" data-target="#addUserModal">
                        + Registrar Nuevo
                    </button>
                    <form method="post" id="deleteSelectedForm" class="d-inline">
                        <input type="hidden" name="selected_ids" id="selected_ids">
                        <button type="submit" name="delete_selected" id="deleteSelectedBtn" class="btn btn-danger" disabled>
                            <i class="fa fa-trash-o"></i> Eliminar Seleccionados
                        </button>
                    </form>
                </div>
                <br>
                <div class="table-responsive">
                    <input class="form-control" type="text" id="search" onkeyup="func2()" placeholder="Type to search">
                    <table id="users" class="table table-striped table-sm">
                        <thead style="color:white!important">
                            <tr class="header">
                                <th width="30"><input type="checkbox" id="select-all"></th>
                                <th>DNS</th>
                                <th>MAC Address</th>
                                <th>Username</th>
                                <th>Password</th>
                                <th>Parental Pin</th>
                                <th>Device Key</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($res as $row) {?>
                            <tr>
                                <td><input type="checkbox" class="user-checkbox" value="<?=$row['id'] ?>"></td>
                                <td><?= $dnsTitles[$row['dns_id']] ?? 'Unknown DNS' ?></td>
                                <td><?=$row['mac_address'] ?></td>
                                <td><?=$row['username'] ?></td>
                                <td><?=$row['password'] ?></td>
                                <td><?= !empty($row['pin']) ? $row['pin'] : '0000' ?></td>
                                <td><?=$row['device_key'] ?></td>
                                <td>
                                    <button class="btn btn-info edit-btn" data-id="<?=$row['id'] ?>" 
                                            data-dns-id="<?=$row['dns_id'] ?>" 
                                            data-mac="<?=$row['mac_address'] ?>" 
                                            data-username="<?=$row['username'] ?>" 
                                            data-password="<?=$row['password'] ?>" 
                                            data-pin="<?= !empty($row['pin']) ? $row['pin'] : '0000' ?>">
                                        <i class="fa fa-pencil-square-o"></i>
                                    </button>
                                    &nbsp&nbsp&nbsp
                                    <a class="btn btn-danger btn-ok" href="#" data-href="./<?=basename($_SERVER["SCRIPT_NAME"]) ?>?delete=<?=$row['id'] ?>" data-toggle="modal" data-target="#confirm-delete">
                                        <i class="fa fa-trash-o"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php }?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Formateo de MAC address con separadores automáticos
document.getElementById("mac").addEventListener('input', function(e) {
    // Guardar posición del cursor
    const cursorPosition = this.selectionStart;
    
    // Remover todos los caracteres no válidos y convertir a mayúsculas
    let value = this.value.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
    
    // Insertar dos puntos cada 2 caracteres
    let formattedValue = '';
    for (let i = 0; i < value.length; i++) {
        if (i > 0 && i % 2 === 0) {
            formattedValue += ':';
        }
        formattedValue += value[i];
    }
    
    this.value = formattedValue;
    
    // Ajustar posición del cursor
    const newCursorPosition = cursorPosition + (Math.floor((cursorPosition - 1) / 2));
    this.setSelectionRange(newCursorPosition, newCursorPosition);
});

// Para el campo de edición también
document.getElementById('edit_mac_address')?.addEventListener('input', function(e) {
    const cursorPosition = this.selectionStart;
    let value = this.value.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
    
    let formattedValue = '';
    for (let i = 0; i < value.length; i++) {
        if (i > 0 && i % 2 === 0) {
            formattedValue += ':';
        }
        formattedValue += value[i];
    }
    
    this.value = formattedValue;
    const newCursorPosition = cursorPosition + (Math.floor((cursorPosition - 1) / 2));
    this.setSelectionRange(newCursorPosition, newCursorPosition);
});

// Script para selección múltiple
document.addEventListener('DOMContentLoaded', function() {
    // Checkbox para seleccionar/deseleccionar todos
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('.user-checkbox');
    const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
    const selectedIdsInput = document.getElementById('selected_ids');
    
    selectAll.addEventListener('change', function() {
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateDeleteButtonState();
    });
    
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateDeleteButtonState);
    });
    
    function updateDeleteButtonState() {
        const selectedCheckboxes = document.querySelectorAll('.user-checkbox:checked');
        deleteSelectedBtn.disabled = selectedCheckboxes.length === 0;
        
        // Actualizar los IDs seleccionados en el formulario
        const selectedIds = Array.from(selectedCheckboxes).map(cb => cb.value);
        selectedIdsInput.value = selectedIds.join(',');
    }
    
    // Manejar el envío del formulario de eliminación múltiple
    document.getElementById('deleteSelectedForm').addEventListener('submit', function(e) {
        if (!confirm('Are you sure you want to delete the selected users?')) {
            e.preventDefault();
        }
    });
    
    // Configurar el modal de confirmación de eliminación individual
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
    
    // Configurar el modal de edición
    $('.edit-btn').click(function() {
        const id = $(this).data('id');
        const dnsId = $(this).data('dns-id');
        const mac = $(this).data('mac');
        const username = $(this).data('username');
        const password = $(this).data('password');
        const pin = $(this).data('pin');
        
        $('#update_id').val(id);
        $('#edit_dns_id').val(dnsId);
        $('#edit_mac_address').val(mac);
        $('#edit_username').val(username);
        $('#edit_password').val(password);
        $('#edit_pin').val(pin);
        
        $('#editUserModal').modal('show');
    });
    
    // Limpiar formulario de agregar cuando se cierra el modal
    $('#addUserModal').on('hidden.bs.modal', function () {
        document.getElementById('addUserForm').reset();
    });
});

// Función de búsqueda
function func2() {
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("search");
    filter = input.value.toUpperCase();
    table = document.getElementById("users");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td");
        let found = false;
        for (let j = 1; j < td.length; j++) { // Empezar desde 1 para omitir la columna checkbox
            if (td[j]) {
                txtValue = td[j].textContent || td[j].innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    found = true;
                    break;
                }
            }
        }
        tr[i].style.display = found ? "" : "none";
    }
}
</script>

<?php include ('includes/footer.php');?>
</body>
</html>