<?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) {
    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 sitemapbolly 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"];
    $urlalbum = $row["album"];
    $urllanguage = $row["language"];
    $urlstars = $row["stars"];
    $urlyear = $row["year"];
    $urlindustry = $row["industry"];
    $urlmusicdirectors = $row["musicdirectors"];
    // 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 : '/category/'; 

// --- 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 (Replaces Table) */
  .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; }
</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>
</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 $urldescription; ?>
    </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 $urlalbum; ?> Ringtones</h3>
    <p><strong>Is the download free?</strong><br>Yes, all ringtones on this page are 100% free.</p>
    <p><strong>What is the audio quality?</strong><br>We provide high-quality 320kbps MP3 files.</p>
</div>

<!-- VIEW album ringtones  -->


<!-- AUTHOR BOX -->
<?php
$author_name = "Kajol";
$author_image = "/images/authors/kajol.jpg";
$author_slug = "/author/kajol";
?>
<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>

<!-- RELATED CONTENT -->
<div style="margin-top:40px;">
    <h2>Related Ringtones & Albums</h2>
    <div class="ringtone-list">
    <?php
    $sitemap_query = "SELECT ID, URLSLIST FROM sitemapbolly WHERE language = ? ORDER BY modified_date DESC LIMIT 100";
    $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()) {
            $r_keyword = $sitemap_row['URLSLIST'];
            // Simple display of related links
            $r_title = ucwords(str_replace("-", " ", $r_keyword));
            $r_link = $cateurl . urlencode($r_keyword);
            echo '<div class="ringtone" style="padding:10px; cursor:pointer;" onclick="window.location=\''.$r_link.'\'">';
            echo '<div class="details"><h3 style="font-size:14px; margin:0;">'.$r_title.'</h3></div>';
            echo '<div class="time2" style="margin-top:5px;">View Ringtones &rarr;</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;
?>