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

$action = $_GET['action'] ?? '';

if ($action === 'get_channel') {
    try {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

        if ($id <= 0) {
            http_response_code(400);
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Invalid channel ID']);
            exit;
        }

        $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([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            // Ensure all fields are properly set
            $row['adultos'] = isset($row['adultos']) ? (int)$row['adultos'] : 0;
            $row['claroandina'] = isset($row['claroandina']) ? (int)$row['claroandina'] : 0;
            $row['groupid'] = isset($row['groupid']) ? $row['groupid'] : '';
            $row['isMagis'] = isset($row['isMagis']) ? (int)$row['isMagis'] : 0;
            $row['webview'] = isset($row['webview']) ? $row['webview'] : 'no';
            $row['drm_scheme'] = isset($row['drm_scheme']) ? $row['drm_scheme'] : '';
            $row['drm_license_uri'] = isset($row['drm_license_uri']) ? $row['drm_license_uri'] : '';
            $row['default_KID'] = isset($row['default_KID']) ? $row['default_KID'] : '';
            $row['headers'] = isset($row['headers']) ? $row['headers'] : '';
            $row['logo'] = isset($row['logo']) ? $row['logo'] : '';
            $row['uri'] = isset($row['uri']) ? $row['uri'] : '';

            header('Content-Type: application/json');
            echo json_encode($row);
        } else {
            http_response_code(404);
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Channel not found']);
        }
    } catch (Exception $e) {
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
    exit;
}

http_response_code(400);
echo json_encode(['error' => 'Bad request']);
