<?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'; 

// --- 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);
            $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;
}

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

// -------------------------------------------------------------------------
// 4. FETCH DATA BEFORE HEADER (SEO OPTIMIZATION: COUNT & CONTENT ANALYSIS)
// -------------------------------------------------------------------------

// A. Fetch Ringtones List First to get Count and Details
$sitemapData = [];
$meta_lang = "Ringtones";
$first_cast = "";
$first_year = "";

$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 query
$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();
    while($row = $result_sitemap->fetch_assoc()) {
        $sitemapData[] = $row;
    }
    $stmt_sitemap->close();
}

// Extract details for SEO generation
$total_ringtones = count($sitemapData);
if ($total_ringtones > 0) {
    if (!empty($sitemapData[0]['language'])) $meta_lang = $sitemapData[0]['language'];
    if (!empty($sitemapData[0]['stars'])) $first_cast = explode(',', $sitemapData[0]['stars'])[0];
    if (!empty($sitemapData[0]['year'])) $first_year = $sitemapData[0]['year'];
}

// B. Fetch Custom SEO Data (Album / Cast / Director)
$custom_seo_found = false;
$custom_seo_title = "";
$custom_seo_desc = ""; 
$custom_faq_content = ""; 

// 1. Check sitemapbollyalbums
if (!$custom_seo_found) {
    $sql_check_album = "SELECT seotitle, description_for_album, faq FROM sitemapbollyalbums WHERE album = ? LIMIT 1";
    if ($stmt = $con->prepare($sql_check_album)) {
        $stmt->bind_param("s", $category_slug);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            $stmt->bind_result($db_title, $db_desc, $db_faq);
            $stmt->fetch();
            if (!empty($db_title)) { $custom_seo_title = $db_title; $custom_seo_found = true; }
            if (!empty($db_desc)) { $custom_seo_desc = $db_desc; }
            if (!empty($db_faq)) { $custom_faq_content = $db_faq; }
        }
        $stmt->close();
    }
}

// 2. Check b_ringtones_cast
if (!$custom_seo_found) {
    $sql_check_cast = "SELECT castseotitle, faq FROM b_ringtones_cast WHERE cast_name = ? LIMIT 1";
    if ($stmt = $con->prepare($sql_check_cast)) {
        $stmt->bind_param("s", $category_slug);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            $stmt->bind_result($db_title, $db_faq);
            $stmt->fetch();
            if (!empty($db_title)) { $custom_seo_title = $db_title; $custom_seo_found = true; }
            if (!empty($db_faq)) { $custom_faq_content = $db_faq; }
        }
        $stmt->close();
    }
}

// 3. Check b_ringtones_music_director
if (!$custom_seo_found) {
    $sql_check_md = "SELECT musicdirector_seotitle, faq FROM b_ringtones_music_director WHERE music_director = ? LIMIT 1";
    if ($stmt = $con->prepare($sql_check_md)) {
        $stmt->bind_param("s", $category_slug);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            $stmt->bind_result($db_title, $db_faq);
            $stmt->fetch();
            if (!empty($db_title)) { $custom_seo_title = $db_title; $custom_seo_found = true; }
            if (!empty($db_faq)) { $custom_faq_content = $db_faq; }
        }
        $stmt->close();
    }
}

// -------------------------------------------------------------------------
// 5. CONSTRUCT FINAL SEO TAGS
// -------------------------------------------------------------------------

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

// Title Logic
if ($custom_seo_found) {
    $pageTitle = $custom_seo_title;
} else {
    // Dynamic Title: Includes count if meaningful
    if($total_ringtones > 0) {
        $pageTitle = "Download Top $total_ringtones " . $category_name . " Ringtones (MP3) | " . $category_name . " Songs";
    } else {
        $pageTitle = "Latest " . $category_name . " Ringtones Download (Mp3 & M4R & Songs)";
    }
}

// Description Logic
if (!empty($custom_seo_desc)) {
    $metaDesc = strip_tags($custom_seo_desc);
} else {
    // Dynamic Description: Uses count, year, and cast for uniqueness
    if ($total_ringtones > 0) {
        $metaDesc = "Listen and Download $total_ringtones+ high-quality $category_name ringtones free. Includes trending BGM from " . ($first_year ? $first_year : 'latest movies') . ", dialogue tones" . ($first_cast ? " starring $first_cast" : "") . " and songs for Android & iPhone.";
    } else {
        $metaDesc = "Explore our exclusive collection of free $category_name ringtones, including Latest $category_name ringtone, $category_name songs, popular tunes, and more.";
    }
}

$pageKeywords = $category_name . " ringtone, " . $category_name . " bgm download, " . $category_name . " mp3, m4r, android, iphone, best ringtones 2024";
?>

<!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 $metaDesc; ?>">
    <meta name="keywords" content="<?php echo $pageKeywords; ?>">
    <link rel="canonical" href="<?php echo $canonicalUrl; ?>">
    
    <!-- ADVANCED ROBOTS (Improve Snippets) -->
    <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1">

    <!-- OPEN GRAPH (Facebook/Linkedin) -->
    <meta property="og:type" content="music.playlist">
    <meta property="og:title" content="<?php echo $pageTitle; ?>">
    <meta property="og:description" content="<?php echo $metaDesc; ?>">
    <meta property="og:url" content="<?php echo $canonicalUrl; ?>">
    <meta property="og:site_name" content="<?php echo $sitename; ?>">
    <meta property="og:image" content="<?php echo $siteurlnav; ?>/images/<?php echo isset($faviconurl) ? $faviconurl : 'pagalworld.png';?>">

    <!-- TWITTER CARDS (X) -->
    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="<?php echo $pageTitle; ?>">
    <meta name="twitter:description" content="<?php echo $metaDesc; ?>">
    <meta name="twitter:image" content="<?php echo $siteurlnav; ?>/images/<?php echo isset($faviconurl) ? $faviconurl : 'pagalworld.png';?>">
    
    <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; text-decoration: underline; }
        h1 { font-size: 1.8rem; margin: 15px 0 10px; color: #fff; text-transform: capitalize; }
        .seo-intro { color: #ccc; font-size: 1rem; margin-bottom: 20px; line-height: 1.5; }
        .details h3 { margin: 0; padding: 0; }
        
        /* Changed to article for semantics */
        article.ringtone { 
            border: 1px solid #333; margin-bottom: 15px; padding: 10px; 
            border-radius: 8px; background: #111; cursor: pointer;
            transition: all 0.2s ease-in-out;
        }
        article.ringtone:hover { background: #1a1a1a; border-color: greenyellow; }
        
        .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;
        }
        
        .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; display: flex; align-items: center; gap: 10px; }
        .author-box img { border-radius: 50%; width: 40px; height: 40px; object-fit: cover; }
        
        /* FAQ Styling */
        .faq { margin-top: 30px; margin-bottom: 20px; color: #ddd; background: #0a0a0a; padding: 15px; border-radius: 8px; }
        .faq h2 { color: #fff; margin-bottom: 15px; border-bottom: 1px solid #333; padding-bottom: 10px; font-size: 1.5rem; }
        .faq h3 { color: #00d4ff; margin-top: 20px; font-size: 1.1rem; }
        .faq p { line-height: 1.6; margin-bottom: 10px; color: #ccc; }
        
        .ringtone-list .ringtone .download-button a {
 box-shadow: inset 0px 0px 4px 2px rgb(55 115 32 / 93%);}
    </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
    // --- DISPLAY BREADCRUMBS ---
    $lang_url = "/ringtones/" . urlformat_seo($meta_lang);
    echo '<nav class="breadcrumb-nav" aria-label="Breadcrumb">';
    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 '</nav>';

    // --- DISPLAY H1 (Custom or Default) ---
    if ($custom_seo_found) {
        echo "<h1>" . htmlspecialchars($custom_seo_title) . "</h1>";
    } else {
        echo "<h1>Download ". ucfirst(htmlspecialchars($category_name))  .  " Ringtones</h1>";
    }
    
    // --- DISPLAY SEO INTRO ---
    echo '<div class="seo-intro">';
    if (!empty($custom_seo_desc)) {
        // Display description_for_album from database
        echo "<p>" . $custom_seo_desc . "</p>";
    } else {
        // Dynamic Default Text
        echo "<p>Looking for the best <strong>" . htmlspecialchars($category_name) . "</strong> ringtones? You've come to the right place. 
        We have a collection of <strong>$total_ringtones</strong> high-quality MP3 BGMs, dialogue tones, and theme music from " . htmlspecialchars($category_name) . ". 
        Optimized for all Android and iOS devices. Free to download.</p>";
    }
    echo '</div>';


    // --- DISPLAY LIST OF RINGTONES ---
    $schemaList = []; 

    if ($total_ringtones > 0) {
        
        // Use <main> for the primary content
        echo '<main 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;
            
            $raw_album = $row_sitemap['album'];
            $raw_year = isset($row_sitemap['year']) ? $row_sitemap['year'] : '';
            $raw_stars = $row_sitemap['stars'];
            $raw_directors = $row_sitemap['musicdirectors'];

            // Post Search Logic
            $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) . '%';
            
            // Re-using connection for inner loop
            if ($stmt_posts = $con->prepare("SELECT title, `download link` AS download_link, download_count, duration FROM posts WHERE title LIKE ? LIMIT 1")) {
                $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";

                    // Audio with preload=none to speed up initial page load
                    $audioPlayerHtml = "<audio controls preload='none' controlsList='nodownload' style='width:100%; margin-top:10px;'><source src='$direct_download_url' type='audio/mpeg' /></audio>";
                    $playsText = "<div class='time'> &#9658; 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 (Using ARTICLE tag)
            echo '<article class="ringtone" onclick="window.location=\'' . $anchor_href . '\';">';
                echo "<div class='details'>";
                
                    // 1. Song Title (H2 for better hierarchy inside Main)
                    echo "<h2 style='font-size: 18px; margin-bottom:5px; margin-top:0;'>";
                    echo "<a href='" . $anchor_href . "' title='Download " . $clean_title . " Ringtone'>$clean_title Ringtone</a>";
                    echo "</h2>";

                    // --- AUTHOR BOX (Lazy Load Image) ---
                    $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 '<img src="' . $author_image . '" alt="' . htmlspecialchars($category_name) . ' Ringtone Uploader" loading="lazy" width="30" height="30">';
                    echo '<span itemprop="name" style="font-size:18px; color:#777;">By <a href="' . $author_slug . '" style="color:#59dde0;" rel="nofollow">' . $author_name . '</a></span>';
                    echo '</div>';

                    // 2. Song Meta Data
                    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:#00d4ff; font-size:18px;'> MORE ringtones from $clean_title </a>";
                    echo "</div>";
                    echo $playsText;
                    echo "<div class='download-button'>";
                    echo "<a href='" . $anchor_href . "' onclick='event.stopPropagation();' title='Download " . $clean_title . "' class='dl-btn' style='color:#00d4ff;'>⬇ Download MP3</a>";
                    echo "</div>";
                }
            echo '</article>'; 
        }
        echo '</main>'; // End Main
        
        // --- SCHEMA JSON-LD GENERATION ---
        
        // 1. Breadcrumb Schema
        $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]
            ]
        ];

        // 2. CollectionPage Schema (Better for Lists)
        $schemaCollection = [
            "@context" => "https://schema.org",
            "@type" => "CollectionPage",
            "name" => $pageTitle,
            "description" => $metaDesc,
            "url" => $canonicalUrl,
            "mainEntity" => [
                "@type" => "ItemList",
                "itemListElement" => []
            ]
        ];

        $pos = 1;
        foreach($schemaList as $item) {
            $schemaCollection['mainEntity']['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($schemaCollection) . '</script>';

    } else {
        echo "<p style='padding:20px; text-align:center;'>No ringtones found for <strong>" . htmlspecialchars($category_name) . "</strong>.</p>";
    }
    
    // --- PRINT FAQ CONTENT (Before Footer) ---
    if (!empty($custom_faq_content)) {
        echo "<section class='faq-section'>";
        echo $custom_faq_content;
        echo "</section>";
    }
    
    $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>