<?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-blue: #003366;
    --dark-blue: #001a33;
    --light-blue: #00AEEF;
    --gold: #FFD166;
    --success-green: #28a745;
    --danger-red: #dc3545;
    --text-light: #f8f9fa;
}

body {
    background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
    background-attachment: fixed;
    color: var(--text-light);
    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(0, 174, 239, 0.2);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(0, 174, 239, 0.25);
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}

.card-header-custom {
    background: linear-gradient(90deg, var(--dark-blue), var(--primary-blue));
    padding: 20px;
    border-bottom: 2px solid var(--light-blue);
    color: var(--gold);
    text-align: center;
    font-weight: bold;
}

.card-body-custom { padding: 30px; }
h2, h3 { font-weight: 700; color: var(--gold); text-shadow: 0 0 6px rgba(0,0,0,0.6); }
.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.25); }
.table-custom thead tr { background: linear-gradient(90deg, var(--dark-blue), var(--primary-blue)); color: #fff; text-align: left; }
.table-custom th, .table-custom td { padding: 12px 15px; border-bottom: 1px solid rgba(0,174,239,0.25); }
.table-custom tbody tr { background-color: rgba(0,0,0,0.55); }
.table-custom tbody tr:last-of-type { border-bottom: 2px solid var(--light-blue); }
.table-custom tbody tr:hover { background-color: rgba(0,174,239,0.12); }

.action-buttons { display: flex; gap: 10px; }
.action-btn { padding: 6px 12px; border-radius: 5px; text-decoration: none; color: #fff !important; font-weight: bold; transition: all 0.3s; }
.action-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.25); text-decoration: none; }
.btn-edit { background: linear-gradient(45deg, var(--light-blue), #0056b3); }
.btn-delete { background: linear-gradient(45deg, var(--danger-red), #a71d2a); }

.btn-custom {
    background: linear-gradient(45deg, var(--dark-blue), var(--primary-blue));
    border: none; border-radius: 8px; padding: 12px 30px;
    font-weight: bold; color: #fff; transition: all 0.3s;
    box-shadow: 0 4px 15px rgba(0,174,239,0.25);
}
.btn-custom:hover { background: linear-gradient(45deg, var(--primary-blue), var(--light-blue)); transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,174,239,0.35); }

.alert-success { background-color: rgba(40,167,69,0.2); border: 1px solid rgba(40,167,69,0.3); color: #d4edda; border-radius: 8px; padding: 12px; margin-bottom: 20px; text-align: center; }
.alert-danger  { background-color: rgba(220,53,69,0.2); border: 1px solid rgba(220,53,69,0.3); color: #f8d7da; border-radius: 8px; padding: 12px; margin-bottom: 20px; text-align: center; }

/* Modal */
.modal-content { background: rgba(0,0,0,0.9); border: 1px solid rgba(0,174,239,0.3); border-radius: 15px; color: white; }
.modal-header { background: linear-gradient(90deg, var(--dark-blue), var(--primary-blue)); border-bottom: 1px solid var(--light-blue); }
.modal-footer { border-top: 1px solid rgba(0,174,239,0.3); }
.btn-default { background: linear-gradient(45deg,#6c757d,#495057); color:#fff; }
.btn-default:hover { background: linear-gradient(45deg,#495057,#343a40); }

/* Pequeno ajuste para o grupo do campo M3U */
.input-group { display: flex; gap: 8px; align-items: stretch; }
.input-group > input { flex: 1 1 auto; }
.input-group .btn { white-space: nowrap; }

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

            <div class="form-group">
                <label class="form-label" for="m3u"><span class="emoji">📄</span> Lista M3U / URL Xtream (opcional)</label>
                <div class="input-group">
                    <input class="form-control" id="m3u" placeholder="Cole aqui a URL (ex.: http://host:porta/get.php?username=USER&password=PASS&type=m3u )" type="text">
                    <button id="btnExtract" class="btn btn-custom" type="button">Extrair</button>
                </div>
                <small style="opacity:.85">Ao clicar em <b>Extrair</b>, preenchemos Usuário, Senha e tentamos selecionar o DNS automaticamente.</small>
            </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>
                        <option value="" selected disabled>Selecione uma opção</option>
                        <?php foreach($dnss as $dns) { ?>
                        <option value="<?=$dns['id']?>" data-url="<?=htmlspecialchars($dns['url'], ENT_QUOTES)?>"><?=$dns['title'] ?></option>
                        <?php } ?>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label" for="mac"><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="username"><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="password"><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="pin"><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>

            <div class="form-group">
                <label class="form-label" for="m3u"><span class="emoji">📄</span> Nova Lista M3U / URL Xtream (opcional)</label>
                <div class="input-group">
                    <input class="form-control" id="m3u" placeholder="Cole uma nova URL para atualizar os dados abaixo" type="text">
                    <button id="btnExtract" class="btn btn-custom" type="button">Extrair</button>
                </div>
                <small style="opacity:.85">Atualiza Usuário, Senha, Link e tenta selecionar o DNS correspondente.</small>
            </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']}' data-url='".htmlspecialchars($dns['url'], ENT_QUOTES)."' {$selected}>{$dns['title']}</option>";
                        } ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label" for="mac_address"><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="username"><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="password"><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="pin"><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');?>

<?php if (isset($_GET['create']) || isset($_GET['update'])): ?>
<script>
/* ------- Extração de M3U / Xtream (Funciona para Criar e Editar) ------- */
(function(){
  const $m3u = document.getElementById('m3u');
  const $btn = document.getElementById('btnExtract');
  if(!$m3u || !$btn) return; // Só executa se os elementos existirem na página

  const $user = document.getElementById('username');
  const $pass = document.getElementById('password');
  const $link = document.getElementById('link');
  const $dnsSelect = document.querySelector('select[name="dns_id"]');

  function parseM3U(input){
    if(!input) return null;
    const str = input.trim();
    try{
      const u = new URL(str);
      let username = u.searchParams.get('username') || u.searchParams.get('user');
      let password = u.searchParams.get('password') || u.searchParams.get('pass');
      if(!username || !password){
        const parts = u.pathname.split('/').filter(Boolean);
        const liveIdx = parts.findIndex(p => p.toLowerCase() === 'live');
        if(liveIdx !== -1 && parts.length >= liveIdx+3){
          username = username || parts[liveIdx+1];
          password = password || parts[liveIdx+2];
        } else if(parts.length >= 2 && liveIdx === -1){
          username = username || parts[parts.length - 2];
          password = password || parts[parts.length - 1];
        }
      }
      return { hostPort: u.host, username, password, href: u.href };
    }catch(e){
      const m = str.match(/^(?:https?:\/\/ )?([^\/\s]+)\/(?:get\.php|live)\?.*username=([^&]+)&password=([^&]+)/i) ||
                str.match(/^(?:https?:\/\/ )?([^\/\s]+)\/(?:live)\/([^\/\s]+)\/([^\/\s]+)/i);
      if(m){ return { hostPort: m[1], username: m[2], password: m[3], href: str }; }
      return null;
    }
  }

  function selectDnsByHost(hostPort){
    if(!hostPort || !$dnsSelect) return;
    const hostOnly = hostPort.split(':')[0].toLowerCase();
    let chosenId = null;

    for(const option of $dnsSelect.options){
        const dnsUrl = option.dataset.url;
        if(!dnsUrl) continue;
        try {
            const dnsHost = new URL(dnsUrl).hostname.toLowerCase();
            if(dnsHost === hostOnly) {
                chosenId = option.value;
                break;
            }
        } catch(e) {
            const dnsHost = dnsUrl.replace(/^https?:\/\//, '' ).split('/')[0].split(':')[0].toLowerCase();
            if(dnsHost === hostOnly) {
                chosenId = option.value;
                break;
            }
        }
    }
    if(chosenId) $dnsSelect.value = chosenId;
  }

  $btn.addEventListener('click', function(){
    const out = parseM3U($m3u.value);
    if(!out){ alert('Não foi possível ler a URL M3U/XTREAM.'); return; }
    if(out.username) $user.value = decodeURIComponent(out.username);
    if(out.password) $pass.value = decodeURIComponent(out.password);
    if(out.href)     $link.value = out.href;
    selectDnsByHost(out.hostPort);
  });
})();
</script>
<?php endif; ?>

<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");
        if(!input) return;
        filter = input.value.toUpperCase();
        table = document.getElementById("users");
        tr = table.getElementsByTagName("tr");
        for (i = 1; i < tr.length; i++) { // Começa em 1 para ignorar o cabeçalho (thead)
            let found = false;
            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) {
                        found = true;
                        break;
                    }
                }
            }
            tr[i].style.display = found ? "" : "none";
        }
    }
</script>

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