<?php
// 1. START BUFFERING & CACHING
ob_start();
$cacheExpire = 172800; // 48 hours

// Normalize URL for caching
$requestedUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$cacheFile = 'cache/' . md5($requestedUrl) . '.html';

// Serve Cache if valid (and not a POST request)
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheExpire && empty($_POST)) {
    echo file_get_contents($cacheFile);
    exit();
}

// 2. INCLUDE & SETUP
include '../sitedetails.php'; 
include '../databaseconnect.php'; 


// 3. PARSE URL FOR SEO
$request_uri = $_SERVER['REQUEST_URI'];
$category_slug = str_replace('/ringtones/', '', $request_uri);
$category_slug = explode('?', $category_slug)[0]; 
$category_slug = rtrim($category_slug, '/');

// Human Readable Name (e.g. "tiger-3" becomes "Tiger 3")
$category_name = ucwords(str_replace('-', ' ', $category_slug));

// --- NEW LOGIC: CHECK SITEMAPBOLLYALBUMS ---
$custom_seo_title = ""; // Variable to store the custom title if found

// We check if the formatted category name exists in the 'album' column
// If your database stores slugs (e.g. tiger-3) in the album column, change $category_name to $category_slug below
$sql_check_album = "SELECT seotitle FROM sitemapbollyalbums WHERE album = ? LIMIT 1";

if ($stmt_album = $con->prepare($sql_check_album)) {
    $stmt_album->bind_param("s", $category_name);
    $stmt_album->execute();
    $stmt_album->bind_result($fetched_seotitle);
    
    if ($stmt_album->fetch()) {
        // If match found, store the seotitle
        if (!empty($fetched_seotitle)) {
            $custom_seo_title = $fetched_seotitle;
        }
    }
    $stmt_album->close();
}
// -------------------------------------------

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

function generateInternalLinks($commaString, $basePath = '/ringtones/') {
    if (empty($commaString)) return "";
    $items = explode(',', $commaString);
    $links = [];
    foreach ($items as $item) {
        $cleanItem = trim($item);
        if (!empty($cleanItem)) {
            $slug = urlformat_seo($cleanItem);
            // Stop propagation on link click so it doesn't trigger the card click
            $links[] = "<a href='{$basePath}{$slug}' title='Ringtones of $cleanItem' onclick='event.stopPropagation();' class='meta-link'>$cleanItem</a> ";
        }
    }
    return implode(', ', $links);
}

function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0) {
        $refs = array();
        foreach($arr as $key => $value) $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}

// SEO META DATA
if (!empty($custom_seo_title)) {
    // If found in sitemapbollyalbums, use the seotitle
    $pageTitle = $custom_seo_title;
} else {
    // Fallback to default logic
    $pageTitle = "Latest". $category_name . " Ringtones Download (Mp3 & M4R & Songs ) ";
}

$pageDesc = "Explore our exclusive collection of free $category_name ringtones, including Latest $category_name ringtone, $category_name songs, popular tunes, and more. Download high-quality MP3 and M4R ringtones for your iPhone or Android device and personalize your phone with the latest Caller Tunes.";
$pageKeywords = $category_name . " ringtone, " . $category_name . " bgm download, " . $category_name . " mp3, m4r, andriod, iphone, all mobile free ringtones";


$canonicalUrl = $siteurlnav . "/ringtones/" . $category_slug;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <!-- PRIMARY SEO TAGS -->
    <title><?php echo $pageTitle; ?></title>
    <meta name="description" content="<?php echo $pageDesc; ?>">
    <meta name="keywords" content="<?php echo $pageKeywords; ?>">
    <link rel="canonical" href="<?php echo $canonicalUrl; ?>">

    <!-- OPEN GRAPH -->
    <meta property="og:type" content="music.playlist">
    <meta property="og:title" content="<?php echo $pageTitle; ?>">
    <meta property="og:description" content="<?php echo $pageDesc; ?>">
    <meta property="og:url" content="<?php echo $canonicalUrl; ?>">
    <meta property="og:site_name" content="<?php echo $sitename; ?>">
    <link rel="icon" type="image/x-icon" href="/images/<?php echo isset($faviconurl) ? $faviconurl : 'pagalworld.png';?>">
    
    <!-- STYLES -->
    <link rel="stylesheet" type="text/css" href="../css/ringtonelist.css">
    <link rel="stylesheet" type="text/css" href="../css/indexpage2.css">
    
    <style>
        body { color: white; background-color: #000; font-family: 'Segoe UI', sans-serif; }
        a { color: greenyellow; text-decoration: none; }
        a:hover {
  color: red; /* Color on hover */
  text-decoration: underline; /* Adds underline on hover */
}
        h1 { font-size: 1.8rem; margin: 15px 0 10px; color: #fff; text-transform: capitalize; }
        .seo-intro { color: #ccc; font-size: 0.95rem; margin-bottom: 20px; line-height: 1.5; }
        .details h3 { margin: 0; padding: 0; }
        
        .ringtone { 
            border: 1px solid #333; margin-bottom: 15px; padding: 10px; 
            border-radius: 8px; background: #111; cursor: pointer;
        }
        .ringtone:hover { background: #1a1a1a; border-color: greenyellow; }
        
        /* NEW STYLES FOR META DATA PER SONG */
        .song-meta-data {
            font-size: 18px;
            color: #aaa;
            margin-top: 6px;
            line-height: 1.4;
            border-top: 1px dashed #333;
            padding-top: 6px;
        }
        .song-meta-data span { color: #fff; font-weight: 600; }
        .song-meta-data a { color: #00d4ff; text-decoration: underline; text-decoration-color: #555; }
        .song-meta-data a:hover { color: #fff; }

        .download-button a { 
            display: inline-block; margin-top: 5px; color: #00d4ff; 
            font-weight: bold; padding: 5px 0;
        }
        
        /* BREADCRUMBS (SEO Friendly) */
        .breadcrumb-nav { font-size: 18px; margin-top: 15px; color: #888; }
        .breadcrumb-nav a { color: #bbb; }
        .breadcrumb-nav span { margin: 0 5px; color: #555; }
        .breadcrumb-current { color: #00d4ff; }

        .time { color: #aaa; font-size: 18px; padding: 8px; }
        
        
        .author-box {
    font-size: 18px;
}
    </style>
    
    <?php 
    if(file_exists('../externalhead.php')) {
        include('../externalhead.php');
    }
    ?>
</head>

<body>

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

<div class="content-wrapper" style="margin: 0 auto; padding: 0 15px;">

    <?php
    // --- DATABASE SEARCH LOGIC ---
    $sitemap_conditions = [];
    $sitemap_search_param = '%' . $category_name . '%';

    $sitemap_search_columns = [
        'URLSLIST', 'tracklist', 'musicstyle', 'lyrics', 'year',
        'spellingmistakes', 'album', 'industry', 'language', 'stars', 'musicdirectors'
    ];

    foreach ($sitemap_search_columns as $column) {
        $sitemap_conditions[] = "$column LIKE ?";
    }

    $sitemap_where_clause = implode(' OR ', $sitemap_conditions);
    
    // FETCH DATA
    $sql_sitemap = "SELECT URLSLIST, desc1, year, stars, musicdirectors, album, language FROM sitemapbolly WHERE $sitemap_where_clause ORDER BY ID DESC";

    if ($stmt_sitemap = $con->prepare($sql_sitemap)) {
        
        $sitemap_types = str_repeat('s', count($sitemap_search_columns));
        $sitemap_params = array_merge([$sitemap_types], array_fill(0, count($sitemap_search_columns), $sitemap_search_param));

        call_user_func_array([$stmt_sitemap, 'bind_param'], refValues($sitemap_params));
        $stmt_sitemap->execute();
        $result_sitemap = $stmt_sitemap->get_result();

        // Store in array
        $sitemapData = [];
        while($row = $result_sitemap->fetch_assoc()) {
            $sitemapData[] = $row;
        }

        // --- BREADCRUMBS LOGIC ---
        $meta_lang = "Ringtones"; 
        if(count($sitemapData) > 0 && !empty($sitemapData[0]['language'])) {
            $meta_lang = $sitemapData[0]['language'];
        }
        $lang_url = "/ringtones/" . urlformat_seo($meta_lang);
        

        // Display Breadcrumbs
        echo '<div class="breadcrumb-nav">';
        echo '<a href="/">Home</a> <span>›</span> ';
        echo '<a href="' . $lang_url . '">' . $meta_lang . '</a> <span>›</span> ';
        echo '<span class="breadcrumb-current">' . htmlspecialchars($category_name) . '</span>';
        echo '</div>';

        // --- H1 DISPLAY LOGIC ---
        if (!empty($custom_seo_title)) {
            // If match found in sitemapbollyalbums, use seotitle as H1
            echo "<h1>". htmlspecialchars($custom_seo_title) . "</h1>";
        } else {
            // Default H1
            echo "<h1>". ucfirst(htmlspecialchars($category_name)) . " Ringtones</h1>";
        }

        // SEO Text
        echo '<div class="seo-intro">';
     echo '<p>Download the latest and most popular <strong>' . htmlspecialchars($category_name) . '</strong> ringtones in ' . $meta_lang . '. 
Enjoy high-quality MP3 BGMs, dialogue tones, theme music, and mobile ringtones optimized for Android and iOS devices. Fast, free, and easy downloads for every phone.</p>';
echo '</div>';


        $schemaList = []; 
        
        //echo "<h2> Songs,  ". ucfirst($category_name)." Ringtones List</h2>";

        if (count($sitemapData) > 0) {
            
            // Loop through data
            echo '<div class="ringtone-list">';

            foreach ($sitemapData as $row_sitemap) {
                
                $url_list_value = htmlspecialchars($row_sitemap['URLSLIST']);
                $clean_title = ucwords(str_replace('-', ' ', $row_sitemap['URLSLIST']));
                $anchor_href = "/ringtone/" . $url_list_value;
                
                // Meta info
                $raw_album = $row_sitemap['album'];
                $raw_year = isset($row_sitemap['year']) ? $row_sitemap['year'] : '';
                $raw_stars = $row_sitemap['stars'];
                $raw_directors = $row_sitemap['musicdirectors'];

                // --- SEARCH BY TITLE (Removed 'URL' column that caused crash) ---
                $foundPost = false;
                $audioPlayerHtml = "<p style='font-size:18px; color:#666;'>Audio preview unavailable</p>";
                $playsText = "";
                $direct_download_url = "";
                $durationISO = "PT0M30S";

                $search_title_term = '%' . str_replace('-', ' ', $url_list_value) . '%';
                
                $sql_posts = "SELECT title, `download link` AS download_link, download_count, duration FROM posts WHERE title LIKE ? LIMIT 1";

                if ($stmt_posts = $con->prepare($sql_posts)) {
                    $stmt_posts->bind_param('s', $search_title_term);
                    $stmt_posts->execute();
                    $result_posts = $stmt_posts->get_result();

                    if ($row_post = $result_posts->fetch_assoc()) {
                        $foundPost = true;
                        $direct_download_url = $siteurl . htmlspecialchars($row_post['download_link']);
                        $d_count = (int)$row_post['download_count'];
                        $duration = (int)$row_post['duration'];
                        if($duration > 0) $durationISO = "PT" . $duration . "S";

                        $audioPlayerHtml = "<audio controls preload='none' controlsList='nodownload'><source src='$direct_download_url' type='audio/mpeg' /></audio>";
                        $playsText = "<div class='time'> 120+ Plays • $d_count Downloads • $duration Seconds </div>";
                    }
                    $stmt_posts->close();
                }

                // Schema Data
                $schemaList[] = [
                    "@type" => "AudioObject",
                    "name" => $clean_title,
                    "description" => "Download " . $clean_title . " from " . $raw_album,
                    "contentUrl" => $foundPost ? $direct_download_url : $siteurlnav . $anchor_href,
                    "duration" => $durationISO,
                    "inAlbum" => ["@type" => "MusicAlbum", "name" => $raw_album]
                ];

                // RENDER CARD
                echo '<div class="ringtone" onclick="window.location=\'' . $anchor_href . '\';">';
                    echo "<div class='details'>";
                    
                        // 1. Song Title
                        echo "<h3 style='font-size: 18px; margin-bottom:5px;'>";
                        echo "<a href='" . $anchor_href . "' title='" . $clean_title . "'>$clean_title Song Ringtone </a>";
                        echo " </h3>";
////////////////////////////


$author_name  = "Kajol";
$author_image = "/images/authors/kajol.jpg";
$author_slug  = "/author/kajol";

echo '<div class="author-box" itemscope itemtype="https://schema.org/Person">';

echo '<p itemprop="name"> Uploaded by: <a href="' . $author_slug . '" style="color:#59dde0;">' . $author_name . '</a></p>';

echo '</div>';

















////////////
                        // 2. Song Meta Data (Per Song)
                        echo "<div class='song-meta-data'>";
                            if (!empty($raw_album)) {
                                echo "<div><span>Album:</span> " . generateInternalLinks($raw_album) . "</div>  "
;
                            }
                            if (!empty($raw_year)) {
                                echo "<div><span>Year:</span> " . generateInternalLinks($raw_year) . "</div>";
                            }
                            if (!empty($raw_stars)) {
                                echo "<div><span>Cast:</span> " . generateInternalLinks($raw_stars) . "</div>";
                            }
                            if (!empty($raw_directors)) {
                                echo "<div><span>Music By:</span> " . generateInternalLinks($raw_directors) . "</div>";
                            }
                        echo "</div>";

                    echo "</div>"; // End Details

                    echo "<div class='controls'>" . $audioPlayerHtml . "</div>";
                    
                    if($foundPost) {
                        echo "<div class='download-button'>";
                        echo "<a href='" . $anchor_href . "' onclick='event.stopPropagation();' style='color:#000; font-size:18px;'>More Ringtones Like $clean_title </a>";
                        echo "</div>";
                        echo $playsText;
                        echo "<div class='download-button'>";
                        echo "<a href='" . $anchor_href . "' onclick='event.stopPropagation();' title='Save this ringtone'>⬇ Download </a>";
                        echo "</div>";
                    } else {
                        echo "<div class='download-button'></div>";
                    }
                echo '</div>'; 
            }
            echo '</div>'; // End List
            
            // --- SCHEMA JSON-LD ---
            $schemaBC = [
                "@context" => "https://schema.org",
                "@type" => "BreadcrumbList",
                "itemListElement" => [
                    ["@type" => "ListItem", "position" => 1, "name" => "Home", "item" => $siteurlnav],
                    ["@type" => "ListItem", "position" => 2, "name" => $meta_lang, "item" => $siteurlnav . $lang_url],
                    ["@type" => "ListItem", "position" => 3, "name" => $category_name, "item" => $canonicalUrl]
                ]
            ];

            $schemaListObj = [
                "@context" => "https://schema.org",
                "@type" => "ItemList",
                "itemListElement" => []
            ];
            $pos = 1;
            foreach($schemaList as $item) {
                $schemaListObj['itemListElement'][] = [
                    "@type" => "ListItem",
                    "position" => $pos,
                    "item" => $item
                ];
                $pos++;
            }
            
            echo '<script type="application/ld+json">' . json_encode($schemaBC) . '</script>';
            echo '<script type="application/ld+json">' . json_encode($schemaListObj) . '</script>';

        } else {
            echo "<p style='padding:20px; text-align:center;'>No ringtones found for <strong>" . htmlspecialchars($category_name) . "</strong>.</p>";
        }
        $stmt_sitemap->close();
    }
    
    $con->close();
    include('../footer.php');
    ?>

</div>

<!-- JAVASCRIPT FOR AUDIO HANDLING -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    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);
</script>

<?php 
// 4. SAVE TO CACHE AND OUTPUT
$content = ob_get_clean();
file_put_contents($cacheFile, $content);
echo $content;
?>
</body>
</html>