<?php
// JSON file path
$jsonFile = 'channels.json';

// Load data from the file
$data = json_decode(file_get_contents($jsonFile), true);

// Get query parameters (id and extension)
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$ext = isset($_GET['e']) ? $_GET['e'] : '';

// Fetch the channel URL based on the provided ID
$channel = array_filter($data, function ($ch) use ($id) {
    return $ch['id'] === $id;
});

// If no channel found, send 404 error
if (empty($channel)) {
    header("HTTP/1.0 404 Not Found");
    echo "Stream not found!";
    exit;
}

// Get the first matching channel
$channel = array_values($channel)[0];
$streamURL = $channel['url'];

// Validate extension (optional)
if ($ext !== '.m3u8') {
    header("HTTP/1.0 400 Bad Request");
    echo "Invalid extension!";
    exit;
}

// Ensure stream URL is valid
if (!filter_var($streamURL, FILTER_VALIDATE_URL)) {
    header("HTTP/1.0 400 Bad Request");
    echo "Invalid stream URL!";
    exit;
}

// Restrict access to only cwabdtv.eu.org domain by checking the HTTP_REFERER
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
if (strpos($referer, 'cwabdtv.eu.org') === false) {
    header("HTTP/1.0 403 Forbidden");
    echo "Access Denied: Only cwabdtv.eu.org can access this stream.";
    exit;
}

// Set CORS headers to allow cwabdtv.eu.org to access the stream
header("Access-Control-Allow-Origin: http://cwabdtv.eu.org");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type");

// Correct header set and stream the content
header("Content-Type: application/vnd.apple.mpegurl");
readfile($streamURL);
?>