<?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 = strtolower(trim($raw));
    if (strpos($raw, '00:') === 0) $raw = substr($raw, 3);
    $hex = preg_replace('/[^0-9a-f]/', '', $raw);
    $pairs = array_filter(str_split($hex, 2), static fn($p) => strlen($p) === 2);
    return implode(':', $pairs); // keep lowercase
}

$table_name = "playlist";
$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']);
    }

    // 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);
    $db->close();
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=1'</script>";
}

@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['update']]);

if (isset($_POST['submitU'])) {
    unset($_POST['submitU']);
    $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' => $_GET['update']]);
    $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' => $_GET['update']]);

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

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

$dnss = $db->select('dns', '*', '', '');
$dnsTitles = [];
foreach ($dnss as $dns) {
    $dnsTitles[$dns['id']] = $dns['title'];
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciamento de Usuários</title>
    <style>
        :root {
            --primary-black: #000000;
            --dark-red: #8B0000;
            --bright-red: #FF0000;
            --dark-gray: #1a1a1a;
            --light-gray: #f8f9fa;
            --select-text: #333333; /* Cor escura para o texto dos selects */
        }
        
        body {
            background: linear-gradient(135deg, var(--primary-black), var(--dark-red));
            background-attachment: fixed;
            color: white;
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
        }
        
        .page-container {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        
        .main-content {
            flex: 1;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding-top: 40px;
            padding-bottom: 40px;
        }
        
        .card-custom {
            background: rgba(0, 0, 0, 0.7);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(255, 0, 0, 0.2);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 0, 0, 0.2);
            overflow: visible;
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .card-header-custom {
            background: linear-gradient(90deg, var(--primary-black), var(--dark-red));
            padding: 20px;
            border-bottom: 2px solid var(--bright-red);
        }
        
        .card-body-custom {
            padding: 30px;
        }
        
        .form-control {
            background-color: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 0, 0, 0.3);
            color: white;
            border-radius: 8px;
            padding: 12px 15px;
            transition: all 0.3s;
            height: auto;
            min-height: 45px;
            width: 100%;
        }
        
        .form-control:focus {
            background-color: rgba(255, 255, 255, 0.15);
            border-color: var(--bright-red);
            box-shadow: 0 0 0 0.2rem rgba(255, 0, 0, 0.25);
            color: white;
        }
        
        /* Estilo específico para selects - texto escuro */
        select.form-control {
            color: var(--select-text) !important; /* Texto escuro para melhor contraste */
            background-color: rgba(255, 255, 255, 0.9) !important; /* Fundo mais claro para o select */
            padding: 10px 15px;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23333'%3e%3cpath d='M7 10l5 5 5-5z'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 10px center;
            background-size: 16px;
            padding-right: 40px;
        }
        
        /* Opções do select com texto escuro */
        select.form-control option {
            color: var(--select-text);
            background-color: white;
            padding: 12px;
        }
        
        .form-label {
            font-weight: 600;
            color: #f8f9fa;
            margin-bottom: 8px;
            display: block;
        }
        
        .btn-custom {
            background: linear-gradient(45deg, var(--primary-black), var(--dark-red));
            border: none;
            border-radius: 8px;
            padding: 12px 30px;
            font-weight: bold;
            color: white;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(255, 0, 0, 0.2);
            margin-top: 15px;
            display: inline-block;
            text-decoration: none;
            text-align: center;
        }
        
        .btn-custom:hover {
            background: linear-gradient(45deg, var(--dark-red), var(--primary-black));
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 0, 0, 0.3);
            color: white;
            text-decoration: none;
        }
        
        .btn-info-custom {
            background: linear-gradient(45deg, #007bff, #0056b3);
        }
        
        .btn-danger-custom {
            background: linear-gradient(45deg, #dc3545, #a71d2a);
        }
        
        h2, h3 {
            font-weight: 700;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }
        
        .emoji {
            font-size: 1.2em;
            margin-right: 8px;
        }
        
        .table-custom {
            width: 100%;
            border-collapse: collapse;
            margin: 25px 0;
            font-size: 0.9em;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
        }
        
        .table-custom thead tr {
            background: linear-gradient(90deg, var(--primary-black), var(--dark-red));
            color: #ffffff;
            text-align: left;
        }
        
        .table-custom th,
        .table-custom td {
            padding: 12px 15px;
            border-bottom: 1px solid rgba(255, 0, 0, 0.2);
        }
        
        .table-custom tbody tr {
            background-color: rgba(0, 0, 0, 0.5);
        }
        
        .table-custom tbody tr:last-of-type {
            border-bottom: 2px solid var(--bright-red);
        }
        
        .table-custom tbody tr:hover {
            background-color: rgba(255, 0, 0, 0.1);
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        
        .action-btn {
            padding: 6px 12px;
            border-radius: 5px;
            color: white;
            text-decoration: none;
            transition: all 0.3s;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            color: white;
            text-decoration: none;
        }
        
        .btn-edit {
            background: linear-gradient(45deg, #007bff, #0056b3);
        }
        
        .btn-delete {
            background: linear-gradient(45deg, #dc3545, #a71d2a);
        }
        
        /* Modal styles */
        .modal-content {
            background: rgba(0, 0, 0, 0.8);
            border: 1px solid rgba(255, 0, 0, 0.3);
            border-radius: 15px;
            color: white;
        }
        
        .modal-header {
            background: linear-gradient(90deg, var(--primary-black), var(--dark-red));
            border-bottom: 1px solid var(--bright-red);
        }
        
        .modal-footer {
            border-top: 1px solid rgba(255, 0, 0, 0.3);
        }
        
        .btn-default {
            background: linear-gradient(45deg, #6c757d, #495057);
            color: white;
            border: none;
        }
        
        .btn-default:hover {
            background: linear-gradient(45deg, #495057, #343a40);
            color: white;
        }
        
        /* Search box */
        .search-box {
            margin-bottom: 20px;
        }
        
        .search-box .form-control {
            background-color: rgba(255, 255, 255, 0.15);
            border: 1px solid rgba(255, 0, 0, 0.4);
        }
        
        /* Responsividade para dispositivos móveis */
        @media (max-width: 992px) {
            .card-custom {
                max-width: 95%;
            }
            
            .table-custom {
                font-size: 0.85em;
            }
            
            .table-custom th,
            .table-custom td {
                padding: 10px 12px;
            }
        }
        
        @media (max-width: 768px) {
            .main-content {
                padding: 15px;
                padding-top: 20px;
                padding-bottom: 20px;
            }
            
            .card-body-custom {
                padding: 20px;
            }
            
            .card-header-custom {
                padding: 15px;
            }
            
            h2 {
                font-size: 1.5rem;
            }
            
            h3 {
                font-size: 1.3rem;
            }
            
            .btn-custom {
                padding: 10px 20px;
                margin: 10px 5px;
            }
            
            .table-responsive {
                overflow-x: auto;
            }
            
            .table-custom {
                font-size: 0.8em;
            }
            
            .table-custom th,
            .table-custom td {
                padding: 8px 10px;
            }
            
            .action-buttons {
                flex-direction: column;
                gap: 5px;
            }
            
            .action-btn {
                padding: 5px 8px;
                font-size: 0.9em;
                text-align: center;
            }
        }
        
        @media (max-width: 576px) {
            .card-body-custom {
                padding: 15px;
            }
            
            .form-control {
                padding: 10px;
            }
            
            select.form-control {
                padding-right: 35px;
                background-position: right 8px center;
            }
            
            .btn-custom {
                width: 100%;
                margin: 5px 0;
            }
            
            .table-custom {
                font-size: 0.75em;
            }
            
            .table-custom th,
            .table-custom td {
                padding: 6px 8px;
            }
            
            .emoji {
                font-size: 1.1em;
                margin-right: 5px;
            }
        }
    </style>
</head>
<body>
<div class="page-container">

<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><span class="emoji">⚠️</span> Confirmar</h2>
            </div>
            <div class="modal-body">
                Tem certeza que deseja excluir este usuário?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Excluir</a>
            </div>
        </div>
    </div>
</div>

<?php if (isset($_GET['create'])){ ?>
<div class="main-content">
    <div class="card-custom">
        <div class="card-header-custom text-center">
            <h2><span class="emoji">👥</span> Gerenciamento de Usuários</h2>
        </div>
        <div class="card-body-custom">
            <div class="mb-4">
                <h3><span class="emoji">➕</span> Adicionar Usuário</h3>
            </div>
            <form method="post">
                <div class="form-group">
                    <label class="form-label" for="title"><span class="emoji">🌐</span> DNS</label>
                    <select class="form-control" name="dns_id" required>
                        <option value="" selected disabled>Selecione uma opção</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"><span class="emoji">📟</span> Endereço MAC (formato automático)</label>
                    <input class="form-control" id="mac" name="mac_address" placeholder="Ex: A1B2C3D4E5F6" type="text" required/>
                </div>
                <script>
                    document.getElementById("mac").addEventListener('keyup', function() {
                        this.value = (this.value.toUpperCase().replace(/[^\d|A-Z]/g, '').match(/.{1,2}/g) || []).join(":")
                    });
                </script>
                <div class="form-group">
                    <label class="form-label" for="title"><span class="emoji">👤</span> Nome de Usuário</label>
                    <input class="form-control" id="username" name="username" placeholder="Nome de usuário" type="text" required/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="dns"><span class="emoji">🔑</span> Senha</label>
                    <input class="form-control" id="password" name="password" placeholder="Senha" type="text" required/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="dns"><span class="emoji">🔒</span> PIN Parental</label>
                    <input class="form-control" id="pin" name="pin" placeholder="PIN parental" type="text" value="0000" required/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="link"><span class="emoji">🔗</span> Link</label>
                    <input class="form-control" id="link" name="link" placeholder="Link" type="text"/>
                </div>
                <input type="hidden" name="device_key" value="">
                <div class="form-group text-center">
                    <button class="btn btn-custom" name="submit" type="submit">
                        <span class="emoji">💾</span> Salvar
                    </button>
                    <a href="./<?=basename($_SERVER["SCRIPT_NAME"]) ?>" class="btn btn-custom btn-danger-custom">
                        <span class="emoji">↩️</span> Voltar
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>
<?php } else if (isset($_GET['update'])){ ?>
<div class="main-content">
    <div class="card-custom">
        <div class="card-header-custom text-center">
            <h2><span class="emoji">👥</span> Gerenciamento de Usuários</h2>
        </div>
        <div class="card-body-custom">
            <div class="mb-4">
                <h3><span class="emoji">✏️</span> Editar Usuário</h3>
            </div>
            <form method="post">
                <div class="form-group">
                    <label class="form-label" for="dns_id"><span class="emoji">🌐</span> DNS</label>
                    <select class="form-control" name="dns_id" required>
                        <?php foreach($dnss as $dns) {
                            $selected = ($dns['id'] == $resU[0]['dns_id']) ? 'selected' : '';
                            echo "<option value='{$dns['id']}' {$selected}>{$dns['title']}</option>";
                        } ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label" for="dns"><span class="emoji">📟</span> Endereço MAC</label>
                    <input class="form-control" id="mac_address" name="mac_address" value="<?=$resU[0]['mac_address'] ?>" type="text" required/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="title"><span class="emoji">👤</span> Nome de Usuário</label>
                    <input class="form-control" id="username" name="username" value="<?=$resU[0]['username'] ?>" type="text" required/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="dns"><span class="emoji">🔑</span> Senha</label>
                    <input class="form-control" id="password" name="password" value="<?=$resU[0]['password'] ?>" type="text" required/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="dns"><span class="emoji">🔒</span> PIN Parental</label>
                    <input class="form-control" id="pin" name="pin" value="<?=$resU[0]['pin'] ?>" type="text" required/>
                </div>
                <div class="form-group">
                    <label class="form-label" for="link"><span class="emoji">🔗</span> Link</label>
                    <input class="form-control" id="link" name="link" value="<?=$resU[0]['link'] ?>" type="text"/>
                </div>
                <div class="form-group text-center">
                    <button class="btn btn-custom" name="submitU" type="submit">
                        <span class="emoji">💾</span> Atualizar
                    </button>
                    <a href="./<?=basename($_SERVER["SCRIPT_NAME"]) ?>" class="btn btn-custom btn-danger-custom">
                        <span class="emoji">↩️</span> Voltar
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>
<?php } else { ?>
<div class="main-content">
    <div class="card-custom">
        <div class="card-header-custom text-center">
            <h2><span class="emoji">👥</span> Gerenciamento de Usuários</h2>
        </div>
        <div class="card-body-custom">
            <div class="text-center mb-4">
                <a href="./<?=basename($_SERVER["SCRIPT_NAME"]) ?>?create" class="btn btn-custom">
                    <span class="emoji">➕</span> Criar Usuário
                </a>
            </div>
            
            <div class="search-box">
                <input class="form-control" type="text" id="search" onkeyup="func2()" placeholder="🔍 Digite para pesquisar...">
            </div>
            
            <div class="table-responsive">
                <table id="users" class="table-custom">
                    <thead>
                        <tr>
                            <th><span class="emoji">🌐</span> DNS</th>
                            <th><span class="emoji">📟</span> Endereço MAC</th>
                            <th><span class="emoji">👤</span> Usuário</th>
                            <th><span class="emoji">🔑</span> Senha</th>
                            <th><span class="emoji">🔒</span> PIN Parental</th>
                            <th><span class="emoji">🔗</span> Link</th>
                            <th><span class="emoji">🔐</span> Chave do Dispositivo</th>
                            <th><span class="emoji">⚙️</span> Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($res as $row) {?>
                        <tr>
                            <td><?= $dnsTitles[$row['dns_id']] ?? 'DNS Desconhecido' ?></td>
                            <td><?=$row['mac_address'] ?></td>
                            <td><?=$row['username'] ?></td>
                            <td><?=$row['password'] ?></td>
                            <td><?= !empty($row['pin']) ? $row['pin'] : '0000' ?></td>
                            <td><?=$row['link'] ?></td>
                            <td><?=$row['device_key'] ?></td>
                            <td>
                                <div class="action-buttons">
                                    <a class="action-btn btn-edit" href="./<?=basename($_SERVER["SCRIPT_NAME"]) ?>?update=<?=$row['id'] ?>">
                                        <span class="emoji">✏️</span> Editar
                                    </a>
                                    <a class="action-btn btn-delete" href="#" data-href="./<?=basename($_SERVER["SCRIPT_NAME"]) ?>?delete=<?=$row['id'] ?>" data-toggle="modal" data-target="#confirm-delete">
                                        <span class="emoji">🗑️</span> Excluir
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php }?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php } ?>

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

<script>
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
    
    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");
            for (var j = 0; j < td.length; j++) {
                if (td[j]) {
                    txtValue = td[j].textContent || td[j].innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        tr[i].style.display = "";
                        break;
                    } else {
                        tr[i].style.display = "none";
                    }
                }
            }
        }
    }
</script>

</div>
</body>
</html>