<?php

// category.php file

// 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 "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('/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)
// -------------------------------------------------------------------------

// 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 Table Data
$custom_seo_found = false;
$custom_seo_title = "";
$custom_seo_desc = ""; 
$custom_faq_content = ""; 
$albumTableData = null; // Container for table data

// 1. Check sitemapbollyalbums (Added extra columns for Table)
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();
            
            // Set SEO Data
            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; }
            
            // Set Table Data
            $albumTableData = [
                'album' => $tbl_album,
                'stars' => $tbl_stars,
                'language' => $tbl_lang,
                'year' => $tbl_year,
                'musicdirectors' => $tbl_md,
                'image' => $tbl_img
            ];
        }
        $stmt->close();
    }
}

// 2. Check b_ringtones_cast (If not found in albums)
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 not found in albums or cast)
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 {
    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 {
    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">
    
    <!-- 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 -->
    <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1">

    <!-- OPEN GRAPH -->
    <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 -->
    <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">
    <link rel="stylesheet" type="text/css" href="../css/categorypage.css">

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

<body>

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

<div class="content-wrapper">

    <?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 ---
    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)) {
        echo "<p>" . $custom_seo_desc . "</p>";
    } else {
        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>';

    echo "<h2>Download ". ucfirst(htmlspecialchars($category_name))  .  " Ringtones AND SONGS BGM</h2>";

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

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

            // -----------------------------------------------------------------
            // POST SEARCH LOGIC (UPDATED WITH KEYWORD SEARCH)
            // -----------------------------------------------------------------
            $foundPost = false;
            $audioPlayerHtml = "<p class='preview-unavailable'>Audio preview unavailable</p>";
            $playsText = "";
            $direct_download_url = "";
            $durationISO = "PT0M30S";

            // 1. Prepare Keywords: Replace hyphens with space, explode, filter empty, re-index
            $search_clean_string = str_replace('-', ' ', $row_sitemap['URLSLIST']);
            $keywords = array_values(array_filter(explode(' ', $search_clean_string)));

            if (count($keywords) > 0) {
                // 2. Prepare SQL statement with placeholders for exact word match simulation
                // mapping keywords to CONCAT clauses
                $likeClauses = array_map(function($keyword) {
                    return "CONCAT(' ', title, ' ') LIKE ?";
                }, $keywords);

                // Build the Query
                $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)) {
                    
                    // 3. Prepare search terms with wildcards & spaces
                    $searchTerms = array_map(function($keyword) {
                        return "% " . $keyword . " %";
                    }, $keywords);

                    // Create type string 'ssss...'
                    $types = str_repeat('s', count($searchTerms));

                    // 4. Bind parameters and execute
                    // Note: ...$searchTerms (Argument Unpacking) requires PHP 5.6+
                    $stmt_posts->bind_param($types, ...$searchTerms);
                    
                    $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' class='audio-player'><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();
                }
            }
            // -----------------------------------------------------------------
            // END POST SEARCH LOGIC
            // -----------------------------------------------------------------

            // 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 '<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 . " Song Ringtone'>$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 '<img src="' . $author_image . '" alt="' . htmlspecialchars($category_name) . ' Ringtone Uploader" loading="lazy" width="30" height="30">';
                    echo '<span itemprop="name" class="author-text">By <a href="' . $author_slug . '" class="author-link" rel="nofollow">' . $author_name . '</a></span>';
                    echo '</div>';
  if (!empty($albumTableData)) {
    } else {
       
    
                    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 "<div class='download-button'>";
                    echo "<a href='" . $anchor_href . "' onclick='event.stopPropagation();' class='more-link'> MORE ringtones LIKE $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 download-link-blue'>⬇ Download MP3</a>";
                    echo "</div>";
                
            echo '</article>'; 
        }
        echo '</main>';
        
        // --- 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]
            ]
        ];

        $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 class='no-results'>No ringtones found for <strong>" . htmlspecialchars($category_name) . "</strong>.</p>";
    }
    
    // --- DISPLAY FAQ ---
    if (!empty($custom_faq_content)) {
        echo "<section class='faq-section'>";
        echo $custom_faq_content;
        echo "</section>";
    }

    // --- DISPLAY ALBUM DETAILS TABLE (AFTER FAQ) ---
    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>";

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

        // Star Cast (Comma Separated)
        if (!empty($albumTableData['stars'])) {
            echo "<tr>";
            echo "<th>Star Cast</th>";
            echo "<td>" . generateInternalLinks($albumTableData['stars']) . "</td>";
            echo "</tr>";
        }

        // Music Directors (Comma Separated)
        if (!empty($albumTableData['musicdirectors'])) {
            echo "<tr>";
            echo "<th>Music Director</th>";
            echo "<td>" . generateInternalLinks($albumTableData['musicdirectors']) . "</td>";
            echo "</tr>";
        }

        // Language
        if (!empty($albumTableData['language'])) {
            echo "<tr>";
            echo "<th>Language</th>";
            echo "<td>" . generateInternalLinks($albumTableData['language']) . "</td>";
            echo "</tr>";
        }

        // Year
        if (!empty($albumTableData['year'])) {
            echo "<tr>";
            echo "<th>Year</th>";
            echo "<td>" . generateInternalLinks($albumTableData['year']) . "</td>";
            echo "</tr>";
        }

      

        echo "</tbody>";
        echo "</table>";
        
          // Image
        if (!empty($albumTableData['image'])) {
            echo "<tr>";
            echo "<th></th>";
            // Check if full URL or path
            $imgSrc = $albumTableData['image'];
            if(strpos($imgSrc, 'http') === false) {
                 $imgSrc = $siteurlnav . '/images/ringtones/' . $imgSrc; // Adjust path as per your directory structure
            }
            echo "<td><img src='" . htmlspecialchars($imgSrc) . "' alt='" . htmlspecialchars($albumTableData['album']) . " Poster' class='album-art' loading='lazy'></td>";
            echo "</tr>";
        }
        echo "</section>";
    }
    
    $con->close();
    include('../footer.php');
    ?>

</div>

<!-- JAVASCRIPT -->
<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>