<?php
include '../sitedetails.php';


?>
<meta charset="UTF-8">

<!DOCTYPE html>
<style>
  body{
    color: white;
  }
  
  a {
    color: greenyellow;
}

tbody {
    font-size: 14px;
}
p {
    font-size: 14px;
}

h1 {
    font-size: 18px;
}
h3 {
    font-size: 12px;
}
.time {
    font-size: 14px;
}
</style>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
<meta property="og:site_name" content="<?php echo $sitename;?>" />
<meta name="author" content="<?php echo $siteauthor;?>" />
<link rel="icon" type="image/x-icon" href="/images/<?php echo $faviconurl;?>">
<link rel="stylesheet" type="text/css" href="../css/ringtonelist.css">
</head>

<?php

function urlformat($string) {
    // Convert to lowercase
    $string = strtolower($string);
    // Replace spaces and underscores with hyphens
    $string = str_replace([' ', '_'], '-', $string);
    // Remove special characters
    $string = preg_replace('/[^a-z0-9\-]/', '', $string);
    // Remove multiple hyphens
    $string = preg_replace('/-+/', '-', $string);
    // Trim hyphens from start and end
    $string = trim($string, '-');
    return $string;
}

function makeSlug($string) {
    $string = strtolower(trim($string));
    $string = str_replace([' ', '_'], '-', $string);
    $string = preg_replace('/[^a-z0-9\-]/', '', $string);
    $string = preg_replace('/-+/', '-', $string);
    return trim($string, '-');
}
    // FILENAME RINGLIST.PHP // RINGTONS BGM//

include '../analytics.php';
include('externalhead.php');
include('../header.php');
ob_start();
$cacheExpire = 172800; // in seconds

// Parse the requested URL
$requestedUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$cacheFile = 'cache/' . md5($requestedUrl) . '.html';

// Check if cached content exists and is not expired
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheExpire) {
    // Serve the cached content
    echo file_get_contents($cacheFile);
    // Stop executing the script further
    exit();
}
?>



<body>
<?php



#####################################################

$pageurl= $_SERVER['REQUEST_URI'];

$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'];
$final_part2 = str_replace($replaceitems,"",$first_part);
$replaceitemsfortitle = ['/ringtone/','-'];
$replaceitemsfortitle2 = ['downloads','ringbgmsto20','ringtones','download','bgm','ringtone'];

$urlcheck = trim(str_replace('/ringtone/',"",$pageurl));
$urlcheck = trim(str_replace('?source=github',"",$urlcheck));

$titlepart = str_replace($replaceitemsfortitle," ",$pageurl);
$titlepart21 = str_replace($replaceitemsfortitle2," ",$titlepart);

$titlepart2 = ucwords($titlepart21);

$relatedsearchkey2 = $final_part2;
//echo $relatedsearchkey2;
include('../databaseconnect.php');

mysqli_set_charset($con, "utf8mb4");

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

// Execute query
$stmt->execute();
$result = $stmt->get_result();

// Check if URL exists in database
if ($result->num_rows > 0) {
    // URL found, do something
        $row = $result->fetch_assoc();

        $urldescription = $row["desc1"];
        $urlalbum = $row["album"];
        $urllanguage = $row["language"];
        $urlstars = $row["stars"];
                $urlyear = $row["year"];

        $urlindustry = $row["industry"];
        $urlmusicdirectors = $row["musicdirectors"];
        $urltracklist = $row["tracklist"];
        $urlmusicstyle = $row["musicstyle"];

    //echo $urldescription;
    //echo $urlalbum;
    //echo $urllanguage;
    //echo $urlstars;
    //echo $urlindustry;
    //echo $urlmusicdirectors;
    
    // $urltracklist,
    // $urlmusicstyle

} else {
  echo " $urlcheck NOT INn database.";
  header("HTTP/1.0 404 Not Found");
  echo "<html><head><meta name='robots' content='noindex, nofollow'><title>Page Not Found</title></head><body>";
  echo "THIS PAGE IS NOT FOUND OR DELETED RECENTLY.<br>";
  echo "Visit the HOME PAGE <a href='/'>here</a>.<br>";
  echo "</body></html>";
  die();
  
}


include('../searchbar.php');
echo "<title>$titlepart2 - $urlalbum Free $urllanguage Ringtone Download </title>";
echo "<meta name='description' content='Download $titlepart2 - $urlalbum  $urllanguage ringtone for free! High-quality MP3 format. Category: $urlstars $urlalbum movie $titlepart2 song ringtone download,  Tags: $urlalbum, $urlalbum, $titlepart2. No registration required - instant download! $urlalbum ringtones Perfect for Android & iPhone. No registration required - instant download!' />";

echo "<meta property='og:locale' content='en_US' />";
echo "<meta property='og:type' content='article' />";
echo "<link rel='canonical' href='$siteurlnav$pageurl'/>";


////////////////////////////

?>

<style>
/* CSS for the Breadcrumb Visuals */
.breadcrumb-container {
    padding: 10px 0 15px 0;
    font-size: 13px; /* Slightly smaller for mobile optimization */
    color: #ccc;
}
.breadcrumb-list {
    list-style: none;
    padding: 0;
    margin: 0;
}
.breadcrumb-list li {
    display: inline;
}
.breadcrumb-list li+li:before {
    padding: 0 8px;
    color: #888;
    content: "/"; 
}
.breadcrumb-list a {
    color: greenyellow; /* Your site color */
    text-decoration: none;
    text-transform: capitalize; /* Looks cleaner */
}
.breadcrumb-list a:hover {
    text-decoration: underline;
}
.breadcrumb-list li:last-child {
    color: white; 
    font-weight: bold;
}
</style>

<?php
// SEO PREPARATION
// 1. Create a slug for the language URL (e.g., "hindi" or "bollywood")
$lang_slug = urlformat($urllanguage);

// 2. Define the Link. Assuming your category structure is like /category/hindi
// Adjust "$urlpatterncat" if your category URLs are different.
$cat_base_url = isset($urlpatterncat) ? $urlpatterncat : '/category/'; 

// 3. SEO Anchor Text: "Hindi" -> "Hindi Ringtones"
// Adding the word "Ringtones" to the link text helps rank the category page.
$lang_anchor_text = $urllanguage . " Ringtones";
?>

<!-- VISUAL BREADCRUMB -->
<nav class="breadcrumb-container" aria-label="breadcrumb">
    <ol class="breadcrumb-list">
        <li><a href="/">Home</a></li>
        <li><a href="<?php echo $cat_base_url . $lang_slug; ?>"><?php echo $lang_anchor_text; ?></a></li>
        <li><?php echo $urlalbum; ?></li>
    </ol>
</nav>

<!-- GOOGLE SCHEMA.ORG JSON-LD (The "Hidden" Code for Search Engines) -->
<!-- This is cleaner than microdata for 2025 standards -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [{
    "@type": "ListItem",
    "position": 1,
    "name": "Home",
    "item": "<?php echo $siteurlnav; ?>"
  },{
    "@type": "ListItem",
    "position": 2,
    "name": "<?php echo $lang_anchor_text; ?>",
    "item": "<?php echo $siteurlnav . trim($cat_base_url, '/') . '/' . $lang_slug; ?>"
  },{
    "@type": "ListItem",
    "position": 3,
    "name": "<?php echo $urlalbum; ?>",
    "item": "<?php echo $siteurlnav . ltrim($pageurl, '/'); ?>"
  }]
}
</script>


<?php
echo "<h1> $titlepart2 - $urlalbum </h1>";

echo "<p> $urlstars $urlalbum movie $titlepart2 song ringtone download, $urlalbum  ringtone, $titlepart2 bgm , $urlyear ringtone, $urlmusicdirectors ringtone

</p>";

$urlalbum1 = urlformat($urlalbum);
$urllanguage1 = urlformat($urllanguage);
$urlyear1 = urlformat($urlyear);
$urlmusicdirectors1=  urlformat($urlmusicdirectors);

echo '<table border="1" cellpadding="8" cellspacing="0" style="border-collapse: collapse; width:100%;">';

echo '<tr>
        <th>Album / Movie</th>
        <td><a href="'.$urlpatterncat.$urlalbum1.'">'.$urlalbum.'</a></td>
      </tr>';

echo '<tr>
        <th>Language</th>
        <td><a href="'.$urlpatterncat.$urllanguage1.'">'.$urllanguage.'</a></td>
      </tr>';

echo '<tr>
        <th>Year</th>
        <td><a href="'.$urlpatterncat.$urlyear1.'">'.$urlyear.'</a></td>
      </tr>';

echo '<tr>
        <th>Music By & Lyrics By</th>
        <td><a href="'.$urlpatterncat.$urlmusicdirectors1.'">'.$urlmusicdirectors.'</a></td>
      </tr>';

echo '<tr>
        <th>Starring</th>
        <td>';

$items = explode(',', $urlstars);
foreach ($items as $item) {
    $slug = makeSlug($item);
    echo '<a href="'.$urlpatterncat.$slug.'">'.trim($item).'</a>, ';
}

echo '</td>
      </tr>';

echo '<tr>
        <th>Description</th>
        <td>
            <details>
                <summary>Song Ringtone Description &#8595;</summary>
                <div>'.$urldescription.'</div>
            </details>
        </td>
      </tr>';

echo '</table>';






/* $sql = "SELECT * FROM posts WHERE title LIKE '%$relatedsearchkey2%' OR relate LIKE '%$relatedsearchkey2%' ORDER BY title LIMIT 100";

$result = $con->query($sql);
#print_r($result) ;
 */

 $relatedsearchkey2 = trim($relatedsearchkey2);
 //echo '<br>';

 //echo $relatedsearchkey2;

$keywords = array_filter(explode(' ', $relatedsearchkey2));

if (count($keywords) > 0) {
    // Prepare SQL statement with placeholders for exact word match
    $likeClauses = array_map(function($keyword) {
        // Ensure spaces or boundaries around the keyword to avoid partial matches
        return "CONCAT(' ', title, ' ') LIKE ?";
    }, $keywords);

    $sql = "SELECT * FROM posts WHERE " . implode(' AND ', $likeClauses) . " LIMIT 6";
    $stmt = $con->prepare($sql);

    // Prepare search terms with wildcards, ensuring spaces around the words
    $searchTerms = array_map(function($keyword) {
        return "% " . $keyword . " %";
    }, $keywords);

    // Create a string with 's' repeated for each keyword
    $types = str_repeat('s', count($searchTerms));

    // Bind parameters and execute
    $stmt->bind_param($types, ...$searchTerms);
    $stmt->execute();
    $result = $stmt->get_result();

    // Output the number of results
   echo "<p>".$result->num_rows . " Ringtones Found. </p>";

 

 
$printedDescription = false;
$printedDetails = false;


if ($result->num_rows > 0) {
  // output data of each row
  echo '<div class ="ringtone-list">';

  while($row = $result->fetch_assoc() ){
    $download = htmlentities($row['download link']);
    $pageurl1 = htmlentities($row['pageurl']);
    $relatedkeywords = $row["relate"];
    $number = htmlentities($row["No"]);
    $comments = $row["comments"];
    $videoid = $row["videoid"];

    $title = htmlentities($row['title']);
    $replaceitems =['nothing','br' ,'<>'];
    $duration = htmlentities($row["duration"]);
    $download_count = htmlentities($row["download_count"]);

    $album = htmlentities($row['album']);
    $stars = htmlentities($row['stars']);

    $albumcaps = ucwords($album);

    $language = ucwords(htmlentities($row['language']));
    $industry = ucwords(htmlentities($row['industry']));
    $spellingmistakes = htmlentities($row['spellingmistakes']);
    $description = ucwords(htmlentities($row['desc1']));

    $image   = htmlentities($row['image'] ?? '');

    
      $relatedkeywordsreplace = str_replace($replaceitems,'',$relatedkeywords);

      $relatedkeywordspurified =explode("&BGM994",$relatedkeywordsreplace);
      $imagelink = false;
      if (!$imagelink) {

        if (!empty($image)) {

          echo "<p>Album Poster:<img src='$image' alt='$title' width='300' height='300'></p>";
        }
        $imagelink = true;
        }

    
    $videohtml = "<audio controls preload='none' controlsList='nofullscreen  noremoteplayback noplaybackrate foobar novolume'><source src='$siteurl$download' type='audio/mpeg' /></audio>";
    
       # $videohtml = "<audio controls preload='none' controlsList='nofullscreen  noremoteplayback noplaybackrate foobar novolume'><source src='$siteurl$download' type='audio/mpeg' /></audio>";

    echo '<div class ="ringtone">';
            echo "<div class ='details'> <h3>$title</h3></div>";
    echo   "<div class ='controls'> $videohtml </div>";
            echo  "<div class ='time'> 199 Plays , $download_count Downloads.</div>";
            
$durationtrimmedString = substr($duration, 0, 2);

    echo  "<div class ='time'>$durationtrimmedString Seconds. Format : MP3.</div>";



 

   echo "<div class ='download-button'><a href=" . $siteurl.$download . "  >Download</a></div>";
   
   //echo "<div class ='download-button'>
       // <a href='whatsapp://channel/0029VbB5I3N545v1QIU6M71z' onclick='return updateDownloadCount($number, this.href)'>Download</a>
     // </div>";

//$siteurl$download
    echo '</div>';



}




echo '</div>';

} }
else {
  header('HTTP/1.1 404 Not Found'); //This may be put inside err.php instead
  $_GET['e'] = 404; //Set the variable for the error code (you cannot have a
                    // querystring in an include directive).
  include '../404.php';
  exit; //Do not do any more work in this script.
}


$con->close();
//include '../list/all/catesongs.php';

//include '../list/all/cate.php';


#################################3
// Author data (you can later fetch this from DB)
$author = "Kajol";
$author_image = "/images/authors/kajol.jpg"; // Path to author's image
$author_bio = "Kajol regularly uploads crisp, trendy, and premium ringtones, ensuring users always have access to the best audio picks.";


// Generate slug (for profile URL)
$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $author)));
$profile_url = "/author/" . $slug;

// Now echo the HTML
echo '
<div class="author-box" itemscope itemtype="https://schema.org/Person">
    <meta itemprop="jobTitle" content="Author" />
    <meta itemprop="worksFor" content="WallpaperHub" />
    <a href="' . $profile_url . '" itemprop="url" class="author-link">
        <img src="' . $author_image . '" alt="' . htmlspecialchars($author) . ' photo" itemprop="image" loading="lazy" width="80" height="80" style="border-radius:50%;object-fit:cover;">
    </a>
    <div class="author-details">
        <p>Uploaded by:</p>
        <h3 itemprop="name">
            <a href="' . $profile_url . '" style="text-decoration:none;color:#222;">
                ' . htmlspecialchars($author) . '
            </a>
        </h3>
        <p itemprop="description">' . htmlspecialchars($author_bio) . '</p>
    </div>
</div>

<style>
.author-box {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 15px;
    border-radius: 12px;
    margin-top: 20px;
}
.author-details h3 {
    margin: 0;
    font-size: 0.7rem;
}
.author-details p {
    margin: 3px 0;
    font-size: 0.7rem;

}
</style>
';






////////////////

////////////////////////////////////////////////////
?>
<?php
echo '<h2>Related Ringtones</h2>';

include('../databaseconnect.php'); // This file should establish your $con database connection

// Check if the connection is established
if (!$con) {
    die("Database connection failed: " . mysqli_connect_error());
}

// Assuming $siteurl is defined elsewhere, e.g., in a config file or above this snippet.
// **IMPORTANT: Replace with your actual site URL**
$siteurl = "http://gummu.net/"; 
echo '<div class ="ringtone-list">';

// 1. Load last 10 Rows from sitemapbolly by last modified date
// Note: The table name in the query was changed from 'sitemap' to 'sitemapbolly' to match your initial table definition.
$sitemap_query = "SELECT ID, URLSLIST FROM sitemapbolly ORDER BY modified_date DESC LIMIT 10";
$sitemap_result = mysqli_query($con, $sitemap_query);

if ($sitemap_result && mysqli_num_rows($sitemap_result) > 0) {
    while ($sitemap_row = mysqli_fetch_assoc($sitemap_result)) {
        $sitemap_id = $sitemap_row['ID'];
        $url_list_keyword = $sitemap_row['URLSLIST']; // This is the value to be used as title

        // 2. Take URLSLIST keyword and search in Table: posts
        $posts_query = "SELECT No, title, `download link` as download_link, download_count FROM posts WHERE pageurl LIKE '%" . mysqli_real_escape_string($con, $url_list_keyword) . "%' LIMIT 1";
        $posts_result = mysqli_query($con, $posts_query);

        if ($posts_result && mysqli_num_rows($posts_result) > 0) {
            $post_row = mysqli_fetch_assoc($posts_result);

            $post_id = $post_row['No'];
            $download = htmlspecialchars($post_row['download_link']);
            $download_count = (int)$post_row['download_count'];

            // Define the target URL for the entire ringtone item
            $target_page_url = $cateurl . urlencode($url_list_keyword);

            // The entire .ringtone div will now be a clickable element.
            // We're adding an inline JavaScript `onclick` to navigate.
            // Ensure proper escaping for the URL in JavaScript.
            echo '<div class ="ringtone" onclick="window.location=\'' . htmlspecialchars($target_page_url, ENT_QUOTES, 'UTF-8') . '\';">'; // Open the individual ringtone item container

            $videohtml = "<audio controls preload='none' controlsList='nofullscreen  noremoteplayback noplaybackrate foobar novolume'><source src='" . $siteurl . $download . "' type='audio/mpeg' /></audio>";
            
            $url_list_keyword1 = str_replace("-", " ", $url_list_keyword);


            // Display URLSLIST as the title, as requested
            echo "<div class ='details'> <h3 style='font-size: 14px;'>" . htmlspecialchars($url_list_keyword1) . "</h3></div>";
            echo "<div class ='controls'> $videohtml</div>";
            // The '123 Plays' is static in the example, so we output it as is.
            echo "<div class ='time'> 199 Plays , $download_count Downloads.</div>";

            // Add the download button.
            // When this button is clicked, we want to prevent the outer div's click event
            // from also firing, hence `event.stopPropagation()`.
            // The download button's href also points to the same target page.
            echo "<div class ='download-button'>";
            echo "<a href='" . htmlspecialchars($target_page_url, ENT_QUOTES, 'UTF-8') . "' onclick='event.stopPropagation();'>Download</a>";
            echo "</div>";

            echo '</div>'; // Close the individual ringtone item container
        }
        mysqli_free_result($posts_result); // Free result set for posts query
    }
} else {
    echo "No records found in sitemapbolly or query failed.";
}
echo '</div>';

mysqli_free_result($sitemap_result); // Free result set for sitemapbolly query
mysqli_close($con); // Close the database connection


include '../footer.php';

?>



</body>
</html>




<script>
        $(document).ready(function() {
            $("audio").on("play", function() {
                $("audio").not(this).each(function(index, audio) {
                    audio.pause();
                });
            });
        });
    </script>


<script>
function updateDownloadCount(ringtoneId, downloadUrl) {
    // Send AJAX request to update download count
    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 && xhr.status === 200) {
            console.log("Download count updated successfully.");
        }
    };

    xhr.send("id=" + ringtoneId);

    // Allow normal download action
    window.location.href = downloadUrl;
    return false; // Prevent default anchor click behavior
}
</script>
<script>
    // This function ensures all other audio stops when one starts playing
    document.addEventListener('play', function(e){
        var audios = document.getElementsByTagName('audio');
        for(var i = 0, len = audios.length; i < len;i++){
            if(audios[i] != e.target){
                audios[i].pause();
            }
        }
    }, true);

    // This function updates the count and then starts the download
    function updateDownloadCount(ringtoneId, downloadUrl) {
        // Send AJAX request to update download count
        var xhr = new XMLHttpRequest();
        // The path is relative to the current page (ringtoneslist2.php)
        xhr.open("POST", "update_download.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        
        // This function will be called when the server responds
        xhr.onreadystatechange = function () {
            // Check if the request is complete and was successful
            if (xhr.readyState === 4) {
                if(xhr.status === 200) {
                    console.log("Download count updated successfully.");
                } else {
                    console.error("Failed to update download count. Status: " + xhr.status);
                }
                // *** CRUCIAL CHANGE ***
                // Start the download ONLY after the server has responded,
                // regardless of whether the update was successful or not.
                // This ensures the user always gets their file.
                window.location.href = downloadUrl;
            }
        };

        // Send the ringtone ID to the server
        xhr.send("id=" + ringtoneId);

        // Prevent the link's default behavior because we are handling the navigation in JavaScript
        return false; 
    }
</script>


<style>
    
    /* Breadcrumb Styles */
.breadcrumb {
    padding: 10px 0;
    margin-bottom: 15px;
    list-style: none;
    font-size: 14px;
}
.breadcrumb li {
    display: inline;
}
.breadcrumb li+li:before {
    padding: 0 8px;
    color: white;
    content: "/\00a0"; /* Adds a slash separator */
}
.breadcrumb a {
    color: greenyellow;
    text-decoration: none;
}
.breadcrumb a:hover {
    text-decoration: underline;
}
.breadcrumb li:last-child {
    color: white; /* Current page text color */
}
</style>

<?php 
    // FILENAME RINGLIST.PHP // RINGTONS BGM//
    $content = ob_get_clean();

    // Cache the generated content
    file_put_contents($cacheFile, $content);
    
    echo $content;
?>

