<?php
include "db.php";

$settings=$conn->query("SELECT * FROM site_settings WHERE id=1")->fetch_assoc();

$columns=$settings['menu_columns'];
$padding=$settings['menu_padding'];
$imageHeight=$settings['menu_image_height'];
$radius=$settings['menu_border_radius'];
$titleSize=$settings['menu_title_size'];
$gridGap=$settings['menu_grid_gap'];
$titleGap=$settings['menu_title_gap'];

$headerTitle=$settings['header_title'];
$headerHeight=$settings['header_height'];
$footerText=$settings['footer_text'];
?>

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?php echo $headerTitle; ?></title>

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

<style>

body{
font-family:Arial;
margin:0;
background:#f2f2f2;
padding-bottom:120px;
}

/* HEADER */

header{
background:#009688;
color:white;
height:<?php echo $headerHeight; ?>px;
display:flex;
align-items:center;
justify-content:center;
font-size:20px;
font-weight:bold;
}

/* SEARCH BAR */
/* SEARCH BAR */

.search-bar{
background:white;
padding:10px 12px;
border-bottom:1px solid #ddd;
position:sticky;
top:0;
z-index:100;
}

.search-box{
position:relative;
max-width:700px;
margin:auto;
}

.search-box input{
width:100%;
padding:12px 12px 12px 40px;
border:1px solid #ddd;
border-radius:30px;
font-size:15px;
outline:none;
box-sizing:border-box;
transition:0.2s;
}

.search-box input:focus{
border-color:#009688;
box-shadow:0 0 0 2px rgba(0,150,136,0.15);
}

.search-icon{
position:absolute;
left:12px;
top:50%;
transform:translateY(-50%);
font-size:16px;
color:#777;
}

/* MOBILE OPTIMIZATION */

@media(max-width:600px){

.search-bar{
padding:8px;
}

.search-box input{
font-size:14px;
padding:10px 10px 10px 36px;
}

}

/* GRID */

.products{
display:grid;
grid-template-columns:repeat(<?php echo $columns; ?>,1fr);
gap:<?php echo $gridGap; ?>px;
padding:<?php echo $padding; ?>px;
}

/* CARD */

.card{
background:white;
padding:<?php echo $padding; ?>px;
border-radius:8px;
box-shadow:0 2px 6px rgba(0,0,0,0.1);
cursor:pointer;
text-align:center;
}

/* IMAGE */

.card img{
width:100%;
height:<?php echo $imageHeight; ?>px;
object-fit:cover;
border-radius:<?php echo $radius; ?>px;
}

/* TITLE */

.card h3{
margin-top:<?php echo $titleGap; ?>px;
font-size:<?php echo $titleSize; ?>px;
margin-bottom:0;
}

/* PLAYER */

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

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

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

/* 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;
}

</style>
</head>

<body>

<header>
<?php echo $headerTitle; ?>
</header>

<div class="search-bar">
<div class="search-box">
<span class="search-icon">🔍</span>
<input type="text" id="searchInput" placeholder="Search radio station...">
</div>
</div>

<div class="products" id="productList"></div>

<div class="player">

<div id="nowPlaying">Now Playing : None</div>

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

</div>

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

<script>

fetch("track_visit.php");

const player=document.getElementById("player");
const nowPlaying=document.getElementById("nowPlaying");
const searchInput=document.getElementById("searchInput");

let hls=null;
let currentURL="";
let currentType="";
let allStations=[];

let adList=[];
let adTimer=null;
let currentMenuId=null;
let playingAd=false;

/* LOAD STATIONS */

fetch("get_menus.php")
.then(res=>res.json())
.then(data=>{

allStations=data;
renderStations(data);

});


function renderStations(data){

let html="";

data.forEach(menu=>{

html+=`
<div class="card"
onclick="startStation('${menu.id}','${menu.stream_url}','${menu.menu_name}','${menu.stream_type}')">

<img src="${menu.menu_image}">
<h3>${menu.menu_name}</h3>

</div>
`;

});

document.getElementById("productList").innerHTML=html;

}

/* SEARCH FILTER */

searchInput.addEventListener("keyup",function(){

let keyword=this.value.toLowerCase();

let filtered=allStations.filter(station =>
station.menu_name.toLowerCase().includes(keyword)
);

renderStations(filtered);

});

/* PLAY STREAM */
function startStation(menu_id,url,name,type){

currentMenuId=menu_id;

/* start radio immediately */

playStream(url,name,type);

/* load ads in background */

fetch("get_channel_ads.php?menu_id="+menu_id)

.then(res=>res.json())

.then(data=>{

adList=data;
console.log("Loaded Ads:", adList);

startAdTimer(url,name,type);

})

.catch(function(){

adList=[];

});

}

function playStream(url,name,type){

currentURL=url;
currentType=type;

nowPlaying.innerHTML="Now Playing : "+name;

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

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

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

if(type==="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(()=>{});

}

}

/* AUTO RESTART */

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

setTimeout(function(){

if(player.paused && currentURL && !playingAd){
playStream(currentURL,nowPlaying.innerText.replace("Now Playing : ",""),currentType);
}

},300);

});

/* ERROR RECONNECT */

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

setTimeout(function(){

if(currentURL){
playStream(currentURL,nowPlaying.innerText.replace("Now Playing : ",""),currentType);
}

},1000);

});

/* NETWORK RECOVERY */

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

setTimeout(function(){

if(currentURL){
playStream(currentURL,nowPlaying.innerText.replace("Now Playing : ",""),currentType);
}

},500);

});

/* HEALTH CHECK */

setInterval(function(){

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

playStream(currentURL,nowPlaying.innerText.replace("Now Playing : ",""),currentType);

}

},5000);

/* AD TIMER */

function startAdTimer(url,name,type){
console.log("Ad Timer Started");

if(adTimer){
clearInterval(adTimer);
}

if(adList.length==0){
return;
}

let interval = parseInt(adList[0].ad_interval) * 1000;

adTimer=setInterval(function(){

playMidAd(url,name,type);

},interval);

}

/* PLAY AD */

function playMidAd(url,name,type){

if(playingAd) return;

playingAd=true;

/* pick random ad */

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

/* pause radio */

player.pause();

/* show ad label */

nowPlaying.innerHTML="Sponsored Ad";

/* play ad audio */

player.src=ad.ad_audio;

player.play();

/* when ad finishes */

player.onended=function(){

playingAd=false;

/* resume radio */

playStream(url,name,type);

};

}

</script>

</body>
</html>