<?php  
$id=isset($_GET["id"])? $_GET["id"] : (isset($_GET["ch"])? $_GET["ch"] :exit);
if (empty($id)) {
    echo "频道参数不能为空";
    exit;
}

$id = strtolower($id);
$id = preg_replace('/\s+/', '', $id);
$id = str_replace("-", "", $id);

if (stripos($id, "cctv") !== false && stripos($id, "中数") === false) {
    $id = getCCTVepgId($id); 
}

function getCCTVepgId($string) {
    if (strcasecmp($string, 'CCTV4欧洲') === 0 || strcasecmp($string, 'cctv4euo') === 0) {
        return 'cctv4euo';
    }
    if (strcasecmp($string, 'CCTV4美洲') === 0 || strcasecmp($string, 'cctv4ame') === 0) {
        return 'cctv4ame';
    }
    $pattern = "/CCTV.*?\d+/i";
    if (preg_match($pattern, $string, $matches)) {  
        $retStr = $matches[0];
        if (strpos($string, "+") !== false) {
            $retStr .= "+";
        } else if (stripos($string, "4k") !== false) {
            $retStr .= "k";
        }
        return $retStr;  
    } else {     
        return false;  
    }
}

if (!empty($id)) { 
    $idMappingContent = file_get_contents('EPG_LOGO_CH.txt');
    $idMappings = [];
    $lines = explode("\n", $idMappingContent);
    foreach ($lines as $line) {
        $mapping = explode('#', $line, 2);
        if (count($mapping) == 2) {
            $channelId = trim($mapping[0]);
            $idsForChannel = array_map('trim', explode(',', $mapping[1]));
            if (!empty($idsForChannel)) {
                $idsForChannel = array_map(function($item) {
                    $item = trim(strtolower($item));
                    return preg_replace('/\s+/', '', $item);
                }, $idsForChannel);
            }          
            $idMappings[$channelId] = $idsForChannel;
        }
    }
    $found = false; 

    foreach ($idMappings as $channelId => $mappedIds) {
        if (strcasecmp($id, $channelId) === 0 || in_array($id, $mappedIds)) {
			$channelId= strtolower($channelId);
            $id = $channelId;
            $found = true; 
            break; 
        }
    }

    if ($found) {
        $imageDir = './tv_logo/';
        $dir = opendir($imageDir);

        while (false !== ($file = readdir($dir))) {
            if ($file == '.' || $file == '..') {
                continue;
            }

            $fileWithoutExtension = strtolower(pathinfo($file, PATHINFO_FILENAME));

            if ($fileWithoutExtension == $id) {
                header('Content-Type: image/png');
                readfile($imageDir . $file);
                closedir($dir);
                exit;
            }
        }

        closedir($dir);
    } else {
        $logo = "makelogo.php?ch=".$id;
		header('location:'.$logo);
		
    }
}
?>
