<?php
/**
 * Lista.php - Sistema Consolidado v4.0
 * Status: Estabilizado e Responsivo
 */

include('includes/header.php');

$table_name = "playlist";
$status_message = '';
$current_page = basename($_SERVER["SCRIPT_NAME"]);

// --- Funções de Status (ORIGINAL PROTEGIDA) ---
function set_status_message($status) {
    global $status_message;
    $messages = [
        1 => ['class' => 'success', 'icon' => 'check-circle', 'text' => 'Operação realizada com sucesso!'],
        2 => ['class' => 'danger', 'icon' => 'trash', 'text' => 'Registro(s) deletado(s) com sucesso.'],
        3 => ['class' => 'warning', 'icon' => 'exclamation-triangle', 'text' => 'Erro de validação: O ID do DNS é inválido.']
    ];

    if (isset($messages[$status])) {
        $m = $messages[$status];
        $status_message = "<div class='alert alert-modern alert-{$m['class']} animated fadeInDown' role='alert'>
                            <div class='d-flex align-items-center'>
                                <i class='fa fa-{$m['icon']} fa-lg me-3'></i>
                                <span>{$m['text']}</span>
                            </div>
                          </div>";
    }
}

if (isset($_GET['status'])) {
    set_status_message((int)$_GET['status']);
}

/**
 * PROCESSAMENTO DE DADOS (Lógica de Negócio Mantida)
 */
if (isset($_POST['delete_selected']) && !empty($_POST['selected_ids'])) {
    foreach ($_POST['selected_ids'] as $id) {
        $db->delete($table_name, 'id = :id', [':id' => (int)$id]);
    }
    echo "<script>window.location.href='{$current_page}?status=2'</script>";
    exit;
}

if (isset($_POST['delete_all_confirm'])) {
    $db->delete($table_name, '1=1', []); 
    echo "<script>window.location.href='{$current_page}?status=2'</script>";
    exit;
}

if (isset($_POST['submit'])) {
    $dns_id = filter_var($_POST['dns_id'], FILTER_VALIDATE_INT);
    if ($dns_id === false || $dns_id <= 0) {
        echo "<script>window.location.href='{$current_page}?create&status=3'</script>";
        exit;
    }
    unset($_POST['submit'], $_POST['m3u']);
    $_POST['dns_id'] = $dns_id;
    $db->insert($table_name, $_POST);
    echo "<script>window.location.href='{$current_page}?status=1'</script>";
    exit;
}

$update_id = (isset($_GET['update']) && is_numeric($_GET['update'])) ? (int)$_GET['update'] : null;
$resU = [];
if ($update_id) {
    $resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $update_id]) ?? [];
    if (empty($resU)) {
        echo "<script>window.location.href='{$current_page}'</script>";
        exit;
    }
}

if (isset($_POST['submitU']) && $update_id) {
    unset($_POST['submitU'], $_POST['m3u']);
    $db->update($table_name, $_POST, 'id = :id', [':id' => $update_id]);
    echo "<script>window.location.href='{$current_page}?status=1'</script>";
    exit;
}

if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $db->delete($table_name, 'id = :id', [':id' => (int)$_GET['delete']]);
    echo "<script>window.location.href='{$current_page}?status=2'</script>";
    exit;
}

$res = $db->select($table_name, '*', '', 'id DESC') ?? [];
?>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #2E3192 0%, #1BFFFF 100%);
        --danger-gradient: linear-gradient(135deg, #FF416C 0%, #FF4B2B 100%);
        --success-gradient: linear-gradient(135deg, #1D976C 0%, #93F9B9 100%);
        --surface: #ffffff;
        --background: #f8fafc;
        --text-main: #2d3748;
    }

    body { background: var(--background); font-family: 'Inter', sans-serif; color: var(--text-main); }
    .container { max-width: 1200px; padding: 2rem 1rem; }

    /* Estilização Moderna */
    .card-modern { background: var(--surface); border: none; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); overflow: hidden; margin-bottom: 2rem; }
    .card-header-modern { background: var(--primary-gradient); padding: 1.5rem; color: white; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem; }
    .card-header-modern h2 { margin: 0; font-size: 1.3rem; font-weight: 700; letter-spacing: -0.5px; }

    .alert-modern { border: none; border-radius: 12px; color: #fff; font-weight: 500; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
    .alert-success { background: var(--success-gradient); }
    .alert-danger { background: var(--danger-gradient); }
    .alert-warning { background: #f6ad55; }

    .form-control { border-radius: 12px; border: 1.5px solid #edf2f7; padding: 0.8rem 1rem; transition: 0.3s; }
    .form-control:focus { border-color: #2E3192; box-shadow: 0 0 0 4px rgba(46, 49, 146, 0.1); }

    .btn { border-radius: 12px; font-weight: 600; padding: 0.7rem 1.5rem; transition: 0.3s; border: none; }
    .btn-primary { background: var(--primary-gradient); color: white; }
    .btn-danger { background: var(--danger-gradient); color: white; }

    /* Tabela Responsiva */
    .table-responsive { width: 100%; border-radius: 15px; overflow-x: auto; }
    .table thead th { background: #f1f5f9; color: #64748b; font-weight: 700; text-transform: uppercase; font-size: 0.75rem; padding: 1.2rem; border: none; }
    .table tbody td { padding: 1.2rem; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }

    .badge-dns { background: #edf2f7; color: #2d3748; border: 1px solid #cbd5e0; padding: 5px 10px; border-radius: 8px; font-family: monospace; font-weight: 700; }

    @keyframes fadeInDown { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } }
    .animated { animation: fadeInDown 0.6s ease both; }
</style>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px;">
            <div class="modal-body text-center p-5">
                <i class="fa fa-trash-alt fa-4x text-danger mb-4"></i>
                <h3 class="fw-bold">Remover Registro?</h3>
                <p class="text-muted">Essa ação apagará os dados permanentemente do servidor.</p>
                <div class="mt-4">
                    <button type="button" class="btn btn-light me-2" data-dismiss="modal">Cancelar</button>
                    <a class="btn btn-danger btn-ok">Confirmar Exclusão</a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="confirm-delete-all" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px;">
            <div class="modal-body text-center p-5">
                <i class="fa fa-fire-alt fa-4x text-danger mb-4"></i>
                <h2 class="text-danger fw-bold">LIMPEZA TOTAL?</h2>
                <p>Isso apagará <b>todas</b> as playlists cadastradas.</p>
                <form method="post">
                    <div class="mt-4 d-grid gap-2">
                        <button type="submit" name="delete_all_confirm" class="btn btn-danger btn-lg">APAGAR TUDO AGORA</button>
                        <button type="button" class="btn btn-link text-muted" data-dismiss="modal">Cancelar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="container py-4">
    <?= $status_message ?>

    <?php if (isset($_GET['create']) || $update_id): 
        $isEdit = (bool)$update_id;
        $data = $isEdit ? $resU[0] : [];
    ?>
        <div class="card-modern animated">
            <div class="card-header-modern">
                <h2><i class="fa <?= $isEdit ? 'fa-edit' : 'fa-plus-circle' ?> me-2"></i> <?= $isEdit ? 'Editar Configuração' : 'Cadastrar Playlist M3U8' ?></h2>
            </div>
            <div class="card-body p-4 p-md-5">
                <form method="post">
                    <div class="row g-4">
                        <div class="col-md-12">
                            <label class="form-label fw-bold">Servidor DNS Conectado</label>
                            <select class="form-control" name="dns_id" required>
                                <option value="">Selecione o Servidor...</option>
                                <?php
                                $dnss = $db->select('dns', '*', '', 'title ASC') ?? [];
                                foreach($dnss as $dns): ?>
                                    <option value="<?=$dns['id']?>" <?= ($isEdit && $data['dns_id'] == $dns['id']) ? 'selected' : '' ?>><?= htmlspecialchars($dns['title']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-12">
                            <label class="form-label fw-bold">Link da M3U (Extrator Inteligente)</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fa fa-link"></i></span>
                                <input class="form-control m3u-extractor" placeholder="Cole o link completo aqui para preencher usuário e senha automaticamente..." type="url"/>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">Usuário de Acesso</label>
                            <input type="text" name="username" id="username_field" class="form-control" value="<?= $isEdit ? htmlspecialchars($data['username']) : '' ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Senha de Acesso</label>
                            <input type="text" name="password" id="password_field" class="form-control" value="<?= $isEdit ? htmlspecialchars($data['password']) : '' ?>" required>
                        </div>

                        <div class="col-md-8">
                            <label class="form-label fw-bold">Endereço MAC</label>
                            <input class="form-control mac-mask text-uppercase" name="mac_address" value="<?= $isEdit ? htmlspecialchars($data['mac_address']) : '' ?>" placeholder="00:00:00:00:00:00" type="text" maxlength="17" required/>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">PIN</label>
                            <input class="form-control text-center fw-bold" name="pin" value="<?= $isEdit ? htmlspecialchars($data['pin']) : '0000' ?>" type="text" maxlength="4"/>
                        </div>
                    </div>

                    <div class="mt-5 pt-3 border-top d-flex gap-2">
                        <button class="btn btn-primary btn-lg w-100 shadow" name="<?= $isEdit ? 'submitU' : 'submit' ?>" type="submit">
                            <i class="fa fa-save me-2"></i> SALVAR DADOS
                        </button>
                        <a href="<?= $current_page ?>" class="btn btn-light btn-lg px-4 border">Voltar</a>
                    </div>
                </form>
            </div>
        </div>

    <?php else: ?>
        <form method="post">
            <div class="card-modern animated">
                <div class="card-header-modern">
                    <h2><i class="fa fa-database me-2"></i>SISTEMA M3U8</h2>
                    <div class="d-flex gap-2">
                        <a href="?create" class="btn btn-light text-primary btn-sm"><i class="fa fa-plus me-1"></i> ADD M3U8</a>
                        <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#confirm-delete-all"><i class="fa fa-fire-alt"></i></button>
                    </div>
                </div>

                <div class="card-body p-0">
                    <div class="p-3 bg-light border-bottom d-flex justify-content-between align-items-center flex-wrap gap-3">
                        <div class="d-flex align-items-center gap-2">
                            <button type="submit" name="delete_selected" class="btn btn-warning btn-sm text-white px-3 shadow-sm" onclick="return confirm('Excluir registros selecionados?')">
                                <i class="fa fa-check-square me-1"></i> Ação em Massa
                            </button>
                            <span class="text-muted small">| Total: <b><?= count($res) ?></b></span>
                        </div>
                        <div class="input-group shadow-sm" style="max-width: 300px; border-radius: 10px; overflow: hidden;">
                            <span class="input-group-text bg-white border-0"><i class="fa fa-search text-muted"></i></span>
                            <input class="form-control border-0" type="text" id="search" onkeyup="filterTable()" placeholder="Buscar MAC ou Usuário...">
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table id="usersTable" class="table mb-0">
                            <thead>
                                <tr>
                                    <th width="40" class="text-center"><input type="checkbox" id="selectAll" class="form-check-input"></th>
                                    <th>DNS</th>
                                    <th>MAC Address</th>
                                    <th>Usuário / Senha</th>
                                    <th>PIN</th>
                                    <th class="text-center">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($res as $row): ?>
                                <tr>
                                    <td class="text-center"><input type="checkbox" name="selected_ids[]" value="<?= $row['id'] ?>" class="form-check-input selectItem"></td>
                                    <td><span class="badge-dns"><?= htmlspecialchars($row['dns_id']) ?></span></td>
                                    <td><b class="text-primary"><?= htmlspecialchars($row['mac_address']) ?></b></td>
                                    <td>
                                        <div class="small fw-bold text-dark"><?= htmlspecialchars($row['username']) ?></div>
                                        <div class="small text-muted"><?= htmlspecialchars($row['password']) ?></div>
                                    </td>
                                    <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($row['pin']) ?></span></td>
                                    <td class="text-center">
                                        <div class="d-flex justify-content-center gap-1">
                                            <a class="btn btn-primary btn-sm" href="?update=<?= $row['id'] ?>"><i class="fa fa-edit"></i></a>
                                            <button type="button" class="btn btn-danger btn-sm" data-href="?delete=<?= $row['id'] ?>" data-toggle="modal" data-target="#confirm-delete">
                                                <i class="fa fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if(empty($res)): ?>
                                    <tr><td colspan="6" class="text-center py-5 text-muted">Nenhum registro encontrado.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </form>
    <?php endif; ?>
</div>

<script>
// Mantendo toda a sua lógica de Script original funcional
const selectAll = document.getElementById('selectAll');
if(selectAll){
    selectAll.addEventListener('click', function() {
        let checkboxes = document.querySelectorAll('.selectItem');
        checkboxes.forEach(cb => cb.checked = this.checked);
    });
}

function filterTable() {
    let filter = document.getElementById("search").value.toUpperCase();
    let rows = document.querySelector("#usersTable tbody").rows;
    for (let row of rows) {
        let text = row.textContent.toUpperCase();
        row.style.display = text.includes(filter) ? "" : "none";
    }
}

// Máscara de MAC automática
document.querySelectorAll('.mac-mask').forEach(input => {
    input.addEventListener('input', e => {
        let v = e.target.value.toUpperCase().replace(/[^0-9A-F]/g, "").slice(0, 12);
        let parts = v.match(/.{1,2}/g);
        e.target.value = parts ? parts.join(":") : v;
    });
});

// Extrator M3U Original
document.querySelectorAll('.m3u-extractor').forEach(input => {
    input.addEventListener('input', function() {
        if(!this.value) return;
        try {
            let url = new URL(this.value);
            let user = url.searchParams.get("username") || url.searchParams.get("user");
            let pass = url.searchParams.get("password") || url.searchParams.get("pass");
            let mac  = url.searchParams.get("mac");
            if (user) document.getElementById('username_field').value = user;
            if (pass) document.getElementById('password_field').value = pass;
            if (mac) {
                let macIn = document.querySelector('.mac-mask');
                macIn.value = mac.toUpperCase();
                macIn.dispatchEvent(new Event('input'));
            }
        } catch (e) { }
    });
});

// Modais
$(document).on('click', '[data-toggle="modal"]', function() {
    let href = $(this).data('href');
    if(href) $('.btn-ok').attr('href', href);
});

// Auto-close Alertas
setTimeout(() => { $('.alert').fadeOut('slow'); }, 5000);
</script>

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