<?php
/**
 * M3U IPTV Lists & DNS Manager
 * Compatible: PHP 7.0+ (including 8.0, 8.1, 8.2, 8.3, 8.4)
 * cPanel Ready
 * 
 * Funcionalidades:
 * - Gerenciar listas M3U IPTV
 * - Configurar DNS por lista
 * - Trocar DNS em massa
 * - Associar a Mac devices
 */

declare(strict_types=1);

include('includes/header.php');

// Constantes
const PAGE_NAME = 'm3u_manager.php';
const TABLE_M3U = 'm3u_lists';
const TABLE_DNS = 'dns';
const DEFAULT_DNS_PRIMARY = '8.8.8.8';
const DEFAULT_DNS_SECONDARY = '8.8.4.4';

// ===== Funções Utilitárias (PHP 8.4 Compatible) =====

function sanitize_string(mixed $value): string {
    if (!is_string($value)) {
        $value = strval($value);
    }
    return htmlspecialchars(strip_tags(trim($value)), ENT_QUOTES, 'UTF-8');
}

function is_valid_dns(string $dns): bool {
    return filter_var($dns, FILTER_VALIDATE_IP) !== false;
}

function is_valid_m3u_url(string $url): bool {
    $parsed = filter_var($url, FILTER_VALIDATE_URL);
    return $parsed !== false && (str_ends_with($url, '.m3u') || str_ends_with($url, '.m3u8'));
}

// ===== Criação de Tabelas =====

function create_m3u_table(): void {
    global $db;
    try {
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_M3U . " (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            url TEXT NOT NULL,
            dns_primary TEXT DEFAULT '" . DEFAULT_DNS_PRIMARY . "',
            dns_secondary TEXT DEFAULT '" . DEFAULT_DNS_SECONDARY . "',
            mac_address TEXT,
            device_name TEXT,
            import_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            status TEXT DEFAULT 'active',
            playlist_count INTEGER DEFAULT 0
        )";
        @$db->db->exec($sql);
    } catch (Throwable $e) {
        error_log("create_m3u_table error: " . $e->getMessage());
    }
}

// ===== CRUD Operations =====

function get_all_m3u_lists(): array {
    global $db;
    try {
        create_m3u_table();
        $result = $db->select(TABLE_M3U, '*', '', 'import_date DESC');
        return $result ?? [];
    } catch (Throwable $e) {
        error_log("get_all_m3u_lists error: " . $e->getMessage());
        return [];
    }
}

function get_m3u_by_id(int $id): ?array {
    global $db;
    try {
        create_m3u_table();
        $result = $db->select(TABLE_M3U, '*', 'id = :id', '', [':id' => $id]);
        return $result[0] ?? null;
    } catch (Throwable $e) {
        error_log("get_m3u_by_id error: " . $e->getMessage());
        return null;
    }
}

function add_m3u_list(string $title, string $url, string $mac_address = '', 
                      string $device_name = '', string $dns_primary = DEFAULT_DNS_PRIMARY,
                      string $dns_secondary = DEFAULT_DNS_SECONDARY): array {
    global $db;
    
    try {
        create_m3u_table();
        
        // Validar entrada
        $title = sanitize_string($title);
        $device_name = sanitize_string($device_name);
        $mac_address = sanitize_string($mac_address);
        
        if (empty($title) || empty($url)) {
            return ['status' => 'error', 'message' => 'Título e URL são obrigatórios'];
        }
        
        if (!is_valid_m3u_url($url)) {
            return ['status' => 'error', 'message' => 'URL deve terminar com .m3u ou .m3u8'];
        }
        
        // Validar DNS
        if (!empty($dns_primary) && !is_valid_dns($dns_primary)) {
            return ['status' => 'error', 'message' => 'DNS primário inválido'];
        }
        
        if (!empty($dns_secondary) && !is_valid_dns($dns_secondary)) {
            return ['status' => 'error', 'message' => 'DNS secundário inválido'];
        }
        
        $insertData = [
            'title' => $title,
            'url' => $url,
            'dns_primary' => sanitize_string($dns_primary),
            'dns_secondary' => sanitize_string($dns_secondary),
            'mac_address' => $mac_address,
            'device_name' => $device_name,
            'import_date' => date('Y-m-d H:i:s'),
            'updated_date' => date('Y-m-d H:i:s'),
            'status' => 'active'
        ];
        
        $db->insert(TABLE_M3U, $insertData);
        $id = $db->getLastInsertId();
        
        return [
            'status' => 'success',
            'message' => 'Lista M3U adicionada com sucesso',
            'id' => $id
        ];
    } catch (Throwable $e) {
        error_log("add_m3u_list error: " . $e->getMessage());
        return ['status' => 'error', 'message' => 'Erro ao adicionar lista'];
    }
}

function update_m3u_list(int $id, array $data): array {
    global $db;
    
    try {
        create_m3u_table();
        
        // Sanitizar dados
        foreach ($data as $key => $value) {
            if (is_string($value)) {
                $data[$key] = sanitize_string($value);
            }
        }
        
        $data['updated_date'] = date('Y-m-d H:i:s');
        
        $db->update(TABLE_M3U, $data, 'id = :id', [':id' => $id]);
        
        return [
            'status' => 'success',
            'message' => 'Lista M3U atualizada com sucesso'
        ];
    } catch (Throwable $e) {
        error_log("update_m3u_list error: " . $e->getMessage());
        return ['status' => 'error', 'message' => 'Erro ao atualizar lista'];
    }
}

function delete_m3u_list(int $id): array {
    global $db;
    
    try {
        create_m3u_table();
        $db->delete(TABLE_M3U, 'id = :id', [':id' => $id]);
        return ['status' => 'success', 'message' => 'Lista M3U deletada com sucesso'];
    } catch (Throwable $e) {
        error_log("delete_m3u_list error: " . $e->getMessage());
        return ['status' => 'error', 'message' => 'Erro ao deletar lista'];
    }
}

function bulk_update_dns(array $list_ids, string $dns_primary, string $dns_secondary): array {
    global $db;
    
    try {
        create_m3u_table();
        
        if (empty($list_ids)) {
            return ['status' => 'error', 'message' => 'Nenhuma lista selecionada'];
        }
        
        // Validar DNS
        if (!is_valid_dns($dns_primary)) {
            return ['status' => 'error', 'message' => 'DNS primário inválido'];
        }
        
        if (!is_valid_dns($dns_secondary)) {
            return ['status' => 'error', 'message' => 'DNS secundário inválido'];
        }
        
        $dns_primary = sanitize_string($dns_primary);
        $dns_secondary = sanitize_string($dns_secondary);
        
        $updated_count = 0;
        foreach ($list_ids as $list_id) {
            $list_id = intval($list_id);
            $updateData = [
                'dns_primary' => $dns_primary,
                'dns_secondary' => $dns_secondary,
                'updated_date' => date('Y-m-d H:i:s')
            ];
            
            $db->update(TABLE_M3U, $updateData, 'id = :id', [':id' => $list_id]);
            $updated_count++;
        }
        
        return [
            'status' => 'success',
            'message' => "DNS atualizado para {$updated_count} lista(s)",
            'count' => $updated_count
        ];
    } catch (Throwable $e) {
        error_log("bulk_update_dns error: " . $e->getMessage());
        return ['status' => 'error', 'message' => 'Erro ao atualizar DNS'];
    }
}

// ===== Processamento de Requisições POST/GET =====

$status = '';
$message = '';
$message_type = 'info';

// Ação: Criar nova lista
if (isset($_GET['action']) && $_GET['action'] === 'create' && isset($_POST['create_m3u'])) {
    $result = add_m3u_list(
        $_POST['title'] ?? '',
        $_POST['url'] ?? '',
        $_POST['mac_address'] ?? '',
        $_POST['device_name'] ?? '',
        $_POST['dns_primary'] ?? DEFAULT_DNS_PRIMARY,
        $_POST['dns_secondary'] ?? DEFAULT_DNS_SECONDARY
    );
    
    if ($result['status'] === 'success') {
        header("Location: " . PAGE_NAME . "?status=created");
        exit;
    } else {
        $status = 'error';
        $message = $result['message'];
        $message_type = 'danger';
    }
}

// Ação: Atualizar lista
if (isset($_GET['edit']) && isset($_POST['update_m3u'])) {
    $result = update_m3u_list(
        intval($_GET['edit']),
        [
            'title' => $_POST['title'] ?? '',
            'url' => $_POST['url'] ?? '',
            'mac_address' => $_POST['mac_address'] ?? '',
            'device_name' => $_POST['device_name'] ?? '',
            'dns_primary' => $_POST['dns_primary'] ?? DEFAULT_DNS_PRIMARY,
            'dns_secondary' => $_POST['dns_secondary'] ?? DEFAULT_DNS_SECONDARY,
            'status' => $_POST['status'] ?? 'active'
        ]
    );
    
    if ($result['status'] === 'success') {
        header("Location: " . PAGE_NAME . "?status=updated");
        exit;
    } else {
        $status = 'error';
        $message = $result['message'];
        $message_type = 'danger';
    }
}

// Ação: Deletar lista
if (isset($_GET['delete'])) {
    $result = delete_m3u_list(intval($_GET['delete']));
    header("Location: " . PAGE_NAME . "?status=deleted");
    exit;
}

// Ação: Atualizar DNS em massa
if (isset($_POST['bulk_update_dns'])) {
    $list_ids = array_map('intval', $_POST['list_ids'] ?? []);
    $result = bulk_update_dns(
        $list_ids,
        $_POST['dns_primary'] ?? DEFAULT_DNS_PRIMARY,
        $_POST['dns_secondary'] ?? DEFAULT_DNS_SECONDARY
    );
    
    if ($result['status'] === 'success') {
        header("Location: " . PAGE_NAME . "?status=dns_updated");
        exit;
    } else {
        $status = 'error';
        $message = $result['message'];
        $message_type = 'danger';
    }
}

// Ação: Atualizar todos os DNS
if (isset($_POST['update_all_dns'])) {
    $all_lists = get_all_m3u_lists();
    $list_ids = array_column($all_lists, 'id');
    $result = bulk_update_dns(
        $list_ids,
        $_POST['dns_primary'] ?? DEFAULT_DNS_PRIMARY,
        $_POST['dns_secondary'] ?? DEFAULT_DNS_SECONDARY
    );
    
    if ($result['status'] === 'success') {
        header("Location: " . PAGE_NAME . "?status=all_dns_updated");
        exit;
    } else {
        $status = 'error';
        $message = $result['message'];
        $message_type = 'danger';
    }
}

// Processar status GET parameter
$status_param = $_GET['status'] ?? '';
$status_messages = [
    'created' => ['msg' => 'Lista M3U criada com sucesso!', 'type' => 'success'],
    'updated' => ['msg' => 'Lista M3U atualizada com sucesso!', 'type' => 'success'],
    'deleted' => ['msg' => 'Lista M3U deletada com sucesso!', 'type' => 'success'],
    'dns_updated' => ['msg' => 'DNS atualizado para as listas selecionadas!', 'type' => 'success'],
    'all_dns_updated' => ['msg' => 'DNS atualizado para TODAS as listas!', 'type' => 'success'],
];

if (!empty($status_param) && isset($status_messages[$status_param])) {
    $message = $status_messages[$status_param]['msg'];
    $message_type = $status_messages[$status_param]['type'];
}

// Obter dados
$m3u_lists = get_all_m3u_lists();
$edit_id = isset($_GET['edit']) ? intval($_GET['edit']) : null;
$edit_data = $edit_id ? get_m3u_by_id($edit_id) : null;
$show_create = isset($_GET['action']) && $_GET['action'] === 'create' && !isset($_POST['create_m3u']);

?>

<!-- M3U Lists Manager UI -->
<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">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2 class="mb-0"><i class="fa fa-list"></i> Gerenciador de Listas IPTV M3U</h2>
                        <p class="text-muted mb-0 mt-2">Total: <strong><?= count($m3u_lists) ?></strong> lista(s)</p>
                    </div>
                    <a href="<?= PAGE_NAME ?>?action=create" class="btn btn-primary">
                        <i class="fa fa-plus"></i> Nova Lista
                    </a>
                </div>

                <!-- Status Message -->
                <?php if (!empty($message)): ?>
                    <div class="alert alert-<?= $message_type ?> alert-dismissible fade show" role="alert">
                        <i class="fa fa-<?= $message_type === 'success' ? 'check-circle' : 'exclamation-circle' ?>"></i>
                        <?= htmlspecialchars($message) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Aba de Navegação -->
                <ul class="nav nav-tabs mb-4" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link <?= !$show_create && !$edit_id ? 'active' : '' ?>" 
                           href="<?= PAGE_NAME ?>" role="tab">
                            <i class="fa fa-table"></i> Listas
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?= $show_create ? 'active' : '' ?>" 
                           href="<?= PAGE_NAME ?>?action=create" role="tab">
                            <i class="fa fa-plus"></i> Criar Nova
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#bulk-dns" data-bs-toggle="tab" role="tab">
                            <i class="fa fa-cog"></i> Atualizar DNS
                        </a>
                    </li>
                </ul>

                <!-- Conteúdo Dinâmico -->
                <div class="tab-content">
                    <!-- Criar Nova Lista -->
                    <?php if ($show_create): ?>
                        <?php include 'includes/m3u/form_create.php'; ?>
                    <?php endif; ?>

                    <!-- Editar Lista -->
                    <?php if ($edit_id && $edit_data): ?>
                        <?php include 'includes/m3u/form_edit.php'; ?>
                    <?php endif; ?>

                    <!-- Tabela de Listas -->
                    <?php if (!$show_create && !$edit_id): ?>
                        <?php include 'includes/m3u/table_lists.php'; ?>
                    <?php endif; ?>

                    <!-- Bulk DNS Update -->
                    <div class="tab-pane fade" id="bulk-dns" role="tabpanel">
                        <?php include 'includes/m3u/bulk_dns.php'; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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