<?php
include("db.php");

/* SETTINGS */

$settings=mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM site_settings WHERE id=1"));

/* STREAMS */

$streams_query = mysqli_query($conn,"SELECT * FROM streams ORDER BY id ASC");

$streams_array = [];

while($row = mysqli_fetch_assoc($streams_query)){
    $streams_array[] = $row;
}

/* DATA */

$slides=mysqli_query($conn,"SELECT * FROM sliders");
$services=mysqli_query($conn,"SELECT * FROM services ORDER BY sort_order ASC");
$ticker=mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM ticker LIMIT 1"));
?>

<!DOCTYPE html>
<html>

<head>

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

<title><?php echo $settings['app_name']; ?></title>

<link href="https://fonts.googleapis.com/css2?family=<?php echo $settings['google_font']; ?>&display=swap" rel="stylesheet">

<style>

*{
box-sizing:border-box;
margin:0;
padding:0;
}

body{
font-family:'<?php echo $settings['google_font']; ?>',sans-serif;
background:#f4f6f9;
}

/* HEADER */

.header{
background:#0f6c74;
color:white;
padding:15px;
text-align:center;
font-size:22px;
font-weight:bold;
margin-bottom:2px;
}

/* SEARCH BAR */

.search-bar{
display:flex;
align-items:center;
background:white;
border-radius:28px;
padding:0 12px;
gap:8px;
max-width:600px;
width:95%;
margin:10px auto;
height:42px;
box-shadow:0 1px 4px rgba(0,0,0,0.12);

position:sticky;
top:0;
z-index:999;
}

.search-bar input{
flex:1;
border:none;
outline:none;
font-size:16px;
}

.clear-btn{
font-size:18px;
cursor:pointer;
color:#999;
display:none;
}

.mic{
width:28px;
height:28px;
padding:5px;
border-radius:50%;
background:#f1f3f4;
cursor:pointer;
fill:#5f6368;
}

.mic.listening{
background:#ffe5e5;
fill:red;
}

/* SLIDER */

.carousel{
width:<?php echo $settings['slider_width']; ?>%;
height:<?php echo $settings['slider_height']; ?>px;
margin:auto;
overflow:hidden;
background:#ddd;
margin:1px auto 1px auto;
}

.track{
display:flex;
transition:transform .6s ease-in-out;
}

.track a{
width:100%;
flex-shrink:0;
}

.track img{
width:100%;
height:<?php echo $settings['slider_height']; ?>px;
object-fit:cover;
}

/* TICKER */

.ticker{
background:#ff9900;
color:white;
font-size:<?php echo $settings['ticker_font_size']; ?>px;
overflow:hidden;
white-space:nowrap;
padding:8px;
}

.ticker span{
display:inline-block;
padding-left:100%;
animation:ticker 18s linear infinite;
}

@keyframes ticker{
0%{transform:translateX(0);}
100%{transform:translateX(-100%);}
}

/* SERVICES */

.services{
display:grid;
grid-template-columns:repeat(<?php echo $settings['menu_columns']; ?>,1fr);
gap:15px;
padding:20px;
max-width:900px;
margin:auto;
}

.card{
background:white;
padding:<?php echo $settings['card_padding']; ?>px;
border-radius:12px;
text-align:center;
box-shadow:0 2px 6px rgba(0,0,0,0.08);
transition:.3s;
}

.card:hover{
transform:translateY(-3px);
}

.card img{
width:<?php echo $settings['menu_icon_width']; ?>px;
height:<?php echo $settings['menu_icon_height']; ?>px;
margin-bottom:5px;
}

.card a{
text-decoration:none;
color:#333;
font-size:14px;
}

/* FOOTER */

.footer{
background:#111;
color:#aaa;
text-align:center;
padding:18px;
margin-top:20px;
font-size:14px;
}

/* MOBILE */

@media(max-width:768px){

.search-bar{
width:92%;
max-width:none;
margin:10px auto;
}

.carousel{
height:220px;
}

.track img{
height:220px;
}

}
.no-result{
text-align:center;
padding:20px;
font-size:16px;
color:#777;
max-width:900px;
margin:auto;
display:none;
}

</style>

</head>

<body>

<div class="header">
<?php echo $settings['app_name']; ?>
</div>

<!-- SEARCH -->

<div class="search-bar">

<input
type="text"
id="searchInput"
placeholder="Search services..."
onkeyup="filterServices();toggleClear()"
>

<span id="clearBtn" class="clear-btn" onclick="clearSearch()">✕</span>

<svg id="micIcon" class="mic" onclick="startVoiceSearch()" viewBox="0 0 24 24">
<path d="M12 14a3 3 0 003-3V5a3 3 0 10-6 0v6a3 3 0 003 3zm5-3a1 1 0 112 0 7 7 0 01-6 6.92V21h3a1 1 0 110 2H8a1 1 0 110-2h3v-3.08A7 7 0 015 11a1 1 0 112 0 5 5 0 0010 0z"/>
</svg>

</div>

<!-- SLIDER -->

<div class="carousel">

<div class="track" id="track">

<?php while($s=mysqli_fetch_assoc($slides)){ ?>

<a href="<?php echo $s['link']; ?>">

<img src="uploads/sliders/<?php echo $s['image']; ?>">

</a>

<?php } ?>

</div>

</div>

<!-- TICKER -->

<div class="ticker">
<span>
<?php echo $ticker['content']; ?>
</span>
</div>

<!-- NO RESULT MESSAGE -->

<div id="noResult" class="no-result" style="display:none;">
No result found
</div>

<!-- SERVICES -->

<div class="services">

<?php while($srv=mysqli_fetch_assoc($services)){ ?>

<div class="card service-card">

<a href="<?php echo $srv['link']; ?>">

<?php
if(!empty($srv['image_url'])){
$img=$srv['image_url'];
}else{
$img="uploads/services/".$srv['image'];
}
?>

<img src="<?php echo $img; ?>" loading="lazy">

<p><?php echo $srv['title']; ?></p>

</a>

</div>

<?php } ?>

</div>

<!-- FOOTER -->

<div class="footer">

<?php echo $settings['footer_content']; ?>

</div>

<script>

/* SEARCH */

function filterServices(){

let input=document.getElementById("searchInput").value.toLowerCase();
let cards=document.querySelectorAll(".service-card");
let visibleCount=0;

cards.forEach(card=>{

let text=card.innerText.toLowerCase();

if(text.includes(input)){
card.style.display="block";
visibleCount++;
}else{
card.style.display="none";
}

});

let noResult=document.getElementById("noResult");

if(input !== "" && visibleCount === 0){
noResult.style.display="block";
}else{
noResult.style.display="none";
}

}

/* CLEAR BUTTON */

function toggleClear(){

let input=document.getElementById("searchInput");

document.getElementById("clearBtn").style.display=input.value?"block":"none";

}

function clearSearch(){

document.getElementById("searchInput").value="";
toggleClear();
filterServices();

}

/* VOICE SEARCH */

function startVoiceSearch(){

const SpeechRecognition=window.SpeechRecognition||window.webkitSpeechRecognition;

if(!SpeechRecognition){
alert("Voice search not supported");
return;
}

const recognition=new SpeechRecognition();

recognition.lang="en-US";

const mic=document.getElementById("micIcon");

mic.classList.add("listening");

recognition.start();

recognition.onresult=function(e){

document.getElementById("searchInput").value=e.results[0][0].transcript;

filterServices();
toggleClear();

};

recognition.onend=function(){

mic.classList.remove("listening");

};

}

/* AUTO SLIDER */

let index=0;

const track=document.getElementById("track");

const slides=track.children;

function slide(){

index++;

if(index>=slides.length){
index=0;
}

track.style.transform="translateX(-"+index*100+"%)";

}

setInterval(slide,3500);

</script>
<!-- Reserve space for player -->

<div style="height:30px;"></div>
<iframe 
id="radioFrame"
srcdoc='<meta charset="utf-8"/>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

<style>
@import url("https://fonts.googleapis.com/css2?family=Open+Sans&display=swap");
body{
  font-family:"Open Sans",sans-serif;
  margin:0;
  background:#ffffff;
}
audio{
  width:100%;
  height:50px;
  outline:none;
  border:none;
  box-shadow:none;
  display:block;
  background:#ffffff;
}
.no-result{
text-align:center;
padding:20px;
font-size:16px;
color:#777;
display:none;
max-width:900px;
margin:auto;
}
</style>

<center>
<audio id="mergedPlayer" controls autoplay playsinline controlsList="nodownload" style="width:100%;height:30px;"></audio>
</center>

<script>
const player=document.getElementById("mergedPlayer");
const retryDelay=2000;
const icecastTimeout=8000;
const icecastRetryLimit=3;

const streams=<?php echo json_encode($streams_array); ?>;

streams.forEach(s=>{
s.enabled = s.enabled == 1;
});

let currentIndex = streams.findIndex(s => s.enabled);
if(currentIndex === -1) currentIndex = 0;

let hlsInstance=null,icecastRetries=0,promoPlayed=false;

function playNext(){
if(currentIndex>=streams.length)currentIndex=0;
let stream=streams[currentIndex],tries=0;
while(!stream.enabled&&tries<streams.length){
currentIndex++;if(currentIndex>=streams.length)currentIndex=0;
stream=streams[currentIndex];tries++;
}
icecastRetries=0;
if(stream.type==="MP3"){
if(promoPlayed){currentIndex++;playNext();}
else playMP3(stream);
}else if(stream.type==="HLS") playHLS(stream);
else playIcecast(stream);
}

function playMP3(s){
player.src=s.url+"?t="+Date.now();
player.play().catch(()=>{});
player.onended=player.onerror=()=>{promoPlayed=true;currentIndex++;playNext();};
}

function playHLS(s){
if(hlsInstance)hlsInstance.destroy();
hlsInstance=new Hls();
hlsInstance.loadSource(s.url+"?t="+Date.now());
hlsInstance.attachMedia(player);
hlsInstance.on(Hls.Events.MANIFEST_PARSED,()=>player.play().catch(()=>{}));
hlsInstance.on(Hls.Events.ERROR,(e,d)=>{
if(d.fatal){
if(d.type===Hls.ErrorTypes.NETWORK_ERROR) setTimeout(()=>playHLS(s),retryDelay);
else if(d.type===Hls.ErrorTypes.MEDIA_ERROR) hlsInstance.recoverMediaError();
else{hlsInstance.destroy();hlsInstance=null;currentIndex++;playNext();}
}});
}

function playIcecast(s){
player.src=s.url+"?t="+Date.now();
let started=false;
let timeout=setTimeout(()=>{if(!started)handleIcecastFailure(s);},icecastTimeout);
player.play().then(()=>{started=true;clearTimeout(timeout);icecastRetries=0;}).catch(()=>{});
player.onerror=()=>{clearTimeout(timeout);handleIcecastFailure(s);};
}

function handleIcecastFailure(s){
if(icecastRetries<icecastRetryLimit){
icecastRetries++;
setTimeout(()=>playIcecast(s),retryDelay*Math.pow(2,icecastRetries-1));
}else{icecastRetries=0;currentIndex++;playNext();}
}

player.addEventListener("pause",()=>setTimeout(playNext,retryDelay));

document.addEventListener("keydown",e=>{
if((e.ctrlKey&&["s","S","u","U"].includes(e.key))||e.key==="F12")e.preventDefault();
});
document.addEventListener("selectstart",e=>{
if(!e.target.closest("audio"))e.preventDefault();
});

playNext();
</script>'
style="position:fixed;bottom:0px;left:0;width:100%;height:30px;border:none;background:#ffffff;z-index:9999;"
allow="autoplay">
</iframe>

</body>
</html>