<?php
// 1. DATABASE & CONFIG
include('databaseconnect.php');
include('sitedetails.php');

// Helper function to format URLs
function urlformat($string) {
    $string = strtolower($string);
    $string = str_replace([' ', '_'], '-', $string);
    $string = preg_replace('/[^a-z0-9\-]/', '', $string);
    $string = preg_replace('/-+/', '-', $string);
    $string = trim($string, '-');
    return $string;
}

$sitecategorypatternurl = '/ringtone/';

// --- PAGINATION SETTINGS ---
$limit = 1000; // UPDATED: 1000 posts per page

// Page Detection Logic
// Tries $_GET first (if .htaccess rewrites are active), otherwise parses URI path
$page = 1;
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
    $page = (int)$_GET['page'];
} elseif (strpos($_SERVER['REQUEST_URI'], '/page/') !== false) {
    // Fallback: Parse URL like /home/page/5 if $_GET isn't set
    $parts = explode('/page/', $_SERVER['REQUEST_URI']);
    if (isset($parts[1])) {
        $page = (int)$parts[1];
    }
}

if ($page < 1) $page = 1;
$start_from = ($page - 1) * $limit;

// Base URL for pagination links
$pagination_base_url = '/home/page/';

// 1. Get Total Records
$sql_count = "SELECT COUNT(ID) AS total FROM $tablename";
$result_count = $con->query($sql_count);
$row_count = $result_count->fetch_assoc();
$total_records = $row_count['total'];
$total_pages = ceil($total_records / $limit);

// 2. Fetch posts
$sql = "SELECT URLSLIST, modified_date, ID, album, tags, year 
        FROM $tablename 
        ORDER BY modified_date DESC 
        LIMIT $start_from, $limit";
$result = $con->query($sql);
?>

<!-- 2. CSS STYLING -->
<style>
    /* Container settings */
    .track-list-container {
        max-width: 900px;
        margin: 30px auto;
        padding: 0 10px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    /* Individual Row */
    .track-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: #111;
        border: 1px solid #222;
        padding: 12px 20px;
        margin-bottom: 10px;
        border-radius: 50px;
        transition: all 0.2s ease-in-out;
    }

    .track-row:hover {
        background-color: #1a1a1a;
        border-color: #444;
        transform: scale(1.01);
        box-shadow: 0 4px 15px rgba(0,0,0,0.5);
    }

    /* Left side: Info wrapper */
    .track-info {
        display: flex;
        flex-direction: column;
        justify-content: center;
        gap: 2px;
        overflow: hidden; 
    }

    /* SONG TITLE LINK */
    .track-title {
        font-size: 1.1rem;
        font-weight: 700;
        color: #fff;
        text-decoration: none;
        letter-spacing: 0.5px;
        margin-bottom: 2px;
    }

    .track-title:hover {
        color: #ff00cc;
        text-decoration: underline;
    }

    /* TAGS STYLING */
    .track-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
        margin-bottom: 4px;
    }

    .track-tag-link {
        font-size: 0.7rem;
        color: #aaa;
        background-color: #2a2a2a;
        padding: 1px 6px;
        border-radius: 4px;
        text-decoration: none;
        transition: background 0.2s, color 0.2s;
    }

    .track-tag-link:hover {
        background-color: #444;
        color: greenyellow;
    }

    /* ALBUM LINK */
    .track-album {
        font-size: 0.8rem;
        color: #00d4ff;
        text-decoration: none;
        display: inline-block;
        width: fit-content;
        font-weight: 600;
        text-transform: uppercase;
        opacity: 0.8;
        transition: opacity 0.2s;
    }

    .track-album:hover {
        opacity: 1;
        text-decoration: underline;
        color: #5effff;
    }

    /* DOWNLOAD BUTTON */
    .track-btn {
        background: linear-gradient(90deg, #8A2387, #E94057, #F27121);
        color: white;
        padding: 10px 25px;
        border-radius: 30px;
        text-decoration: none;
        font-weight: bold;
        font-size: 0.9rem;
        white-space: nowrap;
        margin-left: 15px; 
        box-shadow: 0 4px 15px rgba(233, 64, 87, 0.4);
        transition: transform 0.2s;
    }

    .track-btn:hover {
        transform: translateY(-2px);
        filter: brightness(1.2);
    }

    /* --- PAGINATION CSS --- */
    .pagination-wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 5px;
        margin-top: 30px;
        margin-bottom: 50px;
        flex-wrap: wrap;
    }

    .page-link {
        display: inline-block;
        padding: 8px 14px;
        background-color: #111;
        border: 1px solid #333;
        color: #fff;
        text-decoration: none;
        border-radius: 5px;
        font-size: 0.9rem;
        transition: all 0.2s;
    }

    .page-link:hover {
        background-color: #333;
        border-color: #555;
    }

    .page-link.active {
        background: linear-gradient(90deg, #8A2387, #E94057);
        border-color: transparent;
        font-weight: bold;
    }

    @media (max-width: 600px) {
        .track-row {
            border-radius: 15px;
            padding: 15px;
        }
        .track-btn {
            padding: 8px 15px;
            font-size: 0.75rem;
        }
        .track-title { font-size: 1rem; }
    }
</style>

<!-- 3. HTML OUTPUT -->
<div class="track-list-container">

    <?php
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            
            // Prepare Data
            $fullUrl = $row["URLSLIST"];
            $album = $row["album"];
            $albumurl = urlformat($album);
            
            // Get Tags
            $tags_raw = isset($row["tags"]) ? $row["tags"] : '';

            $slug = basename($fullUrl);
            $title = ucwords(str_replace('-', ' ', $slug));
            
            // Define Links
            $songLink = htmlspecialchars($siteurlnav) . htmlspecialchars($sitecategorypatternurl) . htmlspecialchars($slug);
            $albumLink = '/category/' . htmlspecialchars($albumurl);

            // Output HTML
            echo '<div class="track-row">';
                
                // Left Side
                echo '<div class="track-info">';
                    
                    // 1. Title
                    echo '<a href="' . $songLink . '" class="track-title">' . htmlspecialchars($title) . '</a>';
                    
                    // 2. Tags
                    if (!empty($tags_raw)) {
                        echo '<div class="track-tags">';
                        $tags_array = explode(',', $tags_raw);
                        
                        $count = 0;
                        foreach ($tags_array as $tag) {
                            if ($count >= 10) break; 
                            $clean_tag = trim($tag);
                            if (!empty($clean_tag)) {
                                $catPrefix = isset($urlpatterncat) ? $urlpatterncat : '/tag/';
                                $tagLink = $catPrefix . urlformat($clean_tag);
                                echo '<a href="' . $tagLink . '" class="track-tag-link">#' . htmlspecialchars($clean_tag) . '</a>';
                            }
                            $count++;
                        }
                        echo '</div>';
                    }

                    // 3. Album
                    echo '<a href="' . $albumLink . '" class="track-album">';
                    echo '📁 ' . htmlspecialchars($album); 
                    echo '</a>';
                    
                echo '</div>';

                // Right Side: Button
                echo '<a href="' . $songLink . '" class="track-btn">DOWNLOAD ➜</a>';

            echo '</div>';
        }
    } else {
        echo '<p style="color:white; text-align:center;">No posts found.</p>';
    }
    ?>

    <!-- 4. PAGINATION CONTROLS -->
    <?php if ($total_pages > 1): ?>
    <div class="pagination-wrapper">
        <?php
        $range = 2; // Range of pages to show around current page

        // PREVIOUS BUTTON
        if ($page > 1) {
            echo '<a href="' . $pagination_base_url . ($page - 1) . '" class="page-link">« Prev</a>';
        }

        // FIRST PAGE LINK (if far away)
        if ($page > ($range + 1)) {
            echo '<a href="' . $pagination_base_url . '1" class="page-link">1</a>';
            if ($page > ($range + 2)) {
                echo '<span class="page-link" style="border:none; background:transparent;">...</span>';
            }
        }

        // LOOP NUMBERED LINKS
        for ($x = ($page - $range); $x <= ($page + $range); $x++) {
            if ($x > 0 && $x <= $total_pages) {
                if ($x == $page) {
                    echo '<span class="page-link active">' . $x . '</span>';
                } else {
                    echo '<a href="' . $pagination_base_url . $x . '" class="page-link">' . $x . '</a>';
                }
            }
        }

        // LAST PAGE LINK (if far away)
        if ($page < ($total_pages - $range)) {
            if ($page < ($total_pages - $range - 1)) {
                echo '<span class="page-link" style="border:none; background:transparent;">...</span>';
            }
            echo '<a href="' . $pagination_base_url . $total_pages . '" class="page-link">' . $total_pages . '</a>';
        }

        // NEXT BUTTON
        if ($page < $total_pages) {
            echo '<a href="' . $pagination_base_url . ($page + 1) . '" class="page-link">Next »</a>';
        }
        ?>
    </div>
    <?php endif; ?>

    <?php $con->close(); ?>

</div>