<?php
ob_start();
$cacheExpire = 172800; // in seconds

// Parse the requested URL
$requestedUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$cacheFile = 'cache/' . md5($requestedUrl) . '.html';

// Check if cached content exists and is not expired
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheExpire) {
    // Serve the cached content
    echo file_get_contents($cacheFile);
    // Stop executing the script further
    exit();
}
?>


<?php
include '../sitedetails.php';


?>
<meta charset="UTF-8">

<!DOCTYPE html>
<style>
  body{
    color: white;
  }
  
  a {
    color: greenyellow;
}


</style>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
<meta property="og:site_name" content="<?php echo $sitename;?> Ringtones BGM" />
<meta name="author" content="<?php echo $sitename;?>" />
<link rel="icon" type="image/x-icon" href="/images/<?php echo $faviconurl;?>">
<link rel="stylesheet" type="text/css" href="../css/ringtonelist.css">
</head>


<link rel="stylesheet" type="text/css" href="../css/indexpage2.css">
    <!-- Google tag (gtag.js) -->


<link rel="icon" type="image/x-icon" href="/images/pagalworld.png">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
   <script type="text/javascript" src="script.js"></script>


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

///////////////////////////////////////////
// 1. Include your database connection file
include('../databaseconnect.php'); // This file should establish your $con database connection

// Define your site URL. Replace with your actual site URL.
// This is crucial for the ringtone download link.
$siteurl = "https://gummu.net"; // <-- IMPORTANT: Set your actual website URL here

// 2. Get the current URL path
$request_uri = $_SERVER['REQUEST_URI'];

// 3. Clean the URL to extract the category name
// Example: /category/thaman-s becomes 'thaman s'
$category_slug = str_replace($urlpatterncat, '', $request_uri);
$category_name = str_replace('-', ' ', $category_slug);

// You might want to sanitize this further, e.g., using mysqli_real_escape_string
// For demonstration, we'll use it directly in the query with prepared statements.

// 4. Construct the SQL query to search across multiple columns in sitemapbolly
$sitemap_conditions = [];
$sitemap_search_param = '%' . $category_name . '%'; // Prepare the search string with wildcards

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

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

$sitemap_where_clause = implode(' OR ', $sitemap_conditions);

$sql_sitemap = "SELECT URLSLIST FROM sitemapbolly WHERE $sitemap_where_clause ORDER BY ID DESC";

// 5. Prepare and execute the sitemapbolly statement
if ($stmt_sitemap = $con->prepare($sql_sitemap)) {
    // Bind parameters dynamically for sitemapbolly
    $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();

    // 6. Print the results with the requested div structure
    if ($result_sitemap->num_rows > 0) {
        echo "<title> $category_name Ringtones Download - Tunes </title>";

        echo "<h1>". ucfirst(htmlspecialchars($category_name))  .  " Ringtone Download </h1>";
        
        echo "<h2> Songs, Instrumental , Violin, Entry BGM ". ucfirst($category_name)."</h2>";
        echo '<div class ="ringtone-list">'; // Open the main list container

        while ($row_sitemap = $result_sitemap->fetch_assoc()) {
            $url_list_value = htmlspecialchars($row_sitemap['URLSLIST']);
            
            
            $url_list_value_anchor = str_replace('-', ' ', $url_list_value);

            $anchor_href = $cateurl . $url_list_value;

            // --- NESTED QUERY FOR 'posts' TABLE ---
            // NEW LOGIC: Use the URLSLIST keyword to search for related posts in the 'posts' table
            $ringtone_search_terms_raw = str_replace('-', ' ', $row_sitemap['URLSLIST']);
            $ringtone_keywords = array_filter(explode(' ', $ringtone_search_terms_raw));

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

                $sql_posts = "SELECT title, `download link` AS download_link, download_count FROM posts WHERE " . implode(' AND ', $posts_likeClauses) . " LIMIT 1";

                if ($stmt_posts = $con->prepare($sql_posts)) {
                    $posts_searchTerms = array_map(function($keyword) {
                        return "% " . $keyword . " %"; // Ensure exact word match with spaces
                    }, $ringtone_keywords);

                    $posts_types = str_repeat('s', count($posts_searchTerms));

                    call_user_func_array([$stmt_posts, 'bind_param'], array_merge([$posts_types], refValues($posts_searchTerms)));

                    $stmt_posts->execute();
                    $result_posts = $stmt_posts->get_result();

                    if ($row_post = $result_posts->fetch_assoc()) {
                        // Found a matching ringtone in 'posts', display its details
                        $title = htmlspecialchars($row_post['title']);
                        $download = htmlspecialchars($row_post['download_link']);
                        $download_count = (int)$row_post['download_count'];

                        // The entire .ringtone div will now be a clickable element.
                        // We're adding an inline JavaScript `onclick` to navigate.
                        echo '<div class ="ringtone" onclick="window.location=\'' . htmlspecialchars($anchor_href, ENT_QUOTES, 'UTF-8') . '\';">'; // Open the individual ringtone item container

                        $videohtml = "<audio controls preload='none' controlsList='nofullscreen  noremoteplayback noplaybackrate foobar novolume'><source src='$siteurl$download' type='audio/mpeg' /></audio>";
                        
                        // Display URLSLIST as the title, as requested
                        echo "<div class='details'>
                                <h3 style='font-size: 14px;'>
                                    <a href='" . htmlspecialchars($anchor_href) . "' style='text-decoration:none; color:inherit;'>
                                        " . $url_list_value_anchor . "
                                    </a>
                                </h3>
                              </div>";
                        echo "<div class ='controls'> $videohtml</div>";
                        echo "<div class ='time'> 123 Plays , $download_count Downloads.</div>";
                        
                        // Add the download button.
                        // When this button is clicked, we want to prevent the outer div's click event
                        // from also firing, hence `event.stopPropagation()`.
                        echo "<div class ='download-button'>";
                        echo "<a href='" . htmlspecialchars($anchor_href, ENT_QUOTES, 'UTF-8') . "' onclick='event.stopPropagation();'>Download</a>";
                        echo "</div>";

 echo "<div class ='download-button'>";
                        echo "<a href='" . htmlspecialchars($anchor_href, ENT_QUOTES, 'UTF-8') . "' onclick='event.stopPropagation();'> MORE RINGTONES LIKE $url_list_value_anchor </a>";
                        echo "</div>";
                        echo '</div>'; // Close the individual ringtone item container

                    } else {
                        // No matching ringtone found in 'posts' for this sitemapbolly URLSLIST based on refined search
                        // You could still display the sitemap item as a link, without the player if you wish.
                        echo '<div class ="ringtone">'; // Open the individual ringtone item container
                        echo "<div class='details'>
                                <h3 style='font-size: 14px;'>
                                    <a href='" . htmlspecialchars($anchor_href) . "' style='text-decoration:none; color:inherit;'>
                                        " . htmlspecialchars(str_replace('-', ' ', $row_sitemap['URLSLIST'])) . "
                                    </a>
                                </h3>
                              </div>";
                        echo "<p>No ringtone player available for this item yet.</p>";
                        echo '</div>'; // Close the individual ringtone item container
                    }
                    $stmt_posts->close();
                } else {
                    echo "<p>Error preparing posts statement for " . $url_list_value . ": " . $con->error . "</p>";
                }
            } else {
                // If no keywords could be extracted from URLSLIST
                echo '<div class ="ringtone">'; // Open the individual ringtone item container
                echo "<div class='details'>
                        <h3 style='font-size: 14px;'>
                            <a href='" . htmlspecialchars($anchor_href) . "' style='text-decoration:none; color:inherit;'>
                                " . htmlspecialchars(str_replace('-', ' ', $row_sitemap['URLSLIST'])) . "
                            </a>
                        </h3>
                      </div>";
                echo "<p>No specific keywords found for searching ringtones from this category item.</p>";
                echo '</div>'; // Close the individual ringtone item container
            }
            // --- END NESTED QUERY ---
        }
        echo '</div>'; // Close the main list container
    } else {
        echo "<p>No results found for category: " . htmlspecialchars($category_name) . "</p>";
    }

    $stmt_sitemap->close();
} else {
    echo "Error preparing sitemapbolly statement: " . $con->error;
}

// Helper function for bind_param with dynamic arguments
function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}

// 7. Close the database connection (if not already handled by your include)
mysqli_close($con);


///////////////////////////////////////////////////
include('../footer.php'); // This file should establish your $con database connection

?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-compat/3.0.0-alpha1/jquery.min.js" integrity="sha512-4GsgvzFFry8SXj8c/VcCjjEZ+du9RZp/627AEQRVLatx6d60AUnUYXg0lGn538p44cgRs5E2GXq+8IOetJ+6ow==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    $("audio").on("play", function() {
    $("audio").not(this).each(function(index, audio) {
        audio.pause();
    });
});
</script>

<?php 
    // FILENAME RINGLIST.PHP // RINGTONS BGM//
    $content = ob_get_clean();

    // Cache the generated content
    file_put_contents($cacheFile, $content);
    
    echo $content;
?>