<?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;
position:relative;
min-height:200px;
}

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

/* HOME BUTTON */

.home-btn{
position:absolute;
right:25px;
top:52%;
transform:translateY(-50%);
background:transparent;
border:none;
cursor:pointer;
padding:0;
}

.home-btn img{
height:32px;
width:32px;
}

/* LOADER */

.loader{
display:none;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
background:rgba(255,255,255,0.9);
align-items:center;
justify-content:center;
flex-direction:column;
z-index:5;
}

.spinner{
width:50px;
height:50px;
border:5px solid #ddd;
border-top:5px solid #009688;
border-radius:50%;
animation:spin 1s linear infinite;
}

.loading-text{
margin-top:15px;
font-size:15px;
color:#333;
}

@keyframes spin{
0%{transform:rotate(0deg);}
100%{transform:rotate(360deg);}
}

.products.loading .card{
opacity:0.3;
pointer-events:none;
}
</style>
</head>

<body>

<header style="position:relative;">
<?php echo $headerTitle; ?>

<button onclick="goHome()" class="home-btn">
<img src="https://cdn-icons-png.flaticon.com/128/9073/9073243.png">
</button>

</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 id="loader" class="loader">
<div class="spinner"></div>
<div class="loading-text">Connecting to radio...</div>
</div>

</div>
<div class="player">

<div id="nowPlaying">Now Playing : None</div>
<div id="bufferStatus" style="font-size:12px;color:#777;margin-bottom:4px;">
Connecting...
</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 loader=document.getElementById("loader");
const nowPlaying=document.getElementById("nowPlaying");
const bufferStatus=document.getElementById("bufferStatus");
const searchInput=document.getElementById("searchInput");

let hls=null;
let currentURL="";
let currentType="";
let currentStationName="";
let allStations=[];
let retryCount = 0;
let maxRetries = 5;

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

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

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

})

.catch(function(){

adList=[];

});

}

function playStream(url,name,type){
loader.style.display="flex";
currentURL=url;
currentType=type;
currentStationName = name;
bufferStatus.innerHTML="Connecting to stream...";
player.volume = 1;

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

hls.on(Hls.Events.ERROR,function(event,data){

if(data.fatal){

loader.style.display="none";
nowPlaying.innerHTML="⚠ Station Unreachable";
bufferStatus.innerHTML="HLS Stream Offline";

}

});

}

}else{

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

}

}

/* AUTO RESTART */

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

bufferStatus.innerHTML="";

if(retryCount >= maxRetries){
retryCount = 0;
}

setTimeout(function(){

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

retryCount++;
playStream(currentURL,currentStationName,currentType);

}

},300);

});

/* ERROR RECONNECT */

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

retryCount++;

if(retryCount >= maxRetries){

loader.style.display="none";
nowPlaying.innerHTML="⚠ Station Unreachable";
bufferStatus.innerHTML="Waiting for reconnect...";

return;

}

bufferStatus.innerHTML="Retrying... ("+retryCount+"/"+maxRetries+")";

setTimeout(function(){

if(currentURL){
playStream(currentURL,currentStationName,currentType);
}

},4000);

});

/* NETWORK RECOVERY */

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

retryCount = 0;

setTimeout(function(){

if(currentURL){
playStream(currentURL,currentStationName,currentType);
}

},500);

});

/* HEALTH CHECK */

setInterval(function(){

if(retryCount >= maxRetries) return;

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

retryCount++;
playStream(currentURL,currentStationName,currentType);

}

},5000);

/* CLOCK AD CHECKER */

setInterval(checkClockAds,1000);

/* reset played ads every minute */

setInterval(function(){

playedClockAds = {};

/* clear stored ad flags */

Object.keys(localStorage).forEach(function(key){

if(key.startsWith("playedAd_")){
localStorage.removeItem(key);
}

});

},60000);


/* PLAY AD */

function playMidAd(url,name,type){

if(playingAd) return;

playingAd=true;

/* pick random ad */

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

console.log("Overlay Ad:", ad.ad_audio);

/* show ad message */

nowPlaying.innerHTML="Sponsored Ad";

/* reduce radio volume */

player.volume = 0.1;

/* create persistent ad player */

adPlayer = new Audio(ad.ad_audio);   // ❗ removed "/" prefix
adPlayer.volume = 1;

/* safety: restore volume if ad fails */

let restoreTimer = setTimeout(function(){
console.log("Ad fallback restore");
player.volume = 1;
playingAd = false;
nowPlaying.innerHTML = "Now Playing";
}, 20000); // restore after 20s if nothing happens

/* play ad */

adPlayer.play().then(()=>{

console.log("Ad started");

}).catch(err=>{
console.log("Ad play blocked:", err);

/* restore volume if blocked */

clearTimeout(restoreTimer);
player.volume = 1;
playingAd = false;
nowPlaying.innerHTML="Now Playing : " + currentStationName;

});

/* when ad finishes */

adPlayer.onended = function(){

console.log("Ad finished");

clearTimeout(restoreTimer);

player.volume = 1;

playingAd=false;

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

};
}

function checkClockAds(){

if(adList.length==0 || !currentURL) 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');

/* weekday detection */

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

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

/* today date */

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

adList.forEach(function(ad){

/* expiry check */

if(ad.expiry_date && todayDate > ad.expiry_date){
return;
}

/* weekday check */

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

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

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

}

/* repeat logic */

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;

}

/* exact minute check */

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;

if(playedClockAds[ad.id]) return;

playedClockAds[ad.id] = true;

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

lastAdTimePlayed = currentMinute;

console.log("Scheduled Ad Triggered:", ad.ad_name);

playMidAd(
currentURL,
currentStationName,
currentType
);

});

}

function goHome(){

window.location.reload();

}

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

loader.style.display="none";
bufferStatus.innerHTML="";
retryCount = 0;

});

player.addEventListener("error",function(){
loader.style.display="none";
});
</script>

</body>
</html>