<!-- main_enhanced.php -->
<?php 
include ('includes/header.php');

// Table names
$dns_table = 'dns';
$m3u_table = 'm3u_lists';
$page = 'main_enhanced.php';

// Criar tabelas se não existirem
$createDNSTableSQL = "CREATE TABLE IF NOT EXISTS dns (
    id INTEGER PRIMARY KEY,
    title TEXT,
    url TEXT
)";

$createM3UTableSQL = "CREATE TABLE IF NOT EXISTS m3u_lists (
    id INTEGER PRIMARY KEY,
    title TEXT,
    url TEXT,
    dns_id INTEGER,
    import_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status TEXT DEFAULT 'active',
    playlist_count INTEGER DEFAULT 0
)";

try {
    $db->db->exec($createDNSTableSQL);
    $db->db->exec($createM3UTableSQL);
} catch (Exception $e) {
    // Tables already exist
}

// Get all DNS and M3U lists
$dns_res = $db->select($dns_table, '*', '', '');
$m3u_res = $db->select($m3u_table, '*', '', 'import_date DESC');

// Update call for DNS
@$dnsUpdate = $db->select($dns_table, '*', 'id = :id', '', [':id' => $_GET['update_dns'] ?? null]);

// Bulk DNS Update
if(isset($_POST['bulk_dns_update'])){
    if(isset($_POST['dns_ids']) && isset($_POST['bulk_dns_url'])){
        foreach($_POST['dns_ids'] as $dns_id){
            $updateData = ['url' => $_POST['bulk_dns_url']];
            $db->update($dns_table, $updateData, 'id = :id',[':id' => $dns_id]);
        }
        echo "<script>window.location.href='".$page."?status=bulk_updated'</script>";
    }
}

// Update single DNS
if(isset($_POST['submitU']) && isset($_GET['update_dns'])){
    unset($_POST['submitU']);
    $updateData = $_POST;
    $db->update($dns_table, $updateData, 'id = :id',[':id' => $_GET['update_dns']]);
    echo "<script>window.location.href='".$page."?status=dns_updated'</script>";
}

// Insert new DNS
if (isset($_POST['submit_dns'])){
    unset($_POST['submit_dns']);
    $db->insert($dns_table, $_POST);
    echo "<script>window.location.href='".$page."?status=dns_created'</script>";
}

// Delete DNS
if(isset($_GET['delete_dns'])){
    $db->delete($dns_table, 'id = :id',[':id' => $_GET['delete_dns']]);
    // Also delete associated M3U lists
    $db->delete($m3u_table, 'dns_id = :dns_id',[':dns_id' => $_GET['delete_dns']]);
    echo "<script>window.location.href='".$page."?status=dns_deleted'</script>";
}

// Insert M3U list
if(isset($_POST['submit_m3u'])){
    unset($_POST['submit_m3u']);
    $m3u_data = [
        'title' => $_POST['m3u_title'],
        'url' => $_POST['m3u_url'],
        'dns_id' => $_POST['dns_id'],
        'status' => 'active'
    ];
    
    // Try to fetch and count playlists
    if(filter_var($_POST['m3u_url'], FILTER_VALIDATE_URL)){
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $_POST['m3u_url']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $content = curl_exec($ch);
            curl_close($ch);
            
            if($content){
                $playlist_count = substr_count($content, '#EXTINF');
                $m3u_data['playlist_count'] = max(1, $playlist_count);
            }
        } catch (Exception $e) {
            // If error, set default count
            $m3u_data['playlist_count'] = 1;
        }
    }
    
    $db->insert($m3u_table, $m3u_data);
    echo "<script>window.location.href='".$page."?status=m3u_created'</script>";
}

// Delete M3U list
if(isset($_GET['delete_m3u'])){
    $db->delete($m3u_table, 'id = :id',[':id' => $_GET['delete_m3u']]);
    echo "<script>window.location.href='".$page."?status=m3u_deleted'</script>";
}

?>

<!-- Status Messages -->
<?php if(isset($_GET['status'])): ?>
    <div class="container-fluid pt-4 px-4">
        <div class="row g-4">
            <div class="col-12">
                <?php 
                $messages = [
                    'bulk_updated' => '✅ DNS atualizado em massa com sucesso!',
                    'dns_updated' => '✅ DNS atualizado com sucesso!',
                    'dns_created' => '✅ DNS criado com sucesso!',
                    'dns_deleted' => '✅ DNS removido com sucesso!',
                    'm3u_created' => '✅ Lista M3U importada com sucesso!',
                    'm3u_deleted' => '✅ Lista M3U removida com sucesso!'
                ];
                ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <strong><?php echo $messages[$_GET['status']] ?? 'Operação concluída!'; ?></strong>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- DNS Section Start -->
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">🌐 Gerenciador de DNS</h2>
                <h6 class="text-info mb-3">Adicione, edite e gerencie seus servidores DNS</h6>

                <?php if (isset($_GET['create_dns'])): ?>
                    <!-- Create DNS Form -->
                    <form method="post" class="mb-4">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Título do DNS</label>
                                    <input type="text" name="title" class="form-control" placeholder="Ex: DNS Primário" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">URL/IP do DNS</label>
                                    <input type="text" name="url" class="form-control" placeholder="Ex: http://servidor.com" required>
                                </div>
                            </div>
                        </div>
                        <button type="submit" name="submit_dns" class="btn btn-primary">Salvar DNS</button>
                        <a href="<?php echo $page; ?>" class="btn btn-secondary">Cancelar</a>
                    </form>
                <?php elseif (isset($_GET['update_dns'])): ?>
                    <!-- Update DNS Form -->
                    <form method="post" class="mb-4">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Título do DNS</label>
                                    <input type="text" name="title" class="form-control" value="<?=$dnsUpdate[0]['title']; ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">URL/IP do DNS</label>
                                    <input type="text" name="url" class="form-control" value="<?=$dnsUpdate[0]['url']; ?>" required>
                                </div>
                            </div>
                        </div>
                        <button type="submit" name="submitU" class="btn btn-primary">Atualizar DNS</button>
                        <a href="<?php echo $page; ?>" class="btn btn-secondary">Cancelar</a>
                    </form>
                <?php elseif (isset($_GET['bulk_dns'])): ?>
                    <!-- Bulk DNS Update Form -->
                    <form method="post" class="mb-4">
                        <h5 class="mb-3">🔄 Atualizar DNS em Massa</h5>
                        <div class="mb-3">
                            <label class="form-label">Selecione os DNS</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="select_all" onchange="toggleAll(this)">
                                <label class="form-check-label" for="select_all">
                                    <strong>Selecionar Tudo</strong>
                                </label>
                            </div>
                            <?php foreach($dns_res as $dns): ?>
                                <div class="form-check">
                                    <input class="form-check-input dns-checkbox" type="checkbox" name="dns_ids[]" 
                                           value="<?=$dns['id']; ?>" id="dns_<?=$dns['id']; ?>">
                                    <label class="form-check-label" for="dns_<?=$dns['id']; ?>">
                                        <?=$dns['title']; ?> (<?=$dns['url']; ?>)
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Novo DNS/URL</label>
                            <input type="text" name="bulk_dns_url" class="form-control" 
                                   placeholder="Digite o novo DNS/URL para todos selecionados" required>
                            <small class="text-info">Este URL será aplicado a todos os DNS selecionados acima</small>
                        </div>
                        <button type="submit" name="bulk_dns_update" class="btn btn-warning" 
                                onclick="return confirm('Tem certeza? Isso atualizará todos os DNS selecionados!')">
                            Atualizar em Massa
                        </button>
                        <a href="<?php echo $page; ?>" class="btn btn-secondary">Cancelar</a>
                    </form>
                <?php else: ?>
                    <!-- DNS List -->
                    <div class="text-end mb-3">
                        <a href="<?php echo $page; ?>?create_dns" class="btn btn-primary m-2">
                            <i class="fa fa-plus"></i> Novo DNS
                        </a>
                        <?php if(count($dns_res) > 1): ?>
                        <a href="<?php echo $page; ?>?bulk_dns" class="btn btn-warning m-2">
                            <i class="fa fa-pencil"></i> Atualizar em Massa
                        </a>
                        <?php endif; ?>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Título</th>
                                    <th>DNS/URL</th>
                                    <th>Listas M3U</th>
                                    <th>Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($dns_res)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center text-muted">Nenhum DNS configurado</td>
                                    </tr>
                                <?php else:
                                    foreach ($dns_res as $row):
                                        $m3u_count = count(array_filter($m3u_res, function($m) use ($row) {
                                            return $m['dns_id'] == $row['id'];
                                        }));
                                ?>
                                    <tr>
                                        <td><?=$row['id']; ?></td>
                                        <td><strong><?=$row['title']; ?></strong></td>
                                        <td><code><?=$row['url']; ?></code></td>
                                        <td><span class="badge bg-info"><?=$m3u_count; ?></span></td>
                                        <td>
                                            <a class="btn btn-square btn-sm btn-success" href="<?php echo $page; ?>?update_dns=<?php echo $row['id']; ?>">
                                                <i class="fa fa-pencil"></i>
                                            </a>
                                            <a class="btn btn-square btn-sm btn-danger" href="<?php echo $page; ?>?delete_dns=<?php echo $row['id']; ?>"
                                               onclick="return confirm('Tem certeza? Isso também removerá as listas M3U associadas!')">
                                                <i class="fa fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php
                                    endforeach;
                                endif; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<!-- DNS Section End -->

<!-- M3U Section Start -->
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">📺 Gerenciador de Listas M3U</h2>
                <h6 class="text-info mb-3">Importe e gerencie suas listas de reprodução M3U</h6>

                <?php if (isset($_GET['add_m3u'])): ?>
                    <!-- Add M3U Form -->
                    <form method="post" class="mb-4">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Título da Lista M3U</label>
                                    <input type="text" name="m3u_title" class="form-control" 
                                           placeholder="Ex: Canais Premium" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">DNS Associado</label>
                                    <select name="dns_id" class="form-select" required>
                                        <option value="">Selecione um DNS</option>
                                        <?php foreach($dns_res as $dns): ?>
                                            <option value="<?=$dns['id']; ?>"><?=$dns['title']; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">URL da Lista M3U</label>
                            <input type="url" name="m3u_url" class="form-control" 
                                   placeholder="http://exemplo.com/lista.m3u" required>
                            <small class="text-info">URL completa do arquivo M3U para importação</small>
                        </div>
                        <button type="submit" name="submit_m3u" class="btn btn-primary">Importar Lista M3U</button>
                        <a href="<?php echo $page; ?>" class="btn btn-secondary">Cancelar</a>
                    </form>
                <?php else: ?>
                    <!-- M3U List -->
                    <div class="text-end mb-3">
                        <a href="<?php echo $page; ?>?add_m3u" class="btn btn-primary m-2">
                            <i class="fa fa-plus"></i> Adicionar Lista M3U
                        </a>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Título</th>
                                    <th>DNS</th>
                                    <th>URL</th>
                                    <th>Canais</th>
                                    <th>Data Importação</th>
                                    <th>Status</th>
                                    <th>Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($m3u_res)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center text-muted">Nenhuma lista M3U importada</td>
                                    </tr>
                                <?php else:
                                    foreach ($m3u_res as $row):
                                        $dns_name = 'N/A';
                                        foreach($dns_res as $dns) {
                                            if($dns['id'] == $row['dns_id']) {
                                                $dns_name = $dns['title'];
                                                break;
                                            }
                                        }
                                ?>
                                    <tr>
                                        <td><?=$row['id']; ?></td>
                                        <td><strong><?=$row['title']; ?></strong></td>
                                        <td><span class="badge bg-secondary"><?=$dns_name; ?></span></td>
                                        <td><code class="text-truncate" style="max-width:200px;"><?=$row['url']; ?></code></td>
                                        <td><span class="badge bg-info"><?=$row['playlist_count']; ?></span></td>
                                        <td><?=date('d/m/Y H:i', strtotime($row['import_date'])); ?></td>
                                        <td>
                                            <?php if($row['status'] == 'active'): ?>
                                                <span class="badge bg-success">Ativo</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">Inativo</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a class="btn btn-square btn-sm btn-danger" href="<?php echo $page; ?>?delete_m3u=<?php echo $row['id']; ?>"
                                               onclick="return confirm('Tem certeza que deseja remover esta lista?')">
                                                <i class="fa fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php
                                    endforeach;
                                endif; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<!-- M3U Section End -->

<script>
function toggleAll(checkbox) {
    const checkboxes = document.querySelectorAll('.dns-checkbox');
    checkboxes.forEach(cb => cb.checked = checkbox.checked);
}
</script>

<!-- Footer Start -->
<?php include ('includes/footer.php');?>
<!-- Footer End -->
</body>
</html>
