<?php
include '../sitedetails.php';
include '../analytics.php';
include('externalhead.php');
include('../header.php');

// --- CACHING LOGIC ---
$cacheExpire = 172800; // 48 hours
$requestedUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$cacheFile = 'cache/' . md5($requestedUrl) . '.html';

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheExpire && empty($_POST)) {
    echo file_get_contents($cacheFile);
    exit();
}

ob_start(); // Start Output Buffering

// --- HELPER FUNCTIONS ---
function urlformat($string) {
    $string = strtolower($string);
    $string = str_replace([' ', '_'], '-', $string);
    $string = preg_replace('/[^a-z0-9\-]/', '', $string);
    $string = preg_replace('/-+/', '-', $string);
    return trim($string, '-');
}

function makeSlug($string) {
    return urlformat($string);
}

// --- URL PARSING & DATABASE ---
$pageurl= $_SERVER['REQUEST_URI'];
$urlcheck = trim(str_replace(['/ringtone/','?source=github'],"",$pageurl));

// Extract Title from URL for backup
$pieces = explode("-", $pageurl);
$first_part = implode(" ", array_splice($pieces, 0, 5));
$replaceitems = ['/ringtone/','2024xvx','2025xvx','mp3','ringbgmsto20','44445zz','ringtones','bgm','ringtone','ring20fblzx4s','movie','?source=github'];
$clean_title_part = str_replace($replaceitems,"",$first_part);
$clean_title = ucwords(str_replace(['/ringtone/','-','downloads','download']," ",$clean_title_part));

include('../databaseconnect.php');
mysqli_set_charset($con, "utf8mb4");

$sql = "SELECT * FROM sitemapcomio WHERE URLSLIST = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $urlcheck);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $urldescription = $row["desc1"];
    $url_lyrics = $row["lyrics"];

    $urlalbum = $row["album"];
    $urllanguage = $row["language"];
    $urlstars = $row["stars"];
    $urlyear = $row["year"];
    $urlindustry = $row["industry"];
    $urlmusicdirectors = $row["musicdirectors"];
    // 1. GET TAGS
    $urltags = isset($row["tags"]) ? $row["tags"] : '';

    // Fallbacks
    $urlalbum_link = urlformat($urlalbum);
    $urllanguage_link = urlformat($urllanguage);
    $urlyear_link = urlformat($urlyear);
    $urlmusic_link = urlformat($urlmusicdirectors);
} else {
    header("HTTP/1.0 404 Not Found");
    echo "<html><head><meta name='robots' content='noindex'><title>Page Not Found</title></head><body>Page not found. <a href='/'>Home</a></body></html>";
    die();
}

// --- SEARCH LOGIC (Performed early to get MP3 link for Schema) ---
$relatedsearchkey2 = trim($clean_title_part);
$keywords = array_filter(explode(' ', $relatedsearchkey2));
$posts_result = null;
$first_mp3_url = ""; // For Schema
$total_downloads_schema = 0;

if (count($keywords) > 0) {
    $likeClauses = array_map(function($k) { return "CONCAT(' ', title, ' ') LIKE ?"; }, $keywords);
    $sql_posts = "SELECT * FROM posts WHERE " . implode(' AND ', $likeClauses) . " LIMIT 6";
    $stmt_posts = $con->prepare($sql_posts);
    $searchTerms = array_map(function($k) { return "% " . $k . " %"; }, $keywords);
    $types = str_repeat('s', count($searchTerms));
    $stmt_posts->bind_param($types, ...$searchTerms);
    $stmt_posts->execute();
    $posts_result = $stmt_posts->get_result();
    
    // Peek at first result for Schema
    if ($posts_result->num_rows > 0) {
        $first_row = $posts_result->fetch_assoc();
        $first_mp3_url = $siteurl . $first_row['download link'];
        $total_downloads_schema = (int)$first_row['download_count'];
        $posts_result->data_seek(0); // Reset pointer for display loop
    }
}

// --- SEO VARIABLES ---
$page_title = "$clean_title - $urlalbum Free $urllanguage Ringtone Download";
$meta_desc = "Download $clean_title - $urlalbum $urllanguage ringtone for free! High-quality 320kbps MP3. Perfect for Android & iPhone. No registration required.";
$canonical_url = $siteurlnav . $pageurl;
$cat_base = isset($urlpatterncat) ? $urlpatterncat : '/ringtone/'; 

// --- SCHEMA JSON-LD GENERATION ---
$schema_data = [
    "@context" => "https://schema.org",
    "@graph" => [
        [
            "@type" => "WebPage",
            "@id" => $canonical_url,
            "url" => $canonical_url,
            "name" => $page_title,
            "description" => $meta_desc,
            "inLanguage" => "en-US",
            "isPartOf" => ["@id" => $siteurlnav . "#website"]
        ],
        [
            "@type" => "BreadcrumbList",
            "itemListElement" => [
                ["@type" => "ListItem", "position" => 1, "name" => "Home", "item" => $siteurlnav],
                ["@type" => "ListItem", "position" => 2, "name" => "$urllanguage Ringtones", "item" => $siteurlnav .'/' . trim($cat_base, '/') . '/' . $urllanguage_link],
                ["@type" => "ListItem", "position" => 3, "name" => $urlalbum, "item" => $canonical_url]
            ]
        ],
        [
            "@type" => "FAQPage",
            "mainEntity" => [
                ["@type" => "Question", "name" => "Is $clean_title ringtone free?", "acceptedAnswer" => ["@type" => "Answer", "text" => "Yes, download $clean_title ringtone from $urlalbum for free in MP3 format."]],
                ["@type" => "Question", "name" => "How to download for iPhone?", "acceptedAnswer" => ["@type" => "Answer", "text" => "Download the MP3 file here and convert it to M4R using iTunes or GarageBand."]]
            ]
        ]
    ]
];

// Add AudioObject if MP3 exists
if (!empty($first_mp3_url)) {
    $schema_data["@graph"][] = [
        "@type" => "AudioObject",
        "name" => "$clean_title Ringtone",
        "description" => "Preview and download $clean_title ringtone.",
        "contentUrl" => $first_mp3_url,
        "encodingFormat" => "audio/mpeg",
        "duration" => "PT30S",
        "uploadDate" => date('c'),
        "interactionStatistic" => [
            "@type" => "InteractionCounter",
            "interactionType" => "https://schema.org/DownloadAction",
            "userInteractionCount" => $total_downloads_schema
        ]
    ];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
<title><?php echo $page_title; ?></title>
<meta name="description" content="<?php echo $meta_desc; ?>" />
<meta property="og:site_name" content="<?php echo $sitename;?>" />
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="music.song" />
<meta property="og:title" content="<?php echo $page_title; ?>" />
<meta property="og:description" content="<?php echo $meta_desc; ?>" />
<meta property="og:url" content="<?php echo $canonical_url; ?>" />
<meta name="author" content="<?php echo $siteauthor;?>" />
<link rel="canonical" href="<?php echo $canonical_url;?>"/>
<link rel="icon" type="image/x-icon" href="/images/<?php echo $faviconurl;?>">
<link rel="stylesheet" type="text/css" href="../css/ringtonelist.css">

<!-- SCHEMA.ORG JSON-LD -->
<script type="application/ld+json">
<?php echo json_encode($schema_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); ?>
</script>

<style>
  body { color: white; background-color: #121212; font-family: sans-serif; }
  a { color: greenyellow; text-decoration: none; }
  a:hover { text-decoration: underline; }
  
  /* Breadcrumbs */
  .breadcrumb-container { padding: 10px 0 15px 0; font-size: 13px; color: #888; }
  .breadcrumb-list { list-style: none; padding: 0; margin: 0; }
  .breadcrumb-list li { display: inline; }
  .breadcrumb-list li+li:before { padding: 0 8px; color: #555; content: "/"; }
  .breadcrumb-list a { text-transform: capitalize; }
  .breadcrumb-list li:last-child { color: #fff; font-weight: 500; }

  /* SEO Headings */
  h1.seo-title { font-size: 16px; line-height: 1.4; margin-bottom: 5px; color: #fff; }
  h2.seo-subtitle { font-size: 13px; color: #aaa; font-weight: normal; margin-top: 0; margin-bottom: 20px; }

  /* Meta Grid */
  .meta-grid { display: grid; grid-template-columns: 1fr; gap: 8px; background: #1e1e1e; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #333; }
  .meta-item { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #2a2a2a; padding-bottom: 8px; font-size: 14px; }
  .meta-item:last-child { border-bottom: none; padding-bottom: 0; }
  .meta-label { font-weight: bold; color: #ccc; }
  .meta-value { text-align: right; }

  /* Player & List Styles */
  .ringtone-list { margin-top: 20px; }
  .ringtone { background: #1e1e1e; border: 1px solid #333; padding: 15px; margin-bottom: 15px; border-radius: 8px; }
  .details h3 { font-size: 12px; margin: 0 0 10px 0; color: #fff; }
  .controls audio { margin-bottom: 10px; height: 40px; }
  .time { font-size: 12px; color: #888; margin-bottom: 10px; }
  .time2 { font-size: 12px; color: #1eeeff; margin-bottom: 10px; }
  p.seo-subtitle {font-size: 14px;}
  .download-button a {
      display: block; background: greenyellow; color: #000; text-align: center;
      padding: 10px; border-radius: 5px; font-weight: bold; text-decoration: none;
  }
  .download-button a:hover { background: #adff2f; }
  
  /* Details & FAQ */
  details { background: #1a1a1a; padding: 10px; border-radius: 5px; margin-bottom: 20px; }
  summary { font-size: 14px;cursor: pointer; color: greenyellow; font-weight: bold; }
  .seo-faq { margin-top: 30px; border-top: 1px solid #333; padding-top: 20px; }
  .seo-faq h3 { font-size: 16px; color: greenyellow; }
  .seo-faq p { font-size: 14px; color: #ccc; line-height: 1.5; }
  
  /* Author Box */
  .author-box { display: flex; align-items: center; gap: 15px; background: #1e1e1e; padding: 15px; border-radius: 12px; margin-top: 30px; border: 1px solid #333; }
  .author-details h3 { margin: 0; font-size: 14px; color: #fff; }
  .author-details p { margin: 3px 0; font-size: 12px; color: #aaa; }

  /* Recent Albums Grid CSS */
  .recent-albums-wrap { margin: 30px 0; padding: 15px; background: #1e1e1e; border-radius: 8px; border: 1px solid #333; }
  .recent-albums-wrap h3 { font-size: 16px; color: #fff; margin-bottom: 15px; border-bottom: 1px solid #333; padding-bottom: 8px; margin-top:0;}
  
  /* Mobile First (100px items) */
  .recent-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 12px; }
  .recent-item { text-decoration: none; color: #fff; text-align: center; display: flex; flex-direction: column; align-items: center; }
  .recent-item:hover { opacity: 0.8; }
  .recent-item:hover span { color: greenyellow; text-decoration: underline; }
  .recent-item img { width: 100%; height: auto; aspect-ratio: 1/1; object-fit: cover; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.5); margin-bottom: 5px; }
  .recent-item span { font-size: 16px; line-height: 1.3; font-weight: 500; color:#ccc;}

  /* Desktop / Larger Screens (150px items) */
  @media (min-width: 768px) {
      .recent-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
  }
</style>
</head>

<body>
<?php include('../searchbar.php'); ?>

<!-- BREADCRUMBS -->
<nav class="breadcrumb-container" aria-label="breadcrumb">
    <ol class="breadcrumb-list">
        <li><a href="/">Home</a></li>
        <li><a href="<?php echo $cat_base . $urllanguage_link; ?>"><?php echo $urllanguage; ?> Ringtones</a></li>
        <li><?php echo $urlalbum; ?></li>
    </ol>
</nav>

<!-- H1 & SUBTITLE -->
<h1 class="seo-title"><?php echo $clean_title; ?> Ringtone Download - <?php echo $urlalbum; ?></h1>
<p class="seo-subtitle">
    Download high-quality <?php echo $urllanguage; ?> ringtones from the movie <?php echo $urlalbum; ?> (<?php echo $urlyear; ?>). 
    Music composed by <?php echo $urlmusicdirectors; ?>. Free MP3 for Android & iOS.
</p>

<!-- META GRID -->
<div class="meta-grid">
    <div class="meta-item">
        <span class="meta-label">Movie / Album</span>
        <span class="meta-value"><a href="<?php echo $urlpatterncat.$urlalbum_link; ?>"><?php echo $urlalbum; ?></a></span>
    </div>
    <div class="meta-item">
        <span class="meta-label">Language</span>
        <span class="meta-value"><a href="<?php echo $urlpatterncat.$urllanguage_link; ?>"><?php echo $urllanguage; ?></a></span>
    </div>
    <div class="meta-item">
        <span class="meta-label">Year</span>
        <span class="meta-value"><a href="<?php echo $urlpatterncat.$urlyear_link; ?>"><?php echo $urlyear; ?></a></span>
    </div>
    <div class="meta-item">
        <span class="meta-label">Music By</span>
        <span class="meta-value"><a href="<?php echo $urlpatterncat.$urlmusic_link; ?>"><?php echo $urlmusicdirectors; ?></a></span>
    </div>
    <div class="meta-item">
        <span class="meta-label">Starring</span>
        <span class="meta-value">
            <?php
            $items = explode(',', $urlstars);
            foreach ($items as $item) {
                echo '<a href="'.$urlpatterncat.makeSlug($item).'">'.trim($item).'</a> ';
            }
            ?>
        </span>
    </div>
    
    <!-- 2. SHOW TAGS HERE -->
    <?php if(!empty($urltags)): ?>
    <div class="meta-item">
        <span class="meta-label">Tags</span>
        <span class="meta-value">
            <?php
            $t_items = explode(',', $urltags);
            foreach ($t_items as $t_item) {
                $clean_t = trim($t_item);
                if(!empty($clean_t)){
                    echo '<a href="'.$urlpatterncat.makeSlug($clean_t).'">'.$clean_t.'</a>, ';
                }
            }
            ?>
        </span>
    </div>
    <?php endif; ?>
</div>

<!-- DESCRIPTION -->
<details>
    <summary>Read Song Description &#8595;</summary>
    <div style="margin-top:10px; font-size:14px; line-height:1.6; color:#ccc;">
        <?php echo nl2br($urldescription); ?>
    </div>
</details>

<details>
    <summary>Read Song Lyrics &#8595;</summary>
    <div style="margin-top:10px; font-size:14px; line-height:1.6; color:#ccc;">
        <?php echo nl2br($url_lyrics); ?>
    </div>
</details>

<!-- RINGTONE LIST RESULTS -->
<?php
if ($posts_result && $posts_result->num_rows > 0) {
    echo "<p style='font-size:14px; margin-bottom:10px;'>".$posts_result->num_rows . " Ringtones Found</p>";
    echo '<div class ="ringtone-list">';

    while($row = $posts_result->fetch_assoc()){
        $download = htmlentities($row['download link']);
        $title = htmlentities($row['title']);
        $duration = htmlentities($row['duration']);
        $download_count = htmlentities($row['download_count']);
        $number = htmlentities($row["No"]);
        $image = htmlentities($row['image'] ?? '');
        
        // Show Image only for first item to save bandwidth/layout shift
        static $showImage = true;
        if ($showImage && !empty($image)) {
            echo "<div style='text-align:center; margin-bottom:15px;'><img src='$image' alt='$title Poster' style='max-width:150px; border-radius:8px;'></div>";
            $showImage = false;
        }

        $audio_tag = "<audio controls preload='none' controlsList='nofullscreen noremoteplayback noplaybackrate foobar novolume'><source src='$siteurl$download' type='audio/mpeg' /></audio>";
        $durationSec = substr($duration, 0, 2);

        echo '<div class ="ringtone">';
            echo "<div class ='details'><h3>$title</h3></div>";
            echo "<div class ='controls'>$audio_tag</div>";
            echo "<div class ='time'>$download_count Downloads &bull; $durationSec Sec &bull; MP3</div>";
            
            echo "<div class ='download-button'>
                    <a href='" . $siteurl.$download . "' title='Download $title Ringtone' onclick='return updateDownloadCount($number, this.href)'>
                       Download Ringtone <span style='font-size:11px; font-weight:normal;'>(MP3)</span>
                    </a>
                  </div>";
        echo '</div>';
    }
    echo '</div>'; // End list
} else {
    echo "<p>No ringtones found for this album.</p>";
}
?>

<h3>VIEW ALL SONGS & BGM :  <a href="<?php echo $urlpatterncat.$urlalbum_link; ?>"><?php echo $urlalbum; ?> Ringtones </a></h3>

<!-- FAQ  -->
<div class="seo-faq">
    <h3>FAQ: <?php echo $clean_title; ?> Ringtones</h3>
    <p><strong> Who penned the lyrics for <?php echo $clean_title; ?> ?</strong><br>Lyrics Written By.</p>
    <p><strong>  Who is the music composer for <?php echo $clean_title; ?> ?</strong><br> composed by <?php echo $urlmusicdirectors; ?></p>
    <p><strong>What is the audio quality?</strong><br>We provide high-quality 320kbps MP3 files.</p>
</div>

<!-- AUTHOR BOX -->
<?php
$author_name = "Mounika";
$author_image = "/images/authors/mounika.jpg";
$author_slug = "/author/mounika";
?>
<div class="author-box" itemscope itemtype="https://schema.org/Person">
    <a href="<?php echo $author_slug; ?>" itemprop="url">
        <img src="<?php echo $author_image; ?>" alt="<?php echo $author_name; ?>" itemprop="image" width="60" height="60" style="border-radius:50%; object-fit:cover;">
    </a>
    <div class="author-details">
        <p>Uploaded by:</p>
        <h3 itemprop="name"><a href="<?php echo $author_slug; ?>" style="color:#fff;"><?php echo $author_name; ?></a></h3>
        <p>Curator of trending <?php echo $urllanguage; ?> ringtones.</p>
    </div>
</div>

<!-- 3. MORE RINGTONES FROM SAME ALBUM SECTION -->
<div style="margin-top:30px;">
    <h2>More from <?php echo htmlspecialchars($urlalbum); ?></h2>
    <div class="ringtone-list">
    <?php
    // Query sitemapcomio for entries with same Album but different slug
    $sql_same_album = "SELECT URLSLIST FROM sitemapcomio WHERE album = ? AND URLSLIST != ? LIMIT 5";
    if($stmt_sa = $con->prepare($sql_same_album)) {
        $stmt_sa->bind_param("ss", $urlalbum, $urlcheck);
        $stmt_sa->execute();
        $result_sa = $stmt_sa->get_result();

        if ($result_sa && $result_sa->num_rows > 0) {
            while ($row_sa = $result_sa->fetch_assoc()) {
                
                $sa_slug = $row_sa['URLSLIST'];
                $sa_display_title = ucwords(str_replace("-", " ", $sa_slug));
                
                // Fetch the MP3 audio for this slug (to make it playable)
                // We use keyword search on posts table just like the main logic
                $sa_search_string = str_replace(['ringtone', 'download', 'mp3', 'bgm', '-'], ' ', $sa_slug);
                $sa_search_string = trim($sa_search_string);
                
                $sql_sa_post = "SELECT * FROM posts WHERE title LIKE ? LIMIT 1";
                $stmt_sa_post = $con->prepare($sql_sa_post);
                $sa_like = "%" . $sa_search_string . "%";
                $stmt_sa_post->bind_param("s", $sa_like);
                $stmt_sa_post->execute();
                $res_sa_post = $stmt_sa_post->get_result();

                if ($res_sa_post->num_rows > 0) {
                    $p_row = $res_sa_post->fetch_assoc();
                    $p_download = htmlentities($p_row['download link']);
                    $p_id = htmlentities($p_row["No"]);
                    $p_duration = substr(htmlentities($p_row['duration']), 0, 2);
                    $full_link = "/ringtone/" . $sa_slug; 
                    
                    echo '<div class="ringtone">';
                        echo '<div class="details">
                                <h3><a href="'.$full_link.'" style="color:#fff;">'.$sa_display_title.'</a></h3>
                              </div>';
                        
                        if (!empty($p_download)) {
                            echo '<div class="controls">
                                    <audio controls preload="none" controlsList="nofullscreen noremoteplayback noplaybackrate foobar novolume">
                                        <source src="'.$siteurl.$p_download.'" type="audio/mpeg" />
                                    </audio>
                                  </div>';
                            echo '<div class="time">'.$p_duration.' Sec &bull; MP3</div>';
                            echo '<div class="download-button">
                                    <a href="' . $full_link . '">
                                       View & Download
                                    </a>
                                  </div>';
                        }
                    echo '</div>'; 
                }
                $stmt_sa_post->close();
            }
        } else {
             echo "<p style='color:#777; font-size:13px;'>No other tracks found for this album.</p>";
        }
        $stmt_sa->close();
    }
    ?>
    </div>
</div>

<!-- RECENT ALBUMS SECTION -->
<?php
$sql_recent_albums = "SELECT album, image FROM sitemapbollyalbums ORDER BY id DESC LIMIT 8";
$result_recent_albums = $con->query($sql_recent_albums);

if ($result_recent_albums && $result_recent_albums->num_rows > 0) {
    echo '<section class="recent-albums-wrap">';
    echo '<h3>Recent Albums</h3>';
    echo '<div class="recent-grid">';
    while($r_row = $result_recent_albums->fetch_assoc()) {
        $raw_name = $r_row['album'];
        $clean_name = ucwords(str_replace('-', ' ', $raw_name));
        $link_slug = "/category/" . urlformat($raw_name); // Reusing urlformat helper
        
        $imgSrcRecent = $r_row['image'];
        if(strpos($imgSrcRecent, 'http') === false) {
            $imgSrcRecent = $siteurlnav . '/images/category/' . $imgSrcRecent; 
        }
        
        echo '<a href="' . $link_slug . '" class="recent-item" title="' . $clean_name . '">';
        echo '<img src="' . htmlentities($imgSrcRecent) . '" alt="' . htmlentities($clean_name) . '" loading="lazy">';
        echo '<span>' . $clean_name . '</span>';
        echo '</a>';
    }
    echo '</div>';
    echo '</section>';
}
?>

<!-- RESTORED: RELATED CONTENT 2 (Recent Ringtones) -->
<div style="margin-top:20px;">
    <h2>RECENT RINGTONES</h2>
    <div class="ringtone-list">
    <?php
    // 1. Fetch Related Albums (Limited for performance)
    $sitemap_query = "SELECT URLSLIST FROM sitemapcomio WHERE language = ? ORDER BY RAND() LIMIT 10";
    $stmt_rel = $con->prepare($sitemap_query);
    $stmt_rel->bind_param("s", $urllanguage);
    $stmt_rel->execute();
    $sitemap_result = $stmt_rel->get_result();

    if ($sitemap_result) {
        while ($sitemap_row = $sitemap_result->fetch_assoc()) {
            
            $raw_url_key = $sitemap_row['URLSLIST'];
            $display_title = ucwords(str_replace("-", " ", $raw_url_key));
            $search_clean = str_replace(['ringtone', 'download', 'mp3', 'bgm', '-'], ' ', $raw_url_key);
            $search_clean = trim($search_clean);
            
            $rel_post_sql = "SELECT * FROM posts WHERE title LIKE ? LIMIT 1";
            $stmt_rel_post = $con->prepare($rel_post_sql);
            $search_param = "%" . $search_clean . "%";
            $stmt_rel_post->bind_param("s", $search_param);
            $stmt_rel_post->execute();
            $rel_post_result = $stmt_rel_post->get_result();

            // Only display if we actually found a song in the posts table
            if ($rel_post_result->num_rows > 0) {
                $p_row = $rel_post_result->fetch_assoc();
                
                $p_download = htmlentities($p_row['download link']);
                $p_title = htmlentities($p_row['title']); 
                $p_id = htmlentities($p_row["No"]);
                $p_duration = substr(htmlentities($p_row['duration']), 0, 2);
                
                // Link to the full album page
               $album_link = isset($cateurl) ? $siteurlnav . $cateurl . $raw_url_key : "/ringtone/" . $raw_url_key; 
                
                echo '<div class="ringtone">';
                    echo '<div class="details">
                            <h3><a href="'.$album_link.'" style="color:#fff;">'.$display_title.'</a></h3>
                            <p style="font-size:12px; color:#aaa; margin:0;">Featured: '.$p_title.'</p>
                          </div>';
                    
                    if (!empty($p_download)) {
                        echo '<div class="controls">
                                <audio controls preload="none" controlsList="nofullscreen noremoteplayback noplaybackrate foobar novolume">
                                    <source src="'.$siteurl.$p_download.'" type="audio/mpeg" />
                                </audio>
                              </div>';
                    }

                    echo '<div class="time">'.$p_duration.' Sec &bull; MP3 &bull; <a href="'.$album_link.'">View All</a></div>';
                    
                    if (!empty($p_download)) {
                        echo '<div class="download-button">
                                <a href="' . $siteurl.$p_download . '" onclick="return updateDownloadCount('.$p_id.', this.href)">
                                   Download Ringtone
                                </a>
                              </div>';
                    }
                          
                echo '</div>'; 
            }
        }
    }
    ?>
    </div>
</div>

<?php 
$con->close(); 
include '../footer.php'; 
?>

<!-- SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $("audio").on("play", function() {
        $("audio").not(this).each(function(index, audio) { audio.pause(); });
    });
});

function updateDownloadCount(ringtoneId, downloadUrl) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "update_download.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            window.location.href = downloadUrl;
        }
    };
    xhr.send("id=" + ringtoneId);
    return false;
}
</script>

</body>
</html>

<?php 
// CACHE SAVE
$content = ob_get_clean();
file_put_contents($cacheFile, $content);
echo $content;
?>