<?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
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);
    return trim($string, '-');
}

function generateInternalLinks($commaString, $basePath = '/category/') {
    if (empty($commaString)) return "N/A";
    $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' 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('/category/', '', $request_uri);
$category_slug = explode('?', $category_slug)[0]; 
$category_slug = rtrim($category_slug, '/');
$category_name = ucwords(str_replace('-', ' ', $category_slug));

// 4. FETCH DATA
$sitemapData = [];
$meta_lang = "Ringtones";
$first_cast = "";
$first_year = "";

$sitemap_conditions = [];
$sitemap_search_param = '%' . $category_name . '%';
$sitemap_search_columns = [
    'URLSLIST', 'tracklist', 'musicstyle', 'lyrics', 'year',
    'tags', 'album', 'industry', 'language', 'stars', 'musicdirectors'
];

foreach ($sitemap_search_columns as $column) {
    $sitemap_conditions[] = "$column LIKE ?";
}
$sitemap_where_clause = implode(' OR ', $sitemap_conditions);

// *** UPDATE 1: Added 'tags' to the SELECT list below ***
$sql_sitemap = "SELECT URLSLIST, desc1, year, stars, musicdirectors, album, language, tags FROM sitemapcomio 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();
}

$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 SEO & Album Data
$custom_seo_found = false;
$custom_seo_title = "";
$custom_seo_desc = ""; 
$custom_faq_content = ""; 
$albumTableData = null; 

// 1. Check albums
if (!$custom_seo_found) {
    $sql_check_album = "SELECT seotitle, description_for_album, faq, album, stars, language, year, musicdirectors, image 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, $tbl_album, $tbl_stars, $tbl_lang, $tbl_year, $tbl_md, $tbl_img);
            $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; }
            
            $albumTableData = [
                'album' => $tbl_album,
                'stars' => $tbl_stars,
                'language' => $tbl_lang,
                'year' => $tbl_year,
                'musicdirectors' => $tbl_md,
                'image' => $tbl_img
            ];
        }
        $stmt->close();
    }
}

// 2. Check 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 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();
    }
}

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

// Title & Desc Construction
if ($custom_seo_found) {
    $pageTitle = $custom_seo_title;
} else {
    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)";
    }
}

if (!empty($custom_seo_desc)) {
    $metaDesc = strip_tags($custom_seo_desc);
} else {
    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 ";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="canonical" href="<?php echo $canonicalUrl; ?>">
    <meta name="robots" content="index, follow, max-image-preview:large">
<meta property="og:site_name" content="Telugu Ringtones Ringtones BGM" />
<meta name="author" content="Telugu Ringtones" />
    <link rel="icon" type="image/x-icon" href="/images/<?php echo isset($faviconurl) ? $faviconurl : 'pagalworld.png';?>">
    
    <link rel="stylesheet" type="text/css" href="../css/ringtonelist.css">
    <link rel="stylesheet" type="text/css" href="../css/indexpage2.css">
    <link rel="stylesheet" type="text/css" href="../css/categorypage.css">
    
    <!-- GRID CSS FOR RECENT ALBUMS -->
<style>
    .recent-albums-wrap { 
        margin: 20px 0; 
        padding: 10px; 
        background: #090000; 
        border-radius: 8px; 
        box-shadow: 0 1px 3px rgba(0,0,0,0.1); 
    }
    .recent-albums-wrap h3 { 
        font-size: 18px; 
        color: #ffffff; 
        margin-bottom: 15px; 
        border-bottom: 2px solid #333; 
        padding-bottom: 5px; 
    }
    
    /* 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 { 
        color: #007bff; 
    }
    .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; 
    }
    /* Tags Styling */
    .ringtone-tags {
        font-size: 0.85rem;
        color: #888;
        margin-bottom: 5px;
        line-height: 1.4;
    }
    .ringtone-tags a {
    color: #949aa0;
    text-decoration: none;
}
    .ringtone-tags a:hover {
        text-decoration: underline;
    }

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

    <?php 
    if(file_exists('../externalhead.php')) {
        include('../externalhead.php');
    }
    ?>
</head>

<body>

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

<div class="content-wrapper">

    <?php
    // --- BREADCRUMBS ---
    $lang_url = "/category/" . 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>';

    // --- H1 ---
    if ($custom_seo_found) {
        echo "<h1>" . htmlspecialchars($custom_seo_title) . "</h1>";
    } else {
        echo "<h1> ". ucfirst(htmlspecialchars($category_name))  .  "</h1>";
    }
    
    // --- INTRO ---
    echo '<div class="seo-intro">';
    if (!empty($custom_seo_desc)) {
        echo "<p>" . $custom_seo_desc . "</p>";
    } else {
       // echo "<p>Looking for the best <strong>" . htmlspecialchars($category_name) . "</strong> ringtones? 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>';

    echo "<h2>Ringtones In this Category</h2>";

    // --- LIST ---
    if ($total_ringtones > 0) {
        
        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'];
            // Get Tags
            $raw_tags = isset($row_sitemap['tags']) ? $row_sitemap['tags'] : '';

            $audioPlayerHtml = "<p class='preview-unavailable'>Audio preview unavailable</p>";
            $playsText = "";
            
            // Search Keyword Logic
            $search_clean_string = str_replace('-', ' ', $row_sitemap['URLSLIST']);
            $keywords = array_values(array_filter(explode(' ', $search_clean_string)));

            if (count($keywords) > 0) {
                $likeClauses = array_map(function($keyword) {
                    return "CONCAT(' ', title, ' ') LIKE ?";
                }, $keywords);

                $sql_posts = "SELECT title, `download link` AS download_link, download_count, duration FROM posts WHERE " . implode(' AND ', $likeClauses) . " LIMIT 1";
                
                if ($stmt_posts = $con->prepare($sql_posts)) {
                    $searchTerms = array_map(function($keyword) {
                        return "% " . $keyword . " %";
                    }, $keywords);
                    $types = str_repeat('s', count($searchTerms));
                    $stmt_posts->bind_param($types, ...$searchTerms);
                    $stmt_posts->execute();
                    $result_posts = $stmt_posts->get_result();

                    if ($row_post = $result_posts->fetch_assoc()) {
                        $direct_download_url = $siteurl . htmlspecialchars($row_post['download_link']);
                        $d_count = (int)$row_post['download_count'];
                        $duration = (int)$row_post['duration'];
                        $audioPlayerHtml = "<audio controls preload='none' controlsList='nodownload' class='audio-player'><source src='$direct_download_url' type='audio/mpeg' /></audio>";
                        $playsText = "<div class='time'> &#9658; 120+ Plays, $d_count Downloads </div>";
                    }
                    $stmt_posts->close();
                }
            }

            echo '<article class="ringtone" onclick="window.location=\'' . $anchor_href . '\';">';
                echo "<div class='details'>";
                    echo "<h3 class='ringtone-title'>";
                    echo "<a href='" . $anchor_href . "' title='Download " . $clean_title . "'>$clean_title</a>";
                    echo "</h3>";
 
                    // *** UPDATE 2: Added Tags Display Here ***
                    if (!empty($raw_tags)) {
                        echo "<div class='ringtone-tags'>";
                        echo "Category: " . generateInternalLinks($raw_tags, '/category/');
                        echo "</div>";
                    }

                    if (empty($albumTableData)) {
                        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>";

                echo "<div class='controls'>" . $audioPlayerHtml . "</div>";
                
              
                echo $playsText;
                echo "<div class='download-button'>";
                echo "<a href='" . $anchor_href . "' onclick='event.stopPropagation();' title='Download " . $clean_title . "' class='dl-btn download-link-blue'>⬇ Download</a>";
                echo "</div>";
                  echo "<div class='download-button'>";
                echo "<a href='" . $anchor_href . "' onclick='event.stopPropagation();' class='more-link'> MORE ringtones LIKE $clean_title </a>";
                echo "</div>";
            echo '</article>'; 
        }
        echo '</main>';
        
    } else {
        echo "<p class='no-results'>No ringtones found for <strong>" . htmlspecialchars($category_name) . "</strong>.</p>";
    }
    
    // --- FAQ ---
    if (!empty($custom_faq_content)) {
        echo "<section class='faq-section'>";
        echo $custom_faq_content;
        echo "</section>";
    }

echo "<p> TAGS: ".generateInternalLinks($albumTableData['album']);
echo ", ".generateInternalLinks($albumTableData['stars']);
echo ", ".generateInternalLinks($albumTableData['musicdirectors']);
echo  ", ".generateInternalLinks($albumTableData['language']);
echo  ", ".generateInternalLinks($albumTableData['year']);

echo "</p>";

    // --- TABLE ---
    if ($albumTableData) {
        //echo "<section class='album-details-section'>";
       // echo "<h2 class='album-section-header'>Movie / Album Details</h2>";
        
       // echo "<table class='movie-details-table'>";
       // echo "<tbody>";

       // echo "<tr><th>Movie / Album</th><td>" . generateInternalLinks($albumTableData['album']) . "</td></tr>";

      //  if (!empty($albumTableData['stars'])) {
       //     echo "<tr><th>Star Cast</th><td>" . generateInternalLinks($albumTableData['stars']) . "</td></tr>";
       // }
       // if (!empty($albumTableData['musicdirectors'])) {
         //   echo "<tr><th>Music Director</th><td>" . generateInternalLinks//($albumTableData['musicdirectors']) . "</td></tr>";
       // }
       // if (!empty($albumTableData['language'])) {
       //     echo "<tr><th>Language</th><td>" . generateInternalLinks//($albumTableData['language']) . "</td></tr>";
        //}
       // if (!empty($albumTableData['year'])) {
          //  echo "<tr><th>Year</th><td>" . generateInternalLinks($albumTableData['year']) . "</td></tr>";
        }

        //echo "</tbody>";
       // echo "</table>";
        
        if (!empty($albumTableData['image'])) {
            echo "<tr><th></th>";
            $imgSrc = $albumTableData['image'];
            if(strpos($imgSrc, 'http') === false) {
                 $imgSrc = $siteurlnav . '/images/category/' . $imgSrc; 
            }
            echo "<td><img src='" . htmlspecialchars($imgSrc) . "' alt='" . htmlspecialchars($albumTableData['album']) . " Poster' class='album-art' loading='lazy'></td></tr>";
        }
     //   echo "</section>";
  //  }

    // --- RECENT ALBUMS SECTION ---
    $sql_recent = "SELECT album, image FROM sitemapbollyalbums ORDER BY id DESC LIMIT 8";
    $result_recent = $con->query($sql_recent);
    
    if ($result_recent && $result_recent->num_rows > 0) {
        echo '<section class="recent-albums-wrap">';
        echo '<h3>Recent Albums</h3>';
        echo '<div class="recent-grid">';
        while($row = $result_recent->fetch_assoc()) {
            $raw_name = $row['album'];
            $clean_name = ucwords(str_replace('-', ' ', $raw_name));
            $link_slug = "/category/" . urlformat_seo($raw_name);
            
            $imgSrcRecent = $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="' . htmlspecialchars($imgSrcRecent) . '" alt="' . htmlspecialchars($clean_name) . '" loading="lazy">';
            echo '<span>' . $clean_name . '</span>';
            echo '</a>';
        }
        echo '</div>';
        echo '</section>';
    }
    
    $con->close();
    include('../footer.php');
    ?>
</div>

<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 
$content = ob_get_clean();
file_put_contents($cacheFile, $content);
echo $content;
?>
</body>
</html>