<?php
include "../db.php";

$slug = $_GET['station'] ?? '';

if(!$slug){
die("Station not found");
}

$station = $conn->query("
SELECT * FROM menus
WHERE menu_slug='$slug' AND status=1
")->fetch_assoc();

if(!$station){
die("Station not found");
}

$copyright=$station['menu_link'];
?>

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="width=device-width,initial-scale=1">

<title><?php echo $station['menu_name']; ?></title>

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

<style>

body{
margin:0;
font-family:Arial;
height:100vh;
background:url('../<?php echo $station['menu_image']; ?>') center/cover no-repeat;
}

/* overlay */

.overlay{
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
background:rgba(0,0,0,0.6);
}

/* center content */

.station-box{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
text-align:center;
color:white;
z-index:2;
}

.station-box img{
width:150px;
height:150px;
border-radius:12px;
object-fit:cover;
margin-bottom:15px;
}

/* PLAY BUTTON */

.playBtn{
margin-top:15px;
padding:12px 28px;
border:none;
background:#ff3d3d;
color:white;
font-size:16px;
border-radius:25px;
cursor:pointer;
}

/* PLAYER */

.player{
position:fixed;
bottom:40px;
left:0;
right:0;
background:white;
padding:6px;
height:60px;
display:flex;
flex-direction:column;
justify-content:center;
box-shadow:0 -2px 6px rgba(0,0,0,0.2);
}

#nowPlaying{
font-size:13px;
margin-bottom:3px;
}

audio{
width:100%;
height:32px;
}

/* FOOTER */

.footer{
position:fixed;
bottom:0;
left:0;
right:0;
height:40px;
background:#009688;
color:white;
display:flex;
align-items:center;
justify-content:center;
font-size:13px;
}

/* LIVE indicator */

.live{
color:red;
font-weight:bold;
animation:blink 1s infinite;
}

@keyframes blink{
0%{opacity:1}
50%{opacity:0.3}
100%{opacity:1}
}

</style>

</head>

<body>

<div class="overlay"></div>

<div class="station-box">

<img src="../<?php echo $station['menu_image']; ?>">

<h2><?php echo $station['menu_name']; ?></h2>

<div class="live">● LIVE RADIO</div>

<button id="playBtn" class="playBtn" onclick="startRadio()">
▶ PLAY RADIO
</button>

</div>

<div class="player">

<div id="nowPlaying">
Now Playing : <?php echo $station['menu_name']; ?>
</div>

<div id="bufferStatus">
Tap PLAY to start
</div>

<audio id="player" controls></audio>

</div>

<div class="footer">
<?php echo $copyright; ?>
</div>

<script>

const player=document.getElementById("player");
const bufferStatus=document.getElementById("bufferStatus");
const playBtn=document.getElementById("playBtn");

let streamURL="<?php echo $station['stream_url']; ?>";
let streamType="<?php echo $station['stream_type']; ?>";
let stationID="<?php echo $station['id']; ?>";

let hls=null;
let retryCount=0;
let maxRetries=5;

let adList=[];
let playingAd=false;
let adPlayer=null;

let lastAdTimePlayed="";
let playedClockAds={};

let started=false;

/* LOAD ADS */

fetch("../get_channel_ads.php?menu_id="+stationID)
.then(res=>res.json())
.then(data=>{
adList=data;
});

/* START RADIO */

function startRadio(){

if(started) return;

started=true;

playBtn.innerHTML="🔴 ON AIR";

playStream();

}

/* PLAY STREAM */

function playStream(){

bufferStatus.innerHTML="Connecting...";

if(hls){
hls.destroy();
hls=null;
}

player.pause();
player.src="";
player.load();

let liveURL=streamURL+"?t="+Date.now();

if(streamType==="HLS"){

if(Hls.isSupported()){

hls=new Hls();

hls.loadSource(liveURL);
hls.attachMedia(player);

hls.on(Hls.Events.MANIFEST_PARSED,function(){
player.play().catch(()=>{});
});

}

}else{

player.src=liveURL;
player.play().catch(()=>{});

}

}

/* WHEN PLAYING */

player.addEventListener("playing",function(){

bufferStatus.innerHTML="LIVE";

retryCount=0;

});

/* PAUSE RESTART */

player.addEventListener("pause",function(){

if(playingAd) return;

/* update button */

playBtn.innerHTML="▶ PLAY RADIO";

/* auto restart after short delay */

setTimeout(function(){

if(player.paused && started && !playingAd){

bufferStatus.innerHTML="Reconnecting...";

playStream();

}

},300);

});

/* RECONNECT */

player.addEventListener("error",function(){

retryCount++;

if(retryCount>=maxRetries){

bufferStatus.innerHTML="Waiting for reconnect...";
return;

}

bufferStatus.innerHTML="Reconnecting...";

setTimeout(playStream,4000);

});

/* NETWORK RETURN */

window.addEventListener("online",function(){

setTimeout(playStream,500);

});

/* HEALTH CHECK */

setInterval(function(){

if(!started) return;

if(player.readyState<2 && !playingAd){

retryCount++;

if(retryCount>=maxRetries){

bufferStatus.innerHTML="Waiting for reconnect...";
return;

}

bufferStatus.innerHTML="Reconnecting...";

playStream();

}

},5000);

/* PLAY AD */

function playMidAd(){

if(adList.length==0) return;

playingAd=true;

let ad=adList[Math.floor(Math.random()*adList.length)];

player.volume=0.1;

adPlayer=new Audio("../"+ad.ad_audio);

adPlayer.play();

adPlayer.onended=function(){

player.volume=1;

playingAd=false;

};

}

/* AD SCHEDULER */

setInterval(checkClockAds,1000);

function checkClockAds(){

if(adList.length==0 || !started) return;

let now=new Date();

let hour=now.getHours();
let minute=now.getMinutes();

let currentMinute=
String(hour).padStart(2,'0')+":"+
String(minute).padStart(2,'0');

let weekdayMap={
0:"sun",
1:"mon",
2:"tue",
3:"wed",
4:"thu",
5:"fri",
6:"sat"
};

let todayName=weekdayMap[now.getDay()];

let todayDate=now.toISOString().split('T')[0];

adList.forEach(function(ad){

/* expiry check */

if(ad.expiry_date && ad.expiry_date !== "0000-00-00"){

if(todayDate > ad.expiry_date) return;

}

/* weekday check */

if(ad.weekdays && ad.weekdays !== "all"){

let allowed = ad.weekdays.split(",");

if(!allowed.includes(todayName)) return;

}

let startHour=parseInt(ad.ad_time.split(":")[0]);
let repeat=parseInt(ad.repeat_hours)||0;

if(repeat>0){

let diff=hour-startHour;

if(diff<0) return;

if(diff%repeat!==0) return;

}

let adMinute=ad.ad_time.substring(0,5);

if(adMinute!==currentMinute) return;

if(playingAd) return;

if(lastAdTimePlayed===currentMinute) return;

let stored=localStorage.getItem("playedAd_"+ad.id);

if(stored===currentMinute) return;

playedClockAds[ad.id]=true;

localStorage.setItem("playedAd_"+ad.id,currentMinute);

lastAdTimePlayed=currentMinute;

playMidAd();

});

}

</script>

</body>
</html>