<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/debug.log');

// Function to log messages
function debugLog($message) {
    file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - $message\n", FILE_APPEND);
}

// Function to retrieve the encryption key
function getEncryptionKey() {
    return "your_16_byte_key_"; // Ensure this is 16 characters
}

// Function to perform encryption
function encryptData($data) {
    $key = getEncryptionKey();
    $iv = "1234567890123456"; // Ensure this is 16 characters

    $encrypted = openssl_encrypt($data, "AES-128-CBC", $key, OPENSSL_RAW_DATA, $iv);
    if ($encrypted === false) {
        throw new Exception('Encryption failed.');
    }
    return bin2hex($encrypted);
}

// Function to perform decryption
function decryptData($data) {
    $key = getEncryptionKey();
    $iv = "1234567890123456"; // Ensure this is 16 characters

    $decryptedData = hex2bin($data);
    if ($decryptedData === false) {
        debugLog("Hex decode failed for: $data");
        throw new Exception('Invalid hexadecimal data.');
    }

    $decrypted = openssl_decrypt($decryptedData, "AES-128-CBC", $key, OPENSSL_RAW_DATA, $iv);
    if ($decrypted === false) {
        debugLog("Decryption failed: " . openssl_error_string());
        throw new Exception('Decryption failed.');
    }
    return $decrypted;
}

// Function to perform a GET request
function reqGet($url, $headers = []) {
    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CONNECTTIMEOUT => 15,
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

// Check if this is a TS segment request
if (isset($_GET['segment'])) {
    // Handle TS segment request (formerly ts2.php)
    $segment = $_GET['segment'];
    
    try {
        $segmentUrl = decryptData($segment);
        debugLog("Decrypted segment URL: $segmentUrl");
    } catch (Exception $e) {
        debugLog("Decryption error: " . $e->getMessage());
        die("Decryption error: " . $e->getMessage());
    }

    if (!filter_var($segmentUrl, FILTER_VALIDATE_URL) || !str_ends_with($segmentUrl, '.ts')) {
        debugLog("Invalid TS URL: $segmentUrl");
        die("Invalid TS segment URL.");
    }

    $content = reqGet($segmentUrl, ['Referer: ']);
    if (!$content) {
        debugLog("Failed to fetch TS segment");
        die("Failed to fetch TS segment.");
    }

    header("Content-Type: video/mp2t");
    header("Cache-Control: no-cache, must-revalidate");
    header("Connection: keep-alive");
    echo $content;
    exit;
}

// Main M3U8 processing (formerly pro.php)
$id = @$_GET['id'];
if (empty($id)) {
    die("Error: ID parameter is required.");
}

$url = "http://jmks45.live/live/fb1ee2643c/0bd2e3b5b0/$id.m3u8";

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_HEADER => false,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Linux; Android 9; Mi Note 3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.6367.82 Mobile Safari/537.36'
]);

$response = curl_exec($curl);

if ($response === false) {
    die("Error: " . curl_error($curl));
}

$info = curl_getinfo($curl);
curl_close($curl);

$redirect_url = $info['url'];
$parsed_url = parse_url($redirect_url);

if ($parsed_url === false) {
    die("Error: Unable to parse URL.");
}

$domain = $parsed_url['scheme'] . '://' . $parsed_url['host'];
if (isset($parsed_url['port'])) {
    $domain .= ':' . $parsed_url['port'];
}

$redirect_curl = curl_init($redirect_url);
curl_setopt($redirect_curl, CURLOPT_RETURNTRANSFER, true);
$redirect_response = curl_exec($redirect_curl);

if ($redirect_response === false) {
    die("Error fetching source of redirect URL: " . curl_error($redirect_curl));
}

curl_close($redirect_curl);

// Encrypt the .ts segment URLs
$redirect_response = preg_replace_callback('/(.*?)\.ts/', function ($matches) use ($domain) {
    try {
        $encryptedSegment = encryptData($domain . $matches[0]);
        return "?segment=" . urlencode($encryptedSegment);
    } catch (Exception $e) {
        return $matches[0]; // Fallback in case of error
    }
}, $redirect_response);

header("Content-Type: application/vnd.apple.mpegurl");
echo $redirect_response;
?>