<?php
require_once dirname(__DIR__) . '/auth.php';
require_once dirname(__DIR__) . '/includes/config.php';
$pdo = pdo();
$pageTitle = 'Canales';

$success_message = '';
$error_message = '';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$items_per_page = 20;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$filter_category = isset($_GET['category']) ? trim($_GET['category']) : '';
$view = isset($_GET['view']) ? $_GET['view'] : 'list'; // 'list' or 'add'

// Handle POST (add/update/delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['delete_selected']) && !empty($_POST['selected_channels']) && is_array($_POST['selected_channels'])) {
            $ids = array_map('intval', $_POST['selected_channels']);
            $in = implode(',', array_fill(0, count($ids), '?'));
            $stmt = $pdo->prepare("DELETE FROM channels WHERE id IN ($in)");
            $stmt->execute($ids);
            $success_message = 'Selected channels deleted';
        }

        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;
            $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;
            $claroandina = isset($_POST['claroandina']) && $_POST['claroandina'] === '1' ? 1 : 0;
            $groupid = trim($_POST['groupid']) ?: null;

            // Validation: if claroandina is true, groupid is required
            if ($claroandina && empty($groupid)) {
                throw new Exception('Group ID is required when Claro Andina is enabled');
            }

            // Validation: if claroandina is false, uri is required
            if (!$claroandina && empty($uri)) {
                throw new Exception('Stream URI is required when Claro Andina is disabled');
            }

            $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);

            $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']);
                if (preg_match('/^([a-fA-F0-9]{32}):([a-fA-F0-9]{32})$/', $key_pair, $m)) {
                    $keyid = $m[1]; $key = $m[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);
                    $drm_license_uri = $api_response !== false ? $api_response : '';
                } 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, claroandina, groupid)
                                   VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->execute([$name, $uri, $category_id, $logo, $drm_scheme, $drm_license_uri, $headers_json, $webview, $isMagis, $default_KID, $adultos, $claroandina, $groupid]);
            $pdo->commit();
            $success_message = 'Channel added';
        }

        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;
            $adultos = isset($_POST['adultos']) && $_POST['adultos'] === '1' ? 1 : 0;
            $claroandina = isset($_POST['claroandina']) && $_POST['claroandina'] === '1' ? 1 : 0;
            $groupid = trim($_POST['groupid']) ?: null;

            // Validation: if claroandina is true, groupid is required
            if ($claroandina && empty($groupid)) {
                throw new Exception('Group ID is required when Claro Andina is enabled');
            }

            // Validation: if claroandina is false, uri is required
            if (!$claroandina && empty($uri)) {
                throw new Exception('Stream URI is required when Claro Andina is disabled');
            }

            $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);

            $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=?, claroandina=?, groupid=? WHERE id=?");
            $stmt->execute([$name, $uri, $category_id, $logo, $drm_scheme, $drm_license_uri, $headers_json, $webview, $isMagis, $default_KID, $adultos, $claroandina, $groupid, $channel_id]);
            $pdo->commit();
            $success_message = 'Channel updated';
        }

        if (isset($_POST['delete_channel'])) {
            $stmt = $pdo->prepare("DELETE FROM channels WHERE id = ?");
            $stmt->execute([(int)$_POST['channel_id']]);
            $success_message = 'Channel deleted';
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $error_message = $e->getMessage();
    }
}

// Data for page
$categories = $pdo->query("SELECT * FROM categories ORDER BY name")->fetchAll();

$count_sql = "SELECT COUNT(*) FROM channels";
$where_conditions = [];
$search_params = [];

if ($search !== '') {
    $where_conditions[] = "(channels.name LIKE ? OR channels.uri LIKE ?)";
    $search_params[] = "%$search%";
    $search_params[] = "%$search%";
}

if ($filter_category !== '') {
    $where_conditions[] = "categories.name = ?";
    $search_params[] = $filter_category;
}

if (!empty($where_conditions)) {
    $count_sql .= " LEFT JOIN categories ON channels.category_id = categories.id WHERE " . implode(' AND ', $where_conditions);
}

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

try {
    $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, channels.claroandina, channels.groupid
            FROM channels LEFT JOIN categories ON channels.category_id = categories.id";

    $where_conditions = [];
    $query_params = [];

    if ($search !== '') {
        $where_conditions[] = "(channels.name LIKE ? OR channels.uri LIKE ?)";
        $query_params[] = "%$search%";
        $query_params[] = "%$search%";
    }

    if ($filter_category !== '') {
        $where_conditions[] = "categories.name = ?";
        $query_params[] = $filter_category;
    }

    if (!empty($where_conditions)) {
        $sql .= " WHERE " . implode(' AND ', $where_conditions);
    }

    $sql .= " ORDER BY categories.name, channels.name LIMIT " . (($page-1)*$items_per_page) . ", " . $items_per_page;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($query_params);
    $channels = $stmt->fetchAll();

    foreach ($channels as &$ch) {
        $ch['adultos'] = isset($ch['adultos']) ? (int)$ch['adultos'] : 0;
        $ch['claroandina'] = isset($ch['claroandina']) ? (int)$ch['claroandina'] : 0;
        $ch['groupid'] = isset($ch['groupid']) ? $ch['groupid'] : '';
        $ch['name'] = $ch['name'] ?? '';
        $ch['uri'] = $ch['uri'] ?? '';
        $ch['logo'] = $ch['logo'] ?? '';
        $ch['drm_scheme'] = $ch['drm_scheme'] ?? '';
        $ch['default_KID'] = $ch['default_KID'] ?? '';
        $ch['category_name'] = $ch['category_name'] ?? 'Uncategorized';
        $ch['webview'] = $ch['webview'] ?? 'no';
        $ch['isMagis'] = isset($ch['isMagis']) ? (int)$ch['isMagis'] : 0;
    }
    unset($ch);
} catch (Exception $e) {
    $error_message = "Error loading channels: " . $e->getMessage();
    $channels = [];
}

include dirname(__DIR__) . '/includes/header.php';
?>

<?php if ($success_message): ?><div class="flash success"><?= h($success_message) ?></div><?php endif; ?>
<?php if ($error_message): ?><div class="flash error"><?= h($error_message) ?></div><?php endif; ?>

<!-- Navigation Tabs -->
<div class="card" style="margin-bottom:1rem;">
  <div style="display:flex; gap:1rem; border-bottom:2px solid #e2e8f0; padding-bottom:.5rem;">
    <a href="?view=list" class="tab-link <?= $view === 'list' ? 'active' : '' ?>" style="padding:.5rem 1rem; text-decoration:none; color:<?= $view === 'list' ? '#4299e1' : '#666' ?>; font-weight:<?= $view === 'list' ? '700' : '500' ?>; border-bottom:3px solid <?= $view === 'list' ? '#4299e1' : 'transparent' ?>;">
      📋 Lista de Canales
    </a>
    <a href="?view=add" class="tab-link <?= $view === 'add' ? 'active' : '' ?>" style="padding:.5rem 1rem; text-decoration:none; color:<?= $view === 'add' ? '#4299e1' : '#666' ?>; font-weight:<?= $view === 'add' ? '700' : '500' ?>; border-bottom:3px solid <?= $view === 'add' ? '#4299e1' : 'transparent' ?>;">
      ➕ Agregar Canal
    </a>
  </div>
</div>

<?php if ($view === 'add'): ?>
<div class="card">
  <h2 style="margin-bottom:.75rem;">📺 Agregar Nuevo Canal</h2>
  <form method="POST" class="form" id="addChannelForm">
    <div class="grid">
      <div class="form-group">
        <label>Nombre del Canal *</label>
        <input type="text" name="name" required placeholder="Ej: ESPN HD">
      </div>
      <div class="form-group">
        <label>Categoría *</label>
        <input type="text" name="category" list="categories" required placeholder="Ej: DEPORTES">
        <datalist id="categories">
          <?php foreach ($categories as $c): ?><option value="<?= h($c['name']) ?>"><?php endforeach; ?>
        </datalist>
      </div>
      <div class="form-group">
        <label>Stream URI <span id="uriRequired">*</span> <small style="color:#666;">(URL del stream)</small></label>
        <input type="url" name="uri" id="uriInput" required placeholder="https://example.com/stream.m3u8">
      </div>
      <div class="form-group">
        <label>Logo URL <small style="color:#666;">(Opcional)</small></label>
        <input type="url" name="logo" placeholder="https://example.com/logo.png">
      </div>
      <div class="form-group">
        <label>DRM Type</label>
        <select name="drm_type" id="drmType" class="form-control">
          <option value="">None</option>
          <option value="clearkey">ClearKey</option>
          <option value="widevine">Widevine</option>
        </select>
      </div>
    </div>

    <!-- DRM Fields (outside grid for full width) -->
    <div class="form-group" id="clearkeyInput" style="display:none; margin-top:1rem;">
      <label>KeyID:Key * <small style="color:#666;">(Formato: keyid:key en hexadecimal)</small></label>
      <input type="text" name="key_pair" placeholder="a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6:q1r2s3t4u5v6w7x8y9z0a1b2c3d4e5f6" class="form-control">
    </div>

    <div class="form-group" id="widevineInput" style="display:none; margin-top:1rem;">
      <label>DRM License URI * <small style="color:#666;">(URL del servidor de licencias)</small></label>
      <input type="url" name="drm_license_uri" placeholder="https://license.example.com/widevine" class="form-control">
    </div>

    <div class="grid" style="margin-top:1rem;">
      <div class="form-group">
        <label>Default KID <small style="color:#666;">(Opcional)</small></label>
        <input type="text" name="default_KID" placeholder="Enter default KID" class="form-control">
      </div>
      <div class="form-group">
        <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>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>Contenido adulto</label><br>
        <label class="switch"><input type="checkbox" name="adultos" value="1"><span class="slider"></span></label>
      </div>
      <div class="form-group">
        <label>🌎 Claro Andina <small style="color:#666;">(Activar para canales de Claro Andina)</small></label><br>
        <label class="switch"><input type="checkbox" name="claroandina" id="claroandinaCheckbox" value="1"><span class="slider"></span></label>
      </div>
    </div>

    <!-- Group ID Field (outside grid for full width) -->
    <div class="form-group" id="groupidInput" style="display:none; margin-top:1rem;">
      <label>🆔 Group ID <span style="color:#e53e3e;">*</span> <small style="color:#666;">(ID del grupo del canal - Requerido para Claro Andina)</small></label>
      <input type="text" name="groupid" id="groupidField" placeholder="Ej: 12345" class="form-control">
    </div>

    <div class="headers-container" style="margin-top:1rem;">
      <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">
          <input type="text" name="headers[0][value]" placeholder="Header Value">
          <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">➕ Agregar Canal</button></div>
  </form>
</div>
<?php endif; ?>

<?php if ($view === 'list'): ?>
<div class="card">
  <!-- Filters -->
  <form method="GET" action="" style="margin-bottom:.75rem;">
    <input type="hidden" name="view" value="list">
    <div style="display:flex; gap:.5rem; flex-wrap:wrap;">
      <input type="text" name="search" placeholder="🔍 Buscar canales..." value="<?= h($search) ?>" style="flex:1; min-width:200px;">

      <select name="category" style="min-width:200px;">
        <option value="">📂 Todas las categorías</option>
        <?php foreach ($categories as $cat): ?>
          <option value="<?= h($cat['name']) ?>" <?= $filter_category === $cat['name'] ? 'selected' : '' ?>>
            <?= h($cat['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>

      <button type="submit" class="btn btn-primary">🔍 Filtrar</button>
      <?php if ($search !== '' || $filter_category !== ''): ?>
        <a class="btn btn-danger" href="?view=list">🔄 Limpiar</a>
      <?php endif; ?>
    </div>
  </form>

  <form method="POST" id="multiDeleteForm">
    <div class="actions" style="justify-content:space-between; margin-bottom:.5rem; flex-wrap:wrap;">
      <div>
        <span style="font-weight:700; font-size:1.1rem;">📋 Lista de Canales (<?= count($channels) ?> de <?= $total_items ?>)</span>
        <?php if ($filter_category !== ''): ?>
          <span class="badge badge-success" style="margin-left:.5rem;">Categoría: <?= h($filter_category) ?></span>
        <?php endif; ?>
      </div>
      <div class="actions">
        <button type="button" class="btn btn-primary" id="selectAllBtn" onclick="toggleSelectAll()">☑️ Seleccionar Todos</button>
        <button type="submit" name="delete_selected" class="btn btn-danger" onclick="return confirm('¿Eliminar los canales seleccionados?')">🗑️ Eliminar Seleccionados</button>
      </div>
    </div>
    <div style="overflow-x:auto;">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" id="selectAllChannels"></th>
            <th>Logo</th>
            <th>Nombre</th>
            <th>Categoría</th>
            <th>URI</th>
            <th>DRM</th>
            <th>Default KID</th>
            <th>Webview</th>
            <th>Magis</th>
            <th>Adulto</th>
            <th>Claro Andina</th>
            <th>Group ID</th>
            <th>Acciones</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($channels)): ?>
            <tr>
              <td colspan="13" style="text-align:center; padding:2rem; color:#666;">
                <?= $error_message ? h($error_message) : 'No hay canales disponibles' ?>
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($channels as $ch): ?>
              <tr id="channel-<?= h($ch['id']) ?>">
                <td style="text-align:center;"><input type="checkbox" name="selected_channels[]" value="<?= h($ch['id']) ?>"></td>
                <td><?php if (!empty($ch['logo'])): ?><img src="<?= h($ch['logo']) ?>" alt="Logo" class="logo-img" width="40" height="40" loading="lazy" style="object-fit:cover;border-radius:4px;" /><?php endif; ?></td>
                <td><?= h($ch['name']) ?></td>
                <td><?= h($ch['category_name']) ?></td>
                <td class="uri-cell">
                  <?php if (!empty($ch['uri'])): ?>
                    <a href="<?= h($ch['uri']) ?>" target="_blank" title="<?= h($ch['uri']) ?>">
                      <?= h(strlen($ch['uri']) > 30 ? substr($ch['uri'], 0, 30) . '...' : $ch['uri']) ?>
                    </a>
                  <?php endif; ?>
                </td>
                <td><?php if (!empty($ch['drm_scheme'])): ?><span class="badge"><?= h($ch['drm_scheme']) ?></span><?php endif; ?></td>
                <td><?= h($ch['default_KID']) ?></td>
                <td><?= h($ch['webview']) ?></td>
                <td><?= $ch['isMagis'] ? 'Sí' : 'No' ?></td>
                <td><?= ((int)$ch['adultos'] === 1) ? '<span class="badge badge-adult">+18</span>' : '<span class="badge">No</span>' ?></td>
                <td><?= ((int)$ch['claroandina'] === 1) ? '<span class="badge badge-success">Sí</span>' : '<span class="badge">No</span>' ?></td>
                <td><?= h($ch['groupid']) ?></td>
                <td>
                  <div class="actions">
                    <button type="button" class="btn btn-primary" onclick="editChannel(<?= (int)$ch['id'] ?>)" title="Editar canal">✏️ Editar</button>
                    <form method="POST" onsubmit="return confirmDelete('<?= htmlspecialchars($ch['name'], ENT_QUOTES) ?>')" style="display:inline;">
                      <input type="hidden" name="channel_id" value="<?= (int)$ch['id'] ?>">
                      <button type="submit" name="delete_channel" class="btn btn-danger" title="Eliminar canal">🗑️ Eliminar</button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </form>

  <?php if ($total_pages > 1): ?>
    <?php
      $pagination_params = 'view=list';
      if ($search !== '') $pagination_params .= '&search=' . urlencode($search);
      if ($filter_category !== '') $pagination_params .= '&category=' . urlencode($filter_category);
    ?>
    <div class="actions" style="justify-content:center; margin-top:.8rem; gap:.25rem; flex-wrap:wrap;">
      <?php if ($page > 1): ?><a class="btn btn-primary" href="?<?= $pagination_params ?>&page=<?= $page-1 ?>">⬅️ Anterior</a><?php endif; ?>
      <?php
        $start_page = max(1, $page - 2);
        $end_page = min($total_pages, $page + 2);
        if ($start_page > 1): ?>
          <a class="btn btn-primary" href="?<?= $pagination_params ?>&page=1">1</a>
          <?php if ($start_page > 2): ?><span style="padding:.5rem;">...</span><?php endif; ?>
        <?php endif; ?>
      <?php for ($i=$start_page;$i<=$end_page;$i++): ?>
        <?php if ($i == $page): ?><span class="btn" style="background:#2b6cb0;color:white;"><?= $i ?></span>
        <?php else: ?><a class="btn btn-primary" href="?<?= $pagination_params ?>&page=<?= $i ?>"><?= $i ?></a><?php endif; ?>
      <?php endfor; ?>
      <?php if ($end_page < $total_pages): ?>
        <?php if ($end_page < $total_pages - 1): ?><span style="padding:.5rem;">...</span><?php endif; ?>
        <a class="btn btn-primary" href="?<?= $pagination_params ?>&page=<?= $total_pages ?>"><?= $total_pages ?></a>
      <?php endif; ?>
      <?php if ($page < $total_pages): ?><a class="btn btn-primary" href="?<?= $pagination_params ?>&page=<?= $page+1 ?>">Siguiente ➡️</a><?php endif; ?>
    </div>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- Edit Modal -->
<div id="editModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,.5); z-index:1000; overflow:auto;">
  <div class="card" style="max-width:900px; margin:5% auto;">
    <div style="display:flex; align-items:center; justify-content:space-between; border-bottom:1px solid #e2e8f0; padding-bottom:.5rem; margin-bottom:.75rem;">
      <h2>✏️ Editar Canal</h2>
      <button class="btn btn-danger" id="closeModal" title="Cerrar">×</button>
    </div>
    <form method="POST" id="editForm">
      <input type="hidden" name="channel_id" id="edit_channel_id">
      <div class="grid">
        <div class="form-group"><label>Channel Name *</label><input type="text" name="name" id="edit_name" required class="form-control"></div>
        <div class="form-group"><label>Category *</label><input type="text" name="category" id="edit_category" list="categories" required class="form-control"></div>
        <div class="form-group"><label>Stream URI <span id="edit_uriRequired">*</span></label><input type="url" name="uri" id="edit_uri" required class="form-control"></div>
        <div class="form-group"><label>Logo URL</label><input type="url" name="logo" id="edit_logo" class="form-control"></div>
        <div class="form-group"><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>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>Default KID</label><input type="text" name="default_KID" id="edit_default_KID" placeholder="Enter default KID" class="form-control"></div>
        <div class="form-group"><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>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>Contenido adulto</label><br><label class="switch"><input type="checkbox" name="adultos" id="edit_adultos" value="1"><span class="slider"></span></label></div>
        <div class="form-group"><label>🌎 Claro Andina</label><br><label class="switch"><input type="checkbox" name="claroandina" id="edit_claroandina" value="1"><span class="slider"></span></label></div>
      </div>

      <!-- Group ID Field for Edit Modal -->
      <div class="form-group" id="edit_groupidInput" style="display:none; margin-top:1rem;">
        <label>🆔 Group ID <span style="color:#e53e3e;">*</span> <small style="color:#666;">(ID del grupo del canal - Requerido para Claro Andina)</small></label>
        <input type="text" name="groupid" id="edit_groupid" placeholder="Ej: 12345" class="form-control">
      </div>
      <div class="headers-container" style="margin-top:1rem;">
        <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">💾 Guardar Cambios</button></div>
    </form>
  </div>
  </div>

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

  if (drmTypeSelect && clearkeyInput && widevineInput) {
    drmTypeSelect.addEventListener('change', function(){
      clearkeyInput.style.display = this.value==='clearkey' ? 'block' : 'none';
      widevineInput.style.display = this.value==='widevine' ? 'block' : 'none';
    });
  }

  // Claro Andina handling
  const claroandinaCheckbox = document.getElementById('claroandinaCheckbox');
  const groupidInput = document.getElementById('groupidInput');
  const groupidField = document.getElementById('groupidField');
  const uriInput = document.getElementById('uriInput');
  const uriRequired = document.getElementById('uriRequired');

  if (claroandinaCheckbox && groupidInput && groupidField && uriInput && uriRequired) {
    claroandinaCheckbox.addEventListener('change', function(){
      if (this.checked) {
        groupidInput.style.display = 'block';
        groupidField.required = true;
        uriInput.required = false;
        uriRequired.style.display = 'none';
        uriInput.style.borderColor = '#48bb78';
        uriInput.placeholder = 'URI opcional para Claro Andina';
        showNotification('✅ Claro Andina activado: Group ID es requerido, URI es opcional', 'success');
      } else {
        groupidInput.style.display = 'none';
        groupidField.required = false;
        uriInput.required = true;
        uriRequired.style.display = 'inline';
        uriInput.style.borderColor = '';
        uriInput.placeholder = 'https://example.com/stream.m3u8';
        showNotification('ℹ️ Claro Andina desactivado: URI es requerido', 'info');
      }
    });
  }

  // Notification function
  function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `flash ${type === 'success' ? 'success' : 'info'}`;
    notification.textContent = message;
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.maxWidth = '400px';
    document.body.appendChild(notification);
    setTimeout(() => {
      notification.remove();
    }, 4000);
  }

  // Presets (only for add form)
  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"};

  const useFlowHeadersEl = document.getElementById('useFlowHeaders');
  const useClaroHeadersEl = document.getElementById('useClaroHeaders');

  if (useFlowHeadersEl && useClaroHeadersEl) {
    useFlowHeadersEl.addEventListener('change', function(){
      if(this.checked){useClaroHeadersEl.checked=false;}
      fillHeaders(this.checked?flowHeaders:null);
    });
    useClaroHeadersEl.addEventListener('change', function(){
      if(this.checked){useFlowHeadersEl.checked=false;}
      fillHeaders(this.checked?claroHeaders:null);
    });
  }

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

  // dynamic headers add/remove (only for add form)
  let headerCount = 1;
  const addHeaderBtn = document.getElementById('addHeader');
  const headersContainer = document.getElementById('headersContainer');

  if (addHeaderBtn && headersContainer) {
    addHeaderBtn.addEventListener('click', function(){
      const d=document.createElement('div');
      d.className='header-row';
      d.innerHTML=`<input type="text" name="headers[${headerCount}][key]" placeholder="Header Key"><input type="text" name="headers[${headerCount}][value]" placeholder="Header Value"><button type="button" class="btn btn-danger remove-header">Remove</button>`;
      headersContainer.appendChild(d);
      headerCount++;
    });
    headersContainer.addEventListener('click', function(e){
      if(e.target.classList.contains('remove-header')) e.target.parentElement.remove();
    });
  }

  // Edit modal - declare at the top
  const modal = document.getElementById('editModal');

  if (modal) {
    const closeModalBtn = document.getElementById('closeModal');
    if (closeModalBtn) {
      closeModalBtn.onclick = ()=> modal.style.display='none';
    }
    window.addEventListener('click', (e)=> { if(e.target===modal) modal.style.display='none'; });
  }

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

  const addEditHeaderBtn = document.getElementById('addEditHeader');
  if (addEditHeaderBtn) {
    addEditHeaderBtn.addEventListener('click', addEmptyHeaderRow);
  }

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

  window.editChannel = function(id){
    if (!modal) {
      alert('❌ Error: Modal no encontrado');
      return;
    }
    console.log('Editing channel ID:', id);

    // Get the correct path to api.php (one level up from pages/)
    const apiPath = window.location.pathname.includes('/pages/')
      ? '../api.php'
      : 'api.php';

    console.log('API Path:', apiPath);
    console.log('Full URL:', `${apiPath}?action=get_channel&id=${id}`);

    fetch(`${apiPath}?action=get_channel&id=${id}`)
      .then(r => {
        console.log('Response status:', r.status);
        console.log('Response ok:', r.ok);

        if (!r.ok) {
          return r.text().then(text => {
            console.error('Error response:', text);
            throw new Error(`HTTP ${r.status}: ${text}`);
          });
        }
        return r.json();
      })
      .then(ch=>{
        console.log('Channel data received:', ch);

        if (ch.error) {
          throw new Error(ch.error);
        }
      modal.style.display='block';
      document.getElementById('edit_channel_id').value = ch.id;
      document.getElementById('edit_name').value = ch.name;
      document.getElementById('edit_category').value = ch.category_name;
      document.getElementById('edit_uri').value = ch.uri;
      document.getElementById('edit_logo').value = ch.logo || '';
      document.getElementById('edit_drm_scheme').value = ch.drm_scheme || '';
      document.getElementById('edit_drm_license_uri').value = ch.drm_license_uri || '';
      document.getElementById('edit_default_KID').value = ch.default_KID || '';
      document.getElementById('edit_webview').value = ch.webview;
      document.getElementById('edit_isMagis').value = ch.isMagis;
      document.getElementById('edit_adultos').checked = Number(ch.adultos) === 1;

      const claroCheckbox = document.getElementById('edit_claroandina');
      const editGroupidInput = document.getElementById('edit_groupidInput');
      const editGroupidField = document.getElementById('edit_groupid');
      const editUriInput = document.getElementById('edit_uri');
      const editUriRequired = document.getElementById('edit_uriRequired');

      if (claroCheckbox) {
        claroCheckbox.checked = Number(ch.claroandina) === 1;
        editGroupidField.value = ch.groupid || '';

        // Handle claro andina logic for edit modal
        if (claroCheckbox.checked) {
          editGroupidInput.style.display = 'block';
          editGroupidField.required = true;
          editUriInput.required = false;
          editUriRequired.style.display = 'none';
        } else {
          editGroupidInput.style.display = 'none';
          editGroupidField.required = false;
          editUriInput.required = true;
          editUriRequired.style.display = 'inline';
        }

        // Add event listener for edit modal claro andina checkbox
        claroCheckbox.addEventListener('change', function(){
          if (this.checked) {
            editGroupidInput.style.display = 'block';
            editGroupidField.required = true;
            editUriInput.required = false;
            editUriRequired.style.display = 'none';
          } else {
            editGroupidInput.style.display = 'none';
            editGroupidField.required = false;
            editUriInput.required = true;
            editUriRequired.style.display = 'inline';
          }
        });
      }

      const container=document.getElementById('editHeadersContainer'); container.innerHTML='';
      let headers={}; try{ headers = JSON.parse(ch.headers) || {}; }catch(e){}
      let i=0; for(const k in headers){ if(Object.hasOwn(headers,k)){ const d=document.createElement('div'); d.className='header-row'; d.innerHTML=`<input type="text" name="headers[${i}][key]" value="${escapeHTML(k)}"><input type="text" name="headers[${i}][value]" value="${escapeHTML(headers[k])}"><button type="button" class="btn btn-danger remove-header">Remove</button>`; container.appendChild(d); i++; } }
      if(container.children.length===0) addEmptyHeaderRow();
    }).catch((error)=>{
      console.error('Error loading channel:', error);
      alert(`❌ Error al cargar los datos del canal.\n\nDetalles: ${error.message}\n\nPor favor, intenta nuevamente.`);
      if (modal) modal.style.display='none';
    });
  };

  // Confirm delete function
  function confirmDelete(channelName) {
    return confirm(`⚠️ ¿Estás seguro de que deseas eliminar el canal "${channelName}"?\n\nEsta acción no se puede deshacer.`);
  }

  window.confirmDelete = confirmDelete;

  // Form validation
  const addChannelForm = document.getElementById('addChannelForm');
  if (addChannelForm) {
    addChannelForm.addEventListener('submit', function(e) {
      const claroandina = document.getElementById('claroandinaCheckbox');
      const groupid = document.getElementById('groupidField');
      const uri = document.getElementById('uriInput');

      if (claroandina && claroandina.checked && groupid && !groupid.value.trim()) {
        e.preventDefault();
        showNotification('❌ Group ID es requerido cuando Claro Andina está activado', 'error');
        groupid.focus();
        return false;
      }

      if (claroandina && !claroandina.checked && uri && !uri.value.trim()) {
        e.preventDefault();
        showNotification('❌ Stream URI es requerido cuando Claro Andina está desactivado', 'error');
        uri.focus();
        return false;
      }
    });
  }

  // select all checkbox
  const selectAllCheckbox = document.getElementById('selectAllChannels');
  if (selectAllCheckbox) {
    selectAllCheckbox.addEventListener('change', function(){
      document.querySelectorAll('input[name="selected_channels[]"]').forEach(cb=>cb.checked=this.checked);
    });
  }

  // Toggle select all button
  function toggleSelectAll() {
    const checkboxes = document.querySelectorAll('input[name="selected_channels[]"]');
    const allChecked = Array.from(checkboxes).every(cb => cb.checked);
    checkboxes.forEach(cb => cb.checked = !allChecked);

    const btn = document.getElementById('selectAllBtn');
    if (btn) {
      btn.textContent = allChecked ? '☑️ Seleccionar Todos' : '☐ Deseleccionar Todos';
    }
  }

  window.toggleSelectAll = toggleSelectAll;
</script>

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