<?php
require_once __DIR__ . '/auth.php';
header('Location: pages/channels.php');
exit;
// Database connection
$host = 'localhost';
$dbname = 'yaetfswo_digital';
$username = 'yaetfswo_digital';
$password = 'et.8PJ9ikUnuVG2';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Create tables if they don't exist
$pdo->exec("CREATE TABLE IF NOT EXISTS categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL UNIQUE
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS channels (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    uri VARCHAR(255) NOT NULL,
    category_id INT,
    logo VARCHAR(255),
    drm_scheme VARCHAR(50),
    drm_license_uri VARCHAR(255),
    headers TEXT,
    webview ENUM('yes', 'no') DEFAULT 'no',
    isMagis TINYINT(1) DEFAULT 0,
    default_KID VARCHAR(255),
    FOREIGN KEY (category_id) REFERENCES categories(id)
)");

// Ensure adultos column exists
try {
    $pdo->exec("ALTER TABLE channels ADD COLUMN adultos TINYINT(1) DEFAULT 0");
} catch (PDOException $e) {
    // ignore if already exists
}

// Initialize variables
$success_message = '';
$error_message = '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$items_per_page = 10;
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // --- Gestión de categorías ---
    if (isset($_POST['add_category']) && !empty($_POST['new_category'])) {
        $newCat = trim($_POST['new_category']);
        try {
            $stmt = $pdo->prepare("INSERT IGNORE INTO categories (name) VALUES (?)");
            $stmt->execute([$newCat]);
            $success_message = "Category added!";
        } catch (PDOException $e) {
            $error_message = "Error: " . $e->getMessage();
        }
    }
    if (isset($_POST['edit_category'], $_POST['category_id'], $_POST['edit_category_name'])) {
        $catId = (int)$_POST['category_id'];
        $catName = trim($_POST['edit_category_name']);
        try {
            $stmt = $pdo->prepare("UPDATE categories SET name=? WHERE id=?");
            $stmt->execute([$catName, $catId]);
            $success_message = "Category updated!";
        } catch (PDOException $e) {
            $error_message = "Error: " . $e->getMessage();
        }
    }
    if (isset($_POST['delete_category'], $_POST['category_id'])) {
        $catId = (int)$_POST['category_id'];
        try {
            // Opcional: eliminar canales de la categoría antes
            $stmt = $pdo->prepare("DELETE FROM channels WHERE category_id=?");
            $stmt->execute([$catId]);
            $stmt = $pdo->prepare("DELETE FROM categories WHERE id=?");
            $stmt->execute([$catId]);
            $success_message = "Category deleted!";
        } catch (PDOException $e) {
            $error_message = "Error: " . $e->getMessage();
        }
    }
    // --- Eliminación múltiple de canales ---
    if (isset($_POST['delete_selected']) && !empty($_POST['selected_channels']) && is_array($_POST['selected_channels'])) {
        $ids = array_map('intval', $_POST['selected_channels']);
        $in = str_repeat('?,', count($ids) - 1) . '?';
        try {
            $stmt = $pdo->prepare("DELETE FROM channels WHERE id IN ($in)");
            $stmt->execute($ids);
            $success_message = "Selected channels deleted!";
        } catch (PDOException $e) {
            $error_message = "Error: " . $e->getMessage();
        }
    }

    if (isset($_POST['add_channel'])) {
        $name = strtoupper(trim($_POST['name']));
        $uri = trim($_POST['uri']);
        $category = strtoupper(trim($_POST['category']));
        $logo = trim($_POST['logo']);
        $drm_type = trim($_POST['drm_type']);
        $default_KID = trim($_POST['default_KID']) ?: null;
        $headers = [];

        if (isset($_POST['headers']) && is_array($_POST['headers'])) {
            foreach ($_POST['headers'] as $header) {
                if (!empty($header['key']) && !empty($header['value'])) {
                    $headers[$header['key']] = $header['value'];
                }
            }
        }

        $headers_json = json_encode($headers);
        $webview = isset($_POST['webview']) && $_POST['webview'] === 'yes' ? 'yes' : 'no';
        $isMagis = isset($_POST['isMagis']) && $_POST['isMagis'] === '1' ? 1 : 0;
        $adultos = isset($_POST['adultos']) && $_POST['adultos'] === '1' ? 1 : 0;

        try {
            $pdo->beginTransaction();
            
            $stmt = $pdo->prepare("INSERT IGNORE INTO categories (name) VALUES (?)");
            $stmt->execute([$category]);

            $stmt = $pdo->prepare("SELECT id FROM categories WHERE name = ?");
            $stmt->execute([$category]);
            $category_id = $stmt->fetchColumn();

            $drm_scheme = null;
            $drm_license_uri = null;
            if ($drm_type === 'clearkey') {
                $drm_scheme = 'clearkey';
                $key_pair = trim($_POST['key_pair']);
                // Si es formato keyid:key, automatizar request
                if (preg_match('/^([a-fA-F0-9]{32}):([a-fA-F0-9]{32})$/', $key_pair, $matches)) {
                    $keyid = $matches[1];
                    $key = $matches[2];
                    $api_url = "https://vercel-php-clearkey-hex-base64-json.vercel.app/api/results.php?keyid=$keyid&key=$key";
                    $api_response = @file_get_contents($api_url);
                    if ($api_response !== false) {
                        $drm_license_uri = $api_response;
                    } else {
                        $drm_license_uri = '';
                    }
                } else {
                    $drm_license_uri = $key_pair;
                }
            } elseif ($drm_type === 'widevine') {
                $drm_scheme = 'widevine';
                $drm_license_uri = trim($_POST['drm_license_uri']);
            }

            $stmt = $pdo->prepare("INSERT INTO channels (name, uri, category_id, logo, drm_scheme, drm_license_uri, headers, webview, isMagis, default_KID, adultos) 
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $uri, $category_id, $logo, $drm_scheme, $drm_license_uri, $headers_json, $webview, $isMagis, $default_KID, $adultos]);
            
            $pdo->commit();
            $success_message = "Channel added successfully!";
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error_message = "Error: " . $e->getMessage();
        }
    }

    if (isset($_POST['update_channel'])) {
        $channel_id = (int)$_POST['channel_id'];
        $name = strtoupper(trim($_POST['name']));
        $uri = trim($_POST['uri']);
        $category = strtoupper(trim($_POST['category']));
        $logo = trim($_POST['logo']) ?: null;
        $drm_scheme = trim($_POST['drm_scheme']) ?: null;
        $drm_license_uri = trim($_POST['drm_license_uri']) ?: null;
        $webview = isset($_POST['webview']) && $_POST['webview'] === 'yes' ? 'yes' : 'no';
        $isMagis = isset($_POST['isMagis']) && $_POST['isMagis'] === '1' ? 1 : 0;
        $default_KID = trim($_POST['default_KID']) ?: null;

        $headers = [];
        if (isset($_POST['headers']) && is_array($_POST['headers'])) {
            foreach ($_POST['headers'] as $header) {
                if (!empty($header['key']) && !empty($header['value'])) {
                    $headers[$header['key']] = $header['value'];
                }
            }
        }
        $headers_json = json_encode($headers);
        $adultos = isset($_POST['adultos']) && $_POST['adultos'] === '1' ? 1 : 0;

        try {
            $pdo->beginTransaction();
            
            $stmt = $pdo->prepare("INSERT IGNORE INTO categories (name) VALUES (?)");
            $stmt->execute([$category]);

            $stmt = $pdo->prepare("SELECT id FROM categories WHERE name = ?");
            $stmt->execute([$category]);
            $category_id = $stmt->fetchColumn();

            $stmt = $pdo->prepare("UPDATE channels SET 
                name = ?, 
                uri = ?, 
                category_id = ?, 
                logo = ?, 
                drm_scheme = ?, 
                drm_license_uri = ?, 
                headers = ?,
                webview = ?,
                isMagis = ?,
                default_KID = ?,
                adultos = ?
                WHERE id = ?");
            $stmt->execute([
                $name,
                $uri,
                $category_id,
                $logo,
                $drm_scheme,
                $drm_license_uri,
                $headers_json,
                $webview,
                $isMagis,
                $default_KID,
                $adultos,
                $channel_id
            ]);
            
            $pdo->commit();
            $success_message = "Channel updated successfully!";
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error_message = "Error: " . $e->getMessage();
        }
    }

    if (isset($_POST['delete_channel'])) {
        try {
            $stmt = $pdo->prepare("DELETE FROM channels WHERE id = ?");
            $stmt->execute([$_POST['channel_id']]);
            $success_message = "Channel deleted successfully!";
        } catch (PDOException $e) {
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Handle AJAX requests for editing
if (isset($_GET['action']) && $_GET['action'] === 'get_channel' && isset($_GET['id'])) {
    $channel_id = (int)$_GET['id'];
    $stmt = $pdo->prepare("
        SELECT channels.*, categories.name as category_name 
        FROM channels 
        LEFT JOIN categories ON channels.category_id = categories.id 
        WHERE channels.id = ?
    ");
    $stmt->execute([$channel_id]);
    $channel = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($channel) {
        header('Content-Type: application/json');
        echo json_encode($channel);
    } else {
        header('HTTP/1.1 404 Not Found');
    }
    exit;
}

// Fetch only necessary data for initial page load
$categories = $pdo->query("SELECT * FROM categories ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Count total channels for pagination
$count_sql = "SELECT COUNT(*) FROM channels";
$search_params = [];

if (!empty($search)) {
    $count_sql .= " WHERE name LIKE ? OR uri LIKE ?";
    $search_params[] = "%$search%";
    $search_params[] = "%$search%";
}

$stmt = $pdo->prepare($count_sql);
$stmt->execute($search_params);
$total_items = $stmt->fetchColumn();
$total_pages = ceil($total_items / $items_per_page);

// Fetch channels with pagination and search
$sql = "
    SELECT channels.id, channels.name, channels.uri, channels.logo, 
           channels.drm_scheme, channels.default_KID, categories.name as category_name,
           channels.webview, channels.isMagis, channels.adultos
    FROM channels 
    LEFT JOIN categories ON channels.category_id = categories.id 
";

if (!empty($search)) {
    $sql .= " WHERE channels.name LIKE ? OR channels.uri LIKE ?";
}

$sql .= " ORDER BY categories.name, channels.name";
$sql .= " LIMIT " . (($page - 1) * $items_per_page) . ", " . $items_per_page;

$stmt = $pdo->prepare($sql);

if (!empty($search)) {
    $stmt->execute(["%$search%", "%$search%"]);
} else {
    $stmt->execute();
}

$channels = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Channel Manager</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background: #f5f7fa;
            padding: 2rem;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }
        
        .title {
            font-size: 2rem;
            color: #2d3748;
        }
        
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #4a5568;
        }
        
        .form-control {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            font-size: 1rem;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #4299e1;
            box-shadow: 0 0 0 3px rgba(66,153,225,0.5);
        }
        
        .btn {
            padding: 0.5rem 1rem;
            border-radius: 4px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            transition: background-color 0.2s;
        }
        
        .btn-primary {
            background: #4299e1;
            color: white;
        }
        
        .btn-primary:hover {
            background: #3182ce;
        }
        
        .btn-danger {
            background: #f56565;
            color: white;
        }
        
        .btn-danger:hover {
            background: #e53e3e;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }
        
        th {
            background: #f7fafc;
            font-weight: 600;
            color: #4a5568;
        }
        
        tr:hover {
            background: #f7fafc;
        }
        
        .logo-img {
            width: 40px;
            height: 40px;
            object-fit: cover;
            border-radius: 4px;
        }
        
        .badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
            background: #ebf8ff;
            color: #2b6cb0;
        }
        
        .headers-container {
            margin-top: 1rem;
        }
        
        .header-row {
            display: flex;
            gap: 1rem;
            margin-bottom: 0.5rem;
        }
        
        .search-box {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            margin-bottom: 1rem;
            font-size: 1rem;
        }
        
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 1rem;
        }
        @media (max-width: 640px) {
            .header { flex-direction: column; align-items: flex-start; gap: .5rem; }
            .title { font-size: 1.5rem; }
            body { padding: 1rem; }
            table { font-size: .95rem; }
        }
        .uri-cell { max-width: 360px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .badge-adult { background:#FED7D7; color:#9B2C2C; }
        .switch { position: relative; display: inline-block; width: 46px; height: 24px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #cbd5e0; transition: .2s; border-radius: 24px; }
        .slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px; background-color: white; transition: .2s; border-radius: 50%; }
        input:checked + .slider { background-color: #48bb78; }
        input:checked + .slider:before { transform: translateX(22px); }

        #editModal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            overflow: auto;
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            width: 80%;
            max-width: 800px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e2e8f0;
            padding-bottom: 1rem;
            margin-bottom: 1rem;
        }

        .close {
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
        }

        .alert {
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 4px;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 2rem;
        }

        .pagination a, .pagination span {
            display: inline-block;
            padding: 0.5rem 1rem;
            margin: 0 0.25rem;
            border-radius: 4px;
            text-decoration: none;
            background: #4299e1;
            color: white;
        }

        .pagination .current {
            background: #2b6cb0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 class="title">Channel Manager</h1>
        </div>

        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success"><?= htmlspecialchars($success_message) ?></div>
        <?php endif; ?>

        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error_message) ?></div>
        <?php endif; ?>

        <div class="card">
            <h2>Manage Categories</h2>
            <form method="POST" id="addCategoryForm" style="margin-bottom:1rem;">
                <input type="text" name="new_category" placeholder="New category name" required class="form-control" style="width:auto;display:inline-block;">
                <button type="submit" name="add_category" class="btn btn-primary">Add Category</button>
            </form>
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $cat): ?>
                        <tr>
                            <form method="POST" style="display:inline;">
                                <td>
                                    <input type="text" name="edit_category_name" value="<?= htmlspecialchars($cat['name']) ?>" class="form-control" style="width:auto;display:inline-block;">
                                    <input type="hidden" name="category_id" value="<?= $cat['id'] ?>">
                                </td>
                                <td>
                                    <button type="submit" name="edit_category" class="btn btn-primary">Edit</button>
                                    <button type="submit" name="delete_category" class="btn btn-danger" onclick="return confirm('Delete this category?')">Delete</button>
                                </td>
                            </form>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="card">
            <h2>Add New Channel</h2>
            <form method="POST" class="form">
                <div class="grid">
                    <div class="form-group">
                        <label class="form-label">Channel Name *</label>
                        <input type="text" name="name" required class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Category *</label>
                        <input type="text" name="category" list="categories" required class="form-control">
                        <datalist id="categories">
                            <?php foreach ($categories as $category): ?>
                                <option value="<?= htmlspecialchars($category['name']) ?>">
                            <?php endforeach; ?>
                        </datalist>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Stream URI *</label>
                        <input type="url" name="uri" required class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Logo URL</label>
                        <input type="url" name="logo" class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">DRM Type</label>
                        <select name="drm_type" class="form-control" id="drmType">
                            <option value="">None</option>
                            <option value="clearkey">ClearKey</option>
                            <option value="widevine">Widevine</option>
                        </select>
                    </div>

                    <div class="form-group" id="clearkeyInput" style="display: none;">
                        <label class="form-label">KeyID:Key *</label>
                        <input type="text" name="key_pair" class="form-control" placeholder="keyid:key">
                    </div>

                    <div class="form-group" id="widevineInput" style="display: none;">
                        <label class="form-label">DRM License URI *</label>
                        <input type="url" name="drm_license_uri" class="form-control" placeholder="https://license.example.com">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Default KID</label>
                        <input type="text" name="default_KID" class="form-control" placeholder="Enter default KID">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Webview</label>
                        <select name="webview" class="form-control">
                            <option value="no">Disable</option>
                            <option value="yes">Enable</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Is Magis</label>
                        <select name="isMagis" class="form-control">
                            <option value="0">No</option>
                            <option value="1">Yes</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Contenido adulto</label><br>
                        <label class="switch">
                            <input type="checkbox" name="adultos" value="1">
                            <span class="slider"></span>
                        </label>
                    </div>
                </div>

                <div class="headers-container">
                    <label class="form-label">Custom Headers</label>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="useFlowHeaders"> Usar headers Flow
                        </label>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="useClaroHeaders"> Usar headers Clarovideo
                        </label>
                    </div>
                    <div id="headersContainer">
                        <div class="header-row">
                            <input type="text" name="headers[0][key]" placeholder="Header Key" class="form-control">
                            <input type="text" name="headers[0][value]" placeholder="Header Value" class="form-control">
                            <button type="button" class="btn btn-danger remove-header">Remove</button>
                        </div>
                    </div>
                    <button type="button" class="btn btn-primary" id="addHeader">Add Header</button>
                </div>

                <div style="margin-top: 1rem;">
                    <button type="submit" name="add_channel" class="btn btn-primary">Add Channel</button>
                </div>
            </form>
        </div>

        <div class="card">
            <form method="GET" action="">
                <div style="display: flex; gap: 1rem; margin-bottom: 1rem;">
                    <input type="text" name="search" placeholder="Search channels..." class="search-box" value="<?= htmlspecialchars($search) ?>">
                    <button type="submit" class="btn btn-primary">Search</button>
                    <?php if (!empty($search)): ?>
                        <a href="panel.php" class="btn btn-danger">Clear</a>
                    <?php endif; ?>
                </div>
            </form>

            <form method="POST" id="multiDeleteForm">
                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;">
                    <span style="font-weight:600;font-size:1.1rem;">Lista de Canales</span>
                    <button type="submit" name="delete_selected" class="btn btn-danger" onclick="return confirm('¿Eliminar los canales seleccionados?')">Eliminar Seleccionados</button>
                </div>
                <div style="overflow-x:auto;">
                <table style="min-width:900px;border-radius:8px;overflow:hidden;">
                    <thead style="position:sticky;top:0;z-index:2;">
                        <tr>
                            <th style="background:#f7fafc;"><input type="checkbox" id="selectAllChannels"></th>
                            <th style="background:#f7fafc;">Logo</th>
                            <th style="background:#f7fafc;">Nombre</th>
                            <th style="background:#f7fafc;">Categoría</th>
                            <th style="background:#f7fafc;">URI</th>
                            <th style="background:#f7fafc;">DRM</th>
                            <th style="background:#f7fafc;">Default KID</th>
                            <th style="background:#f7fafc;">Webview</th>
                            <th style="background:#f7fafc;">Magis</th>
                            <th style="background:#f7fafc;">Adulto</th>
                            <th style="background:#f7fafc;">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($channels as $channel): ?>
                            <tr id="channel-<?= $channel['id'] ?>" style="border-bottom:1px solid #e2e8f0;">
                                <td style="text-align:center;"><input type="checkbox" name="selected_channels[]" value="<?= $channel['id'] ?>"></td>
                                <td>
                                    <?php if ($channel['logo']): ?>
                                        <img src="<?= htmlspecialchars($channel['logo']) ?>" alt="Logo" class="logo-img" width="40" height="40" loading="lazy" style="object-fit:cover;border-radius:4px;" />
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($channel['name']) ?></td>
                                <td><?= htmlspecialchars($category = $channel['category_name'] ?? 'Uncategorized') ?></td>
                                <td class="uri-cell">
                                    <a href="<?= htmlspecialchars($channel['uri']) ?>" target="_blank" title="<?= htmlspecialchars($channel['uri']) ?>">
                                        <?= substr(htmlspecialchars($channel['uri']), 0, 30) . (strlen($channel['uri']) > 30 ? '...' : '') ?>
                                    </a>
                                </td>
                                <td>
                                    <?php if ($channel['drm_scheme']): ?>
                                        <span class="badge"><?= htmlspecialchars($channel['drm_scheme']) ?></span>
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($channel['default_KID'] ?? '') ?></td>
                                <td><?= htmlspecialchars($channel['webview']) ?></td>
                                <td><?= $channel['isMagis'] ? 'Sí' : 'No' ?></td>
                                <td>
                                    <?php if (!empty($channel['adultos'])): ?>
                                        <span class="badge badge-adult">+18</span>
                                    <?php else: ?>
                                        <span class="badge">No</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="display:flex;gap:0.3rem;">
                                        <button type="button" onclick="editChannel(<?= $channel['id'] ?>)" class="btn btn-primary">Editar</button>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="channel_id" value="<?= $channel['id'] ?>">
                                            <button type="submit" name="delete_channel" class="btn btn-danger"
                                                    onclick="return confirm('¿Eliminar este canal?')">
                                                Eliminar
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            </form>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?page=<?= $page - 1 ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?>">Previous</a>
                    <?php endif; ?>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <?php if ($i == $page): ?>
                            <span class="current"><?= $i ?></span>
                        <?php else: ?>
                            <a href="?page=<?= $i ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?>"><?= $i ?></a>
                        <?php endif; ?>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                        <a href="?page=<?= $page + 1 ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?>">Next</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="editModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Edit Channel</h2>
                <span class="close">×</span>
            </div>
            <form method="POST" id="editForm">
                <input type="hidden" name="channel_id" id="edit_channel_id">
                <div class="grid">
                    <div class="form-group">
                        <label class="form-label">Channel Name *</label>
                        <input type="text" name="name" id="edit_name" required class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Category *</label>
                        <input type="text" name="category" id="edit_category" list="categories" required class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Stream URI *</label>
                        <input type="url" name="uri" id="edit_uri" required class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Logo URL</label>
                        <input type="url" name="logo" id="edit_logo" class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">DRM Scheme</label>
                        <select name="drm_scheme" id="edit_drm_scheme" class="form-control">
                            <option value="">None</option>
                            <option value="clearkey">ClearKey</option>
                            <option value="widevine">Widevine</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">DRM License URI</label>
                        <input type="text" name="drm_license_uri" id="edit_drm_license_uri" class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Default KID</label>
                        <input type="text" name="default_KID" id="edit_default_KID" class="form-control" placeholder="Enter default KID">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Webview</label>
                        <select name="webview" id="edit_webview" class="form-control">
                            <option value="no">Disable</option>
                            <option value="yes">Enable</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Is Magis</label>
                        <select name="isMagis" id="edit_isMagis" class="form-control">
                            <option value="0">No</option>
                            <option value="1">Yes</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Contenido adulto</label><br>
                        <label class="switch">
                            <input type="checkbox" name="adultos" id="edit_adultos" value="1">
                            <span class="slider"></span>
                        </label>
                    </div>
                </div>

                <div class="headers-container">
                    <label class="form-label">Custom Headers</label>
                    <div id="editHeadersContainer"></div>
                    <button type="button" class="btn btn-primary" id="addEditHeader">Add Header</button>
                </div>

                <div style="margin-top: 1rem;">
                    <button type="submit" name="update_channel" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // DRM Type handling for add form
        const drmTypeSelect = document.getElementById('drmType');
        const clearkeyInput = document.getElementById('clearkeyInput');
        const widevineInput = document.getElementById('widevineInput');

        drmTypeSelect.addEventListener('change', function () {
            clearkeyInput.style.display = 'none';
            widevineInput.style.display = 'none';

            if (this.value === 'clearkey') {
                clearkeyInput.style.display = 'block';
            } else if (this.value === 'widevine') {
                widevineInput.style.display = 'block';
            }
        });

        // Flow Headers Autocomplete
        const flowHeaders = {
            "Accept": "*/*",
            "Accept-Language": "es-419,es;q=0.9,en;q=0.8",
            "Connection": "keep-alive",
            "Origin": "https://portal.app.flow.com.py",
            "Referer": "https://portal.app.flow.com.py/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
            "sec-ch-ua": "\"Google Chrome\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\""
        };

        const claroHeaders = {
            "Referer": "https://www.clarovideo.com/",
            "Origin": "https://www.clarovideo.com"
        };

        document.getElementById('useFlowHeaders').addEventListener('change', function () {
            if (this.checked) {
                document.getElementById('useClaroHeaders').checked = false;
            }
            fillHeaders(this.checked ? flowHeaders : null);
        });

        document.getElementById('useClaroHeaders').addEventListener('change', function () {
            if (this.checked) {
                document.getElementById('useFlowHeaders').checked = false;
            }
            fillHeaders(this.checked ? claroHeaders : null);
        });

        // --- Autollenado Default KID para Clarovideo ---
        const keyPairInput = document.querySelector('input[name="key_pair"]');
        const defaultKidInput = document.querySelector('input[name="default_KID"]');
        document.getElementById('useClaroHeaders').addEventListener('change', function () {
            if (this.checked) {
                // Si el campo key_pair tiene keyid válido, rellenar Default KID
                setDefaultKidFromKeyPair();
            }
        });

        if (keyPairInput) {
            keyPairInput.addEventListener('input', function () {
                if (document.getElementById('useClaroHeaders').checked) {
                    setDefaultKidFromKeyPair();
                }
            });
        }

        function setDefaultKidFromKeyPair() {
            if (!keyPairInput || !defaultKidInput) return;
            const val = keyPairInput.value.trim();
            const match = val.match(/^([a-fA-F0-9]{32}):([a-fA-F0-9]{32})$/);
            if (match) {
                defaultKidInput.value = match[1];
            }
        }

        function fillHeaders(headersObj) {
            const headersContainer = document.getElementById('headersContainer');
            headersContainer.innerHTML = '';
            if (headersObj) {
                let index = 0;
                for (const [key, value] of Object.entries(headersObj)) {
                    const div = document.createElement('div');
                    div.className = 'header-row';
                    div.innerHTML = `
                        <input type="text" name="headers[${index}][key]" value="${escapeHTML(key)}" placeholder="Header Key" class="form-control">
                        <input type="text" name="headers[${index}][value]" value="${escapeHTML(value)}" placeholder="Header Value" class="form-control">
                        <button type="button" class="btn btn-danger remove-header">Remove</button>
                    `;
                    headersContainer.appendChild(div);
                    index++;
                }
            } else {
                const div = document.createElement('div');
                div.className = 'header-row';
                div.innerHTML = `
                    <input type="text" name="headers[0][key]" placeholder="Header Key" class="form-control">
                    <input type="text" name="headers[0][value]" placeholder="Header Value" class="form-control">
                    <button type="button" class="btn btn-danger remove-header">Remove</button>
                `;
                headersContainer.appendChild(div);
            }
        }

        // Headers management for add form
        let headerCount = 1;
        document.getElementById('addHeader').addEventListener('click', function () {
            const container = document.getElementById('headersContainer');
            const div = document.createElement('div');
            div.className = 'header-row';
            div.innerHTML = `
                <input type="text" name="headers[${headerCount}][key]" placeholder="Header Key" class="form-control">
                <input type="text" name="headers[${headerCount}][value]" placeholder="Header Value" class="form-control">
                <button type="button" class="btn btn-danger remove-header">Remove</button>
            `;
            container.appendChild(div);
            headerCount++;
        });

        document.getElementById('headersContainer').addEventListener('click', function (e) {
            if (e.target.classList.contains('remove-header')) {
                e.target.parentElement.remove();
            }
        });

        // Edit Channel Modal
        const modal = document.getElementById('editModal');
        const closeBtn = document.querySelector('.close');

        closeBtn.onclick = function() {
            modal.style.display = 'none';
        }

        window.onclick = function(event) {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        }

        function editChannel(channelId) {
            // Fetch channel data
            fetch(`panel.php?action=get_channel&id=${channelId}`)
                .then(response => response.json())
                .then(channel => {
                    document.getElementById('edit_channel_id').value = channel.id;
                    document.getElementById('edit_name').value = channel.name;
                    document.getElementById('edit_category').value = channel.category_name;
                    document.getElementById('edit_uri').value = channel.uri;
                    document.getElementById('edit_logo').value = channel.logo || '';
                    document.getElementById('edit_drm_scheme').value = channel.drm_scheme || '';
                    document.getElementById('edit_drm_license_uri').value = channel.drm_license_uri || '';
                    document.getElementById('edit_default_KID').value = channel.default_KID || '';
                    document.getElementById('edit_webview').value = channel.webview;
                    document.getElementById('edit_isMagis').value = channel.isMagis;
                    document.getElementById('edit_adultos').checked = channel.adultos == 1;

                    // Set up headers
                    const headersContainer = document.getElementById('editHeadersContainer');
                    headersContainer.innerHTML = '';
                    
                    let headers = {};
                    try {
                        headers = JSON.parse(channel.headers) || {};
                    } catch(e) {
                        console.error('Failed to parse headers:', e);
                    }

                    let i = 0;
                    for (const key in headers) {
                        if (headers.hasOwnProperty(key)) {
                            const div = document.createElement('div');
                            div.className = 'header-row';
                            div.innerHTML = `<input type="text" name="headers[${i}][key]" value="${escapeHTML(key)}" class="form-control">
                                <input type="text" name="headers[${i}][value]" value="${escapeHTML(headers[key])}" class="form-control">
                                <button type="button" class="btn btn-danger remove-header">Remove</button>
                            `;
                            headersContainer.appendChild(div);
                            i++;
                        }
                    }

                    // If no headers, add an empty row
                    if (i === 0) {
                        addEmptyHeaderRow();
                    }

                    // Show the modal
                    modal.style.display = 'block';
                })
                .catch(error => {
                    console.error('Error fetching channel data:', error);
                    alert('Error loading channel data. Please try again.');
                });
        }

        // Helper function to escape HTML
        function escapeHTML(str) {
            if (!str) return '';
            return str
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        // Add empty header row for edit form
        function addEmptyHeaderRow() {
            const container = document.getElementById('editHeadersContainer');
            const headerCount = container.querySelectorAll('.header-row').length;
            const div = document.createElement('div');
            div.className = 'header-row';
            div.innerHTML = `
                <input type="text" name="headers[${headerCount}][key]" placeholder="Header Key" class="form-control">
                <input type="text" name="headers[${headerCount}][value]" placeholder="Header Value" class="form-control">
                <button type="button" class="btn btn-danger remove-header">Remove</button>
            `;
            container.appendChild(div);
        }

        // Add header button for edit form
        document.getElementById('addEditHeader').addEventListener('click', function() {
            addEmptyHeaderRow();
        });

        // Remove header button for edit form
        document.getElementById('editHeadersContainer').addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-header')) {
                e.target.parentElement.remove();
            }
        });
    </script>
</body>
</html>
