<?php
session_start();

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

include('includes/header.php');

/**
 * Normaliza MAC a formato HEX con “:”
 * - Soporta entrada con/ sin separadores y en base64
 */
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";

/* ---------------------- 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;
}

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

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

/* ---------------------- ALTA (MODAL AGREGAR) ---------------------- */
if (isset($_POST['submit'])) {
    unset($_POST['submit']);

    // Normalizar MAC
    if (isset($_POST['mac_address'])) {
        $_POST['mac_address'] = normalise_mac($_POST['mac_address']);
    }

    // Validar is_demo (0/1)
    if (!isset($_POST['is_demo'])) {
        $_POST['is_demo'] = 0;
    } else {
        $_POST['is_demo'] = intval($_POST['is_demo']) === 1 ? 1 : 0;
    }

    // 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;
    }

    // Generar device_key si no llega
    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;
    }

    // Valor por defecto de PIN
    if (empty($_POST['pin'])) {
        $_POST['pin'] = '0000';
    }

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

/* ---------------------- ACTUALIZACIÓN (MODAL EDITAR) ---------------------- */
if (isset($_POST['submitU'])) {
    unset($_POST['submitU']);

    // ID proveniente del modal
    $update_id = $_POST['update_id'];
    unset($_POST['update_id']);

    $updateData = $_POST;

    // Normalizar MAC si viene en actualización
    if (isset($updateData['mac_address'])) {
        $updateData['mac_address'] = normalise_mac($updateData['mac_address']);
    }

    // Si se marcó el check "convertir a cliente final"
    if (!empty($_POST['convertir_final']) && $_POST['convertir_final'] == 1) {
        $updateData['is_demo'] = 0;
    }
    
    // ELIMINAR EL CAMPO convertir_final DEL ARRAY DE ACTUALIZACIÓN
    unset($updateData['convertir_final']);

    // Obtener registro actual para conocer MAC actual
    $current = $db->select($table_name, '*', 'id = :id', '', [':id' => $update_id]);
    $mac = isset($current[0]['mac_address']) ? normalise_mac($current[0]['mac_address']) : '';

    // Si trae PIN, actualizar PIN en TODAS las filas que tengan esa MAC
    if (!empty($mac) && isset($updateData['pin'])) {
        $db->update($table_name, ['pin' => $updateData['pin']], 'LOWER(mac_address) = :mac', [':mac' => strtolower($mac)]);
        unset($updateData['pin']); // Evita doble set más abajo
    }

    // Actualizar solo este registro con los demás campos
    $db->update($table_name, $updateData, 'id = :id', [':id' => $update_id]);

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


/* ---------------------- ELIMINACIÓN INDIVIDUAL ---------------------- */
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;
}
?>

<!-- Modal 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>Confirmar</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 Agregar -->
<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">+ Agregar Usuario</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 (se formatea automáticamente)</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>

        <!-- is_demo siempre será 0 (cliente final) -->
        <input type="hidden" name="is_demo" value="0">
        <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 Editar -->
<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 Usuario</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">
      <!-- SOLO debe estar este campo oculto -->
      <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>

        <!-- Mostrar estado actual -->
        <div class="form-group">
          <label class="form-label">Estado actual:</label>
          <span id="current_status" class="badge badge-warning">Demo</span>
        </div>

        <!-- Checkbox para convertir a cliente final (solo visible para demos) -->
        <div class="form-group form-check" id="convert_container" style="display: none;">
          <input type="checkbox" class="form-check-input" id="convert_client" name="convertir_final" value="1">
          <label class="form-check-label" for="convert_client">Convertir en Cliente Final</label>
        </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 "¡Operación completada correctamente!"; break;
              case 2: echo "¡Usuario eliminado correctamente!"; break;
              case 3: echo "¡Usuarios seleccionados eliminados correctamente!"; break;
              case 4: echo "Error: ¡Esta MAC ya existe con este servidor DNS!"; break;
              default: echo "Operación completada.";
            }
            ?>
            <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>

        <div class="table-responsive">
          <input class="form-control" type="text" id="search" onkeyup="func2()" placeholder="Buscar...">
          <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>Tipo</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>
                  <?php if (!empty($row['is_demo'])): ?>
                    <span class="badge badge-warning">Demo</span>
                  <?php else: ?>
                    <span class="badge badge-success">Cliente</span>
                  <?php endif; ?>
                </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' ?>"
                          data-is-demo="<?= !empty($row['is_demo']) ? 1 : 0 ?>">
                    <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 (Agregar)
document.getElementById("mac").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);
});

// Formateo de MAC address (Editar)
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);
});

// Checkbox seleccionar todo + eliminación múltiple
document.addEventListener('DOMContentLoaded', function() {
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('.user-checkbox');
    const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
    const selectedIdsInput = document.getElementById('selected_ids');

    const updateDeleteButtonState = () => {
        const selectedCheckboxes = document.querySelectorAll('.user-checkbox:checked');
        deleteSelectedBtn.disabled = selectedCheckboxes.length === 0;
        const selectedIds = Array.from(selectedCheckboxes).map(cb => cb.value);
        selectedIdsInput.value = selectedIds.join(',');
    };

    selectAll.addEventListener('change', function() {
        checkboxes.forEach(checkbox => checkbox.checked = this.checked);
        updateDeleteButtonState();
    });
    checkboxes.forEach(checkbox => checkbox.addEventListener('change', updateDeleteButtonState));

    document.getElementById('deleteSelectedForm').addEventListener('submit', function(e) {
        if (!confirm('¿Seguro que deseas eliminar los usuarios seleccionados?')) {
            e.preventDefault();
        }
    });

    // Modal confirmación eliminar individual
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });

   // Prefill modal de edición
$('.edit-btn').click(function() {
    // Llenar datos básicos
    $('#update_id').val($(this).data('id'));
    $('#edit_dns_id').val($(this).data('dns-id'));
    $('#edit_mac_address').val($(this).data('mac'));
    $('#edit_username').val($(this).data('username'));
    $('#edit_password').val($(this).data('password'));
    $('#edit_pin').val($(this).data('pin'));
    
    const isDemo = $(this).data('is-demo');
    
    // Mostrar estado actual
    $('#current_status').removeClass('badge-warning badge-success')
                       .addClass(isDemo ? 'badge-warning' : 'badge-success')
                       .text(isDemo ? 'Demo' : 'Cliente Final');
    
    // Abrir modal
    $('#editUserModal').modal('show');
    
    // Manejar checkbox después de que el modal se muestre
    setTimeout(function() {
        if ($('#convert_container').length) {
            if (isDemo == 1) {
                $('#convert_container').show();
            } else {
                $('#convert_container').hide();
            }
            $('#convert_client').prop('checked', false);
        }
    }, 100);
});
});

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

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