T.ME/BIBIL_0DAY
CasperSecurity


Server : Apache/2
System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64
User : gositeme ( 1004)
PHP Version : 8.2.29
Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname
Directory :  /home/gositeme/domains/soundstudiopro.com/public_html/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/gositeme/domains/soundstudiopro.com/public_html/library_new_redesigned copy.php
<?php
session_start();

// ALWAYS check if user is logged in - no exceptions
if (!isset($_SESSION['user_id'])) {
    header('Location: /auth/login.php');
    exit;
}

// Include database configuration
require_once 'config/database.php';

$user = getUserById($_SESSION['user_id']);
$user_name = $user['name'] ?? 'User';
$credits = $_SESSION['credits'] ?? 5;

// Get user stats
$pdo = getDBConnection();
$stmt = $pdo->prepare("
    SELECT 
        COUNT(*) as total_tracks,
        COUNT(CASE WHEN status = 'complete' THEN 1 END) as completed_tracks,
        COUNT(CASE WHEN status = 'processing' THEN 1 END) as processing_tracks,
        COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_tracks,
        AVG(CASE WHEN status = 'complete' THEN duration END) as avg_duration,
        SUM(CASE WHEN status = 'complete' THEN duration END) as total_duration
    FROM music_tracks 
    WHERE user_id = ?
");
$stmt->execute([$_SESSION['user_id']]);
$user_stats = $stmt->fetch();

// Get user's music tracks with enhanced data and variations
$status_filter = $_GET['status'] ?? 'all';
$sort_filter = $_GET['sort'] ?? 'latest';

// Build WHERE clause for status filtering
$where_clause = "WHERE mt.user_id = ?";
$params = [$_SESSION['user_id']];

if ($status_filter !== 'all') {
    $where_clause .= " AND mt.status = ?";
    $params[] = $status_filter;
}

// Build ORDER BY clause for sorting
$order_clause = "ORDER BY ";
switch ($sort_filter) {
    case 'oldest':
        $order_clause .= "mt.created_at ASC";
        break;
    case 'popular':
        $order_clause = "LEFT JOIN (SELECT track_id, COUNT(*) as like_count FROM track_likes GROUP BY track_id) likes ON mt.id = likes.track_id ORDER BY likes.like_count DESC, mt.created_at DESC";
        break;
    case 'most-played':
        $order_clause = "LEFT JOIN (SELECT track_id, COUNT(*) as play_count FROM track_plays GROUP BY track_id) plays ON mt.id = plays.track_id ORDER BY plays.play_count DESC, mt.created_at DESC";
        break;
    case 'latest':
    default:
        $order_clause .= "mt.created_at DESC";
        break;
}

// Get tracks
$stmt = $pdo->prepare("
    SELECT 
        mt.*,
        COALESCE(vars.variation_count, 0) as variation_count,
        CASE 
            WHEN mt.created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN '🔥 Hot'
            WHEN mt.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN '⭐ New'
            ELSE ''
        END as badge
    FROM music_tracks mt
    LEFT JOIN (
        SELECT track_id, COUNT(*) as variation_count 
        FROM audio_variations 
        GROUP BY track_id
    ) vars ON mt.id = vars.track_id
    $where_clause
    $order_clause
");
$stmt->execute($params);
$user_tracks = $stmt->fetchAll();

// Get variations for each track
$tracks_with_variations = [];
foreach ($user_tracks as $track) {
    $track['variations'] = [];
    
    if ($track['variation_count'] > 0) {
        $stmt = $pdo->prepare("
            SELECT 
                variation_index,
                audio_url,
                duration,
                title,
                tags,
                image_url,
                source_audio_url,
                stream_audio_url
            FROM audio_variations 
            WHERE track_id = ?
            ORDER BY variation_index
        ");
        $stmt->execute([$track['id']]);
        $track['variations'] = $stmt->fetchAll();
    }
    
    $tracks_with_variations[] = $track;
}
$user_tracks = $tracks_with_variations;

// Set page variables for header
$page_title = 'My Music Library - SoundStudioPro';
$page_description = 'View and manage all your AI-generated music tracks. Play, download, and organize your music collection.';
$current_page = 'library_new';

// Include header
include 'includes/header.php';
?>

<!-- Modern Library Design -->
<div class="modern-library">
    <!-- Hero Section -->
    <div class="library-hero">
        <div class="hero-content">
            <div class="hero-badge">
                <i class="fas fa-music"></i>
                My Library
            </div>
            <h1 class="hero-title">Your Music Collection</h1>
            <p class="hero-subtitle">Manage, play, and organize all your AI-generated music tracks. Your creative journey starts here.</p>
        </div>
        <div class="hero-visual">
            <div class="floating-elements">
                <div class="floating-note">♪</div>
                <div class="floating-note">♫</div>
                <div class="floating-note">♬</div>
            </div>
        </div>
    </div>

    <!-- Stats Dashboard -->
    <div class="stats-dashboard">
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-music"></i>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?= $user_stats['total_tracks'] ?></div>
                <div class="stat-label">Total Tracks</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon success">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?= $user_stats['completed_tracks'] ?></div>
                <div class="stat-label">Completed</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon warning">
                <i class="fas fa-clock"></i>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?= $user_stats['processing_tracks'] ?></div>
                <div class="stat-label">Processing</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon error">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?= $user_stats['failed_tracks'] ?></div>
                <div class="stat-label">Failed</div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="library-content">
        <div class="content-header">
            <div class="header-left">
                <h2 class="section-title">Your Music Tracks</h2>
                <p class="section-subtitle">All your AI-generated music in one place</p>
            </div>
            
            <div class="header-controls">
                <div class="filter-group">
                    <select class="modern-select" onchange="window.location.href='?status=' + this.value + '&sort=<?= $sort_filter ?>'">
                        <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                        <option value="complete" <?= $status_filter === 'complete' ? 'selected' : '' ?>>✅ Complete</option>
                        <option value="processing" <?= $status_filter === 'processing' ? 'selected' : '' ?>>⏳ Processing</option>
                        <option value="failed" <?= $status_filter === 'failed' ? 'selected' : '' ?>>❌ Failed</option>
                    </select>
                    
                    <select class="modern-select" onchange="window.location.href='?status=<?= $status_filter ?>&sort=' + this.value">
                        <option value="latest" <?= $sort_filter === 'latest' ? 'selected' : '' ?>>Latest</option>
                        <option value="oldest" <?= $sort_filter === 'oldest' ? 'selected' : '' ?>>Oldest</option>
                        <option value="popular" <?= $sort_filter === 'popular' ? 'selected' : '' ?>>Most Popular</option>
                        <option value="most-played" <?= $sort_filter === 'most-played' ? 'selected' : '' ?>>Most Played</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Tracks Grid -->
        <div class="tracks-grid">
            <?php if (empty($user_tracks)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="fas fa-music"></i>
                    </div>
                    <h3 class="empty-title">No tracks yet</h3>
                    <p class="empty-description">Start creating your first AI-generated music track!</p>
                    <a href="/create_music.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i>
                        Create Your First Track
                    </a>
                </div>
            <?php else: ?>
                <?php foreach ($user_tracks as $track): ?>
                    <div class="track-card-modern <?= !empty($track['badge']) ? 'has-badge' : '' ?>" 
                         data-track-id="<?= $track['id'] ?>" 
                         data-status="<?= $track['status'] ?>"
                         data-selected-variation="<?= $track['selected_variation'] ?? 0 ?>"
                         data-variations="<?= htmlspecialchars(json_encode($track['variations'] ?? [])) ?>">
                        
                        <?php if (!empty($track['badge'])): ?>
                            <div class="track-badge-modern"><?= $track['badge'] ?></div>
                        <?php endif; ?>

                        <!-- Track Header -->
                        <div class="track-header-modern">
                            <div class="artist-avatar-modern">
                                <?php if (!empty($user['profile_image'])): ?>
                                    <img src="<?= htmlspecialchars($user['profile_image']) ?>" 
                                         alt="<?= htmlspecialchars($user_name) ?>" 
                                         class="avatar-image"
                                         onerror="this.parentElement.innerHTML='<div class=\'avatar-fallback\'><?= substr(htmlspecialchars(ucwords(strtolower($user_name))), 0, 1) ?></div>'">
                                <?php else: ?>
                                    <div class="avatar-fallback"><?= substr(htmlspecialchars(ucwords(strtolower($user_name))), 0, 1) ?></div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="track-info-modern">
                                <h3 class="track-title-modern">
                                    <?php 
                                    $displayTitle = $track['title'];
                                    if (empty($displayTitle)) {
                                        if (!empty($track['prompt'])) {
                                            $displayTitle = substr($track['prompt'], 0, 50);
                                            if (strlen($track['prompt']) > 50) {
                                                $displayTitle .= '...';
                                            }
                                        } else {
                                            $displayTitle = 'Untitled Track';
                                        }
                                    }
                                    ?>
                                    <?= htmlspecialchars($displayTitle) ?>
                                </h3>
                                <p class="track-artist-modern">by <?= htmlspecialchars($user_name) ?></p>
                                
                                <div class="track-meta-modern">
                                    <span class="meta-item">
                                        <i class="fas fa-clock"></i>
                                        <?= floor($track['duration'] / 60) ?>m <?= $track['duration'] % 60 ?>s
                                    </span>
                                    <span class="meta-item">
                                        <i class="fas fa-calendar"></i>
                                        <?= date('M j, Y', strtotime($track['created_at'])) ?>
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- Track Prompt -->
                        <div class="track-prompt-modern">
                            <div class="prompt-label">Original Prompt:</div>
                            <div class="prompt-text"><?= htmlspecialchars(substr($track['prompt'], 0, 150)) ?>...</div>
                        </div>

                        <!-- Track Status -->
                        <div class="track-status-modern">
                            <?php if ($track['status'] === 'complete'): ?>
                                <div class="status-complete">
                                    <i class="fas fa-check-circle"></i>
                                    Complete
                                </div>
                            <?php elseif ($track['status'] === 'processing'): ?>
                                <div class="status-processing">
                                    <div class="processing-spinner"></div>
                                    Processing
                                    <button onclick="checkTrackStatus(<?= $track['id'] ?>)" class="refresh-btn-modern" title="Check Status">
                                        <i class="fas fa-sync-alt"></i>
                                    </button>
                                </div>
                            <?php elseif ($track['status'] === 'failed'): ?>
                                <?php
                                // Extract error message from metadata
                                $error_message = '';
                                $error_type = '';
                                if (!empty($track['metadata'])) {
                                    $metadata = json_decode($track['metadata'], true);
                                    if ($metadata && isset($metadata['msg'])) {
                                        $error_message = $metadata['msg'];
                                    }
                                    if ($metadata && isset($metadata['code'])) {
                                        $error_type = $metadata['code'] == 400 ? 'content_violation' : 'technical_error';
                                    }
                                }
                                ?>
                                <div class="status-failed">
                                    <i class="fas fa-exclamation-triangle"></i>
                                    Failed
                                </div>
                                <?php if ($error_message): ?>
                                    <div class="error-message-modern">
                                        <i class="fas fa-info-circle"></i>
                                        <?= htmlspecialchars($error_message) ?>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <!-- Track Actions -->
                        <div class="track-actions-modern">
                            <?php if ($track['status'] === 'complete'): ?>
                                <button class="action-btn primary" onclick="playTrackFromButton(this)" 
                                        data-audio-url="<?= htmlspecialchars($track['audio_url']) ?>" 
                                        data-title="<?= htmlspecialchars($displayTitle) ?>" 
                                        data-artist="<?= htmlspecialchars($user_name) ?>"
                                        title="Play Track">
                                    <i class="fas fa-play"></i>
                                    Play
                                </button>
                                
                                <button class="action-btn secondary" onclick="downloadTrack(<?= $track['id'] ?>)" title="Download Track">
                                    <i class="fas fa-download"></i>
                                    Download
                                </button>
                                
                                <?php if ($track['variation_count'] > 0): ?>
                                    <button class="action-btn secondary" onclick="showVariations(<?= $track['id'] ?>)" title="View Variations">
                                        <i class="fas fa-layer-group"></i>
                                        Variations
                                    </button>
                                <?php endif; ?>
                                
                                <button class="action-btn secondary" onclick="showLyrics(<?= $track['id'] ?>)" title="View Lyrics">
                                    <i class="fas fa-music"></i>
                                    Lyrics
                                </button>
                                
                            <?php elseif ($track['status'] === 'processing'): ?>
                                <div class="processing-actions">
                                    <button class="action-btn secondary" onclick="checkTrackStatus(<?= $track['id'] ?>)" title="Check Status">
                                        <i class="fas fa-sync-alt"></i>
                                        Check Status
                                    </button>
                                </div>
                                
                            <?php elseif ($track['status'] === 'failed'): ?>
                                <div class="failed-actions-modern">
                                    <button class="action-btn primary" onclick="retryTrack(<?= $track['id'] ?>)" title="Create a new version with the same prompt">
                                        <i class="fas fa-redo"></i>
                                        Retry
                                    </button>
                                    <button class="action-btn secondary" onclick="showFailureHelp(<?= $track['id'] ?>)" title="Why did this fail?">
                                        <i class="fas fa-question-circle"></i>
                                        Help
                                    </button>
                                    <button class="action-btn danger" onclick="deleteFailedTrack(<?= $track['id'] ?>)" title="Delete this failed track">
                                        <i class="fas fa-trash"></i>
                                        Delete
                                    </button>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modern CSS Styles -->
<style>
/* Modern Library Design */
.modern-library {
    min-height: 100vh;
    background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #0a0a0a 100%);
    position: relative;
    overflow-x: hidden;
}

/* Hero Section */
.library-hero {
    position: relative;
    padding: 6rem 0 4rem;
    text-align: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    overflow: hidden;
}

.hero-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem;
    position: relative;
    z-index: 2;
}

.hero-badge {
    display: inline-block;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 1rem 2rem;
    border-radius: 50px;
    font-size: 1.2rem;
    font-weight: 600;
    margin-bottom: 2rem;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.hero-title {
    font-size: 4rem;
    font-weight: 900;
    line-height: 1.1;
    margin-bottom: 1.5rem;
    background: linear-gradient(135deg, #667eea, #764ba2);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.hero-subtitle {
    font-size: 1.5rem;
    color: #a0aec0;
    max-width: 600px;
    margin: 0 auto;
    line-height: 1.6;
}

.hero-visual {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
}

.floating-elements {
    position: relative;
    height: 100%;
}

.floating-note {
    position: absolute;
    font-size: 3rem;
    color: rgba(102, 126, 234, 0.3);
    animation: float 6s ease-in-out infinite;
}

.floating-note:nth-child(1) {
    top: 20%;
    left: 10%;
    animation-delay: 0s;
}

.floating-note:nth-child(2) {
    top: 60%;
    right: 15%;
    animation-delay: 2s;
}

.floating-note:nth-child(3) {
    bottom: 30%;
    left: 20%;
    animation-delay: 4s;
}

@keyframes float {
    0%, 100% { transform: translateY(0px) rotate(0deg); }
    50% { transform: translateY(-20px) rotate(10deg); }
}

/* Stats Dashboard */
.stats-dashboard {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 2rem;
    max-width: 1200px;
    margin: -2rem auto 4rem;
    padding: 0 2rem;
    position: relative;
    z-index: 3;
}

.stat-card {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 20px;
    padding: 2rem;
    backdrop-filter: blur(20px);
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 1.5rem;
}

.stat-card:hover {
    transform: translateY(-5px);
    border-color: rgba(102, 126, 234, 0.3);
    box-shadow: 0 20px 60px rgba(102, 126, 234, 0.1);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 15px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: white;
}

.stat-icon.success {
    background: linear-gradient(135deg, #48bb78, #38a169);
}

.stat-icon.warning {
    background: linear-gradient(135deg, #ed8936, #dd6b20);
}

.stat-icon.error {
    background: linear-gradient(135deg, #f56565, #e53e3e);
}

.stat-content {
    flex: 1;
}

.stat-number {
    font-size: 2.5rem;
    font-weight: 900;
    color: white;
    margin-bottom: 0.5rem;
}

.stat-label {
    font-size: 1rem;
    color: #a0aec0;
    font-weight: 500;
}

/* Library Content */
.library-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem 4rem;
}

.content-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 3rem;
    gap: 2rem;
}

.header-left {
    flex: 1;
}

.section-title {
    font-size: 3rem;
    font-weight: 700;
    color: white;
    margin-bottom: 0.5rem;
}

.section-subtitle {
    font-size: 1.2rem;
    color: #a0aec0;
}

.header-controls {
    display: flex;
    gap: 1rem;
}

.filter-group {
    display: flex;
    gap: 1rem;
}

.modern-select {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    padding: 0.8rem 1.2rem;
    color: white;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
}

.modern-select:hover {
    border-color: rgba(102, 126, 234, 0.3);
    background: rgba(255, 255, 255, 0.08);
}

.modern-select:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.modern-select option {
    background: #1a1a1a;
    color: white;
}

/* Tracks Grid */
.tracks-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 2rem;
}

.track-card-modern {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 20px;
    padding: 2rem;
    backdrop-filter: blur(20px);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.track-card-modern:hover {
    transform: translateY(-5px);
    border-color: rgba(102, 126, 234, 0.3);
    box-shadow: 0 20px 60px rgba(102, 126, 234, 0.1);
}

.track-card-modern.has-badge {
    border-color: rgba(102, 126, 234, 0.3);
}

.track-badge-modern {
    position: absolute;
    top: 1rem;
    right: 1rem;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    z-index: 2;
}

/* Track Header */
.track-header-modern {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.artist-avatar-modern {
    width: 60px;
    height: 60px;
    border-radius: 15px;
    overflow: hidden;
    flex-shrink: 0;
}

.avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-fallback {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    font-weight: 700;
    color: white;
}

.track-info-modern {
    flex: 1;
    min-width: 0;
}

.track-title-modern {
    font-size: 1.3rem;
    font-weight: 700;
    color: white;
    margin-bottom: 0.3rem;
    line-height: 1.3;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.track-artist-modern {
    font-size: 1rem;
    color: #a0aec0;
    margin-bottom: 0.8rem;
}

.track-meta-modern {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 0.3rem;
    font-size: 0.9rem;
    color: #718096;
}

.meta-item i {
    font-size: 0.8rem;
}

/* Track Prompt */
.track-prompt-modern {
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    padding: 1rem;
    margin-bottom: 1.5rem;
}

.prompt-label {
    font-size: 0.9rem;
    color: #a0aec0;
    margin-bottom: 0.5rem;
    font-weight: 600;
}

.prompt-text {
    font-size: 0.9rem;
    color: #cbd5e0;
    line-height: 1.5;
}

/* Track Status */
.track-status-modern {
    margin-bottom: 1.5rem;
}

.status-complete {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #48bb78;
    font-weight: 600;
    font-size: 1rem;
}

.status-processing {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #ed8936;
    font-weight: 600;
    font-size: 1rem;
}

.processing-spinner {
    width: 16px;
    height: 16px;
    border: 2px solid rgba(237, 137, 54, 0.3);
    border-top: 2px solid #ed8936;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.status-failed {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #f56565;
    font-weight: 600;
    font-size: 1rem;
    margin-bottom: 0.5rem;
}

.error-message-modern {
    background: rgba(245, 101, 101, 0.1);
    border: 1px solid rgba(245, 101, 101, 0.3);
    border-radius: 8px;
    padding: 0.8rem;
    font-size: 0.9rem;
    color: #f56565;
    display: flex;
    align-items: flex-start;
    gap: 0.5rem;
    line-height: 1.4;
}

.refresh-btn-modern {
    background: none;
    border: none;
    color: #ed8936;
    cursor: pointer;
    padding: 0.3rem;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.refresh-btn-modern:hover {
    background: rgba(237, 137, 54, 0.1);
    color: #ed8936;
}

/* Track Actions */
.track-actions-modern {
    display: flex;
    gap: 0.8rem;
    flex-wrap: wrap;
}

.action-btn {
    padding: 0.8rem 1.2rem;
    border: none;
    border-radius: 10px;
    font-size: 0.9rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    text-decoration: none;
    flex: 1;
    min-width: 0;
    justify-content: center;
}

.action-btn.primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.action-btn.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.action-btn.secondary {
    background: rgba(255, 255, 255, 0.05);
    color: #a0aec0;
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.action-btn.secondary:hover {
    background: rgba(255, 255, 255, 0.1);
    color: white;
    border-color: rgba(255, 255, 255, 0.2);
}

.action-btn.danger {
    background: rgba(245, 101, 101, 0.1);
    color: #f56565;
    border: 1px solid rgba(245, 101, 101, 0.3);
}

.action-btn.danger:hover {
    background: rgba(245, 101, 101, 0.2);
    color: #f56565;
    border-color: rgba(245, 101, 101, 0.5);
}

.processing-actions,
.failed-actions-modern {
    display: flex;
    gap: 0.8rem;
    width: 100%;
}

/* Empty State */
.empty-state {
    grid-column: 1 / -1;
    text-align: center;
    padding: 4rem 2rem;
}

.empty-icon {
    font-size: 4rem;
    color: #667eea;
    margin-bottom: 2rem;
}

.empty-title {
    font-size: 2rem;
    color: white;
    margin-bottom: 1rem;
}

.empty-description {
    font-size: 1.1rem;
    color: #a0aec0;
    margin-bottom: 2rem;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 1rem 2rem;
    border: none;
    border-radius: 12px;
    font-size: 1rem;
    font-weight: 600;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

/* Responsive Design */
@media (max-width: 768px) {
    .hero-title {
        font-size: 2.5rem;
    }
    
    .section-title {
        font-size: 2rem;
    }
    
    .content-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-group {
        flex-direction: column;
    }
    
    .tracks-grid {
        grid-template-columns: 1fr;
    }
    
    .stats-dashboard {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .track-actions-modern {
        flex-direction: column;
    }
    
    .action-btn {
        width: 100%;
    }
}

@media (max-width: 480px) {
    .stats-dashboard {
        grid-template-columns: 1fr;
    }
    
    .hero-badge {
        padding: 0.8rem 1.5rem;
        font-size: 1rem;
    }
    
    .hero-title {
        font-size: 2rem;
    }
    
    .hero-subtitle {
        font-size: 1.2rem;
    }
}
</style>

<!-- Include the existing JavaScript -->
<script>
    // Global variables for variations
    let trackVariations = [];
    let currentTrackId = null;
    let selectedVariationIndex = null;
    
    // Check if global player is loaded
    window.addEventListener('load', function() {
        console.log('🎵 Modern library loaded');
        console.log('🎵 Global player status:', typeof window.globalPlayer !== 'undefined');
        console.log('🎵 Global player element exists:', !!document.getElementById('globalMusicPlayer'));
        console.log('🎵 playTrackWithGlobalPlayer function exists:', typeof window.playTrackWithGlobalPlayer === 'function');
        
        if (typeof window.globalPlayer === 'undefined') {
            console.error('🎵 Global player not loaded!');
            setTimeout(() => {
                if (typeof window.globalPlayer !== 'undefined') {
                    console.log('🎵 Global player loaded after delay');
                } else {
                    console.error('🎵 Global player still not available after delay');
                }
            }, 1000);
        } else {
            console.log('🎵 Global player loaded successfully');
            window.globalPlayer.showPlayer();
        }
        
        // Check if playTrackWithGlobalPlayer is available
        if (typeof window.playTrackWithGlobalPlayer === 'function') {
            console.log('🎵 playTrackWithGlobalPlayer function is available');
        } else {
            console.error('🎵 playTrackWithGlobalPlayer function is missing!');
        }
        
        // Start status checking for processing tracks
        checkProcessingTracks();
    });
    
    // Check processing tracks status periodically
    function checkProcessingTracks() {
        const processingTracks = document.querySelectorAll('.track-card-modern[data-status="processing"]');
        
        if (processingTracks.length > 0) {
            console.log('🎵 Found processing tracks, checking status...');
            
            // Show status indicator
            showStatusIndicator(`Checking ${processingTracks.length} processing track(s)...`);
            
            processingTracks.forEach(trackCard => {
                const trackId = trackCard.getAttribute('data-track-id');
                checkTrackStatus(trackId);
            });
            
            // Check again in 30 seconds
            setTimeout(checkProcessingTracks, 30000);
        } else {
            hideStatusIndicator();
        }
    }
    
    // Show status indicator
    function showStatusIndicator(message) {
        let indicator = document.getElementById('status-indicator');
        if (!indicator) {
            indicator = document.createElement('div');
            indicator.id = 'status-indicator';
            indicator.className = 'status-indicator';
            indicator.innerHTML = `
                <div class="status-indicator-content">
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>${message}</span>
                </div>
            `;
            document.body.appendChild(indicator);
        } else {
            indicator.querySelector('span').textContent = message;
        }
        indicator.style.display = 'block';
    }
    
    // Hide status indicator
    function hideStatusIndicator() {
        const indicator = document.getElementById('status-indicator');
        if (indicator) {
            indicator.style.display = 'none';
        }
    }
    
    // Check individual track status
    async function checkTrackStatus(trackId) {
        try {
            console.log(`🎵 Checking status for track ${trackId}...`);
            
            // Show loading state on the refresh button
            const refreshBtn = document.querySelector(`[onclick="checkTrackStatus(${trackId})"]`);
            if (refreshBtn) {
                const originalContent = refreshBtn.innerHTML;
                refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                refreshBtn.disabled = true;
            }
            
            const response = await fetch(`/api/check_track_status.php?track_id=${trackId}`);
            const result = await response.json();
            
            if (result.success && result.data) {
                const status = result.data.status;
                const trackCard = document.querySelector(`[data-track-id="${trackId}"]`);
                
                console.log(`🎵 Track ${trackId} status: ${status}`);
                
                if (trackCard && status !== 'processing') {
                    console.log(`🎵 Track ${trackId} status changed to: ${status}`);
                    
                    // Update track card status
                    trackCard.setAttribute('data-status', status);
                    
                    // Show success notification
                    if (typeof window.showNotification === 'function') {
                        window.showNotification(`Track status updated: ${status}`, 'success');
                    }
                    
                    // Refresh the page to show updated status
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else if (status === 'processing') {
                    // Show notification that it's still processing
                    if (typeof window.showNotification === 'function') {
                        window.showNotification('Track is still processing...', 'info');
                    }
                }
            } else {
                console.error('🎵 Track status check failed:', result.message);
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed to check track status', 'error');
                }
            }
        } catch (error) {
            console.error('🎵 Error checking track status:', error);
            
            // Show error notification if available
            if (typeof window.showNotification === 'function') {
                window.showNotification('Error checking track status', 'error');
            }
        } finally {
            // Restore refresh button
            if (refreshBtn) {
                refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i>';
                refreshBtn.disabled = false;
            }
        }
    }
    
    // Retry failed track
    async function retryTrack(trackId) {
        if (!confirm('🔄 Are you sure you want to retry this track? This will create a new version using your original prompt.')) {
            return;
        }
        
        try {
            console.log(`🎵 Retrying track ${trackId}...`);
            
            // Show loading state
            const retryBtn = document.querySelector(`[onclick="retryTrack(${trackId})"]`);
            if (retryBtn) {
                const originalContent = retryBtn.innerHTML;
                retryBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Retrying...';
                retryBtn.disabled = true;
            }
            
            const response = await fetch('/api_retry.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ track_id: trackId })
            });
            
            const result = await response.json();
            
            if (result.success) {
                console.log('🎵 Track retry initiated successfully');
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Track retry initiated! Check your library for the new version.', 'success');
                }
                
                // Refresh the page to show the new track
                setTimeout(() => {
                    window.location.reload();
                }, 2000);
                
            } else {
                console.error('🎵 Track retry failed:', result.error);
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed to retry track: ' + (result.error || 'Unknown error'), 'error');
                } else {
                    alert('❌ Failed to retry track: ' + (result.error || 'Unknown error'));
                }
            }
            
        } catch (error) {
            console.error('🎵 Error retrying track:', error);
            
            if (typeof window.showNotification === 'function') {
                window.showNotification('Network error retrying track. Please try again.', 'error');
            } else {
                alert('❌ Network error retrying track. Please check your connection and try again.');
            }
        } finally {
            // Restore retry button
            if (retryBtn) {
                retryBtn.innerHTML = '<i class="fas fa-redo"></i> Retry';
                retryBtn.disabled = false;
            }
        }
    }
    
    // Delete failed track
    async function deleteFailedTrack(trackId) {
        if (!confirm('🗑️ Are you sure you want to delete this failed track? This action cannot be undone.')) {
            return;
        }
        
        try {
            console.log(`🎵 Deleting failed track ${trackId}...`);
            
            // Show loading state
            const deleteBtn = document.querySelector(`[onclick="deleteFailedTrack(${trackId})"]`);
            if (deleteBtn) {
                const originalContent = deleteBtn.innerHTML;
                deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Deleting...';
                deleteBtn.disabled = true;
            }
            
            const response = await fetch('/api_delete_track.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ track_id: trackId })
            });
            
            const result = await response.json();
            
            if (result.success) {
                console.log('🎵 Failed track deleted successfully');
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed track deleted successfully!', 'success');
                }
                
                // Remove the track card from the DOM
                const trackCard = document.querySelector(`[data-track-id="${trackId}"]`);
                if (trackCard) {
                    trackCard.remove();
                } else {
                    // Fallback: refresh the page
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                }
                
            } else {
                console.error('🎵 Failed to delete track:', result.error);
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed to delete track: ' + (result.error || 'Unknown error'), 'error');
                } else {
                    alert('❌ Failed to delete track: ' + (result.error || 'Unknown error'));
                }
            }
            
        } catch (error) {
            console.error('🎵 Error deleting track:', error);
            
            if (typeof window.showNotification === 'function') {
                window.showNotification('Network error deleting track. Please try again.', 'error');
            } else {
                alert('❌ Network error deleting track. Please check your connection and try again.');
            }
        } finally {
            // Restore delete button
            if (deleteBtn) {
                deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Delete';
                deleteBtn.disabled = false;
            }
        }
    }
    
    // Show failure help modal
    function showFailureHelp(trackId) {
        const helpContent = `
            <div class="failure-help-modal">
                <h3>🤔 Why did my track fail?</h3>
                <p>Track generation can fail for several reasons:</p>
                <ul>
                    <li><strong>🔧 Technical Issues:</strong> API service temporarily unavailable</li>
                    <li><strong>📝 Content Violations:</strong> Prompt contains restricted content (artist names, copyrighted material)</li>
                    <li><strong>⏱️ Timeout:</strong> Generation took too long</li>
                    <li><strong>🎵 Audio Issues:</strong> Problems with audio processing</li>
                </ul>
                <p><strong>🚫 Content Restrictions:</strong></p>
                <ul>
                    <li><strong>Artist names:</strong> "gorillaz", "beatles", "michael jackson", etc.</li>
                    <li><strong>Copyrighted material:</strong> Song titles, lyrics, or melodies</li>
                    <li><strong>Explicit content:</strong> Inappropriate or offensive material</li>
                    <li><strong>Trademarks:</strong> Brand names, company names</li>
                </ul>
                <p><strong>💡 For Charles's case:</strong> The error "Song Description contained artist name: gorillaz" means you mentioned the band "Gorillaz" in your prompt. Try using generic descriptions like "electronic band" or "alternative rock group" instead.</p>
                <p><strong>💡 Tips for success:</strong></p>
                <ul>
                    <li>Keep prompts clear and specific</li>
                    <li>Avoid mentioning existing artists or bands</li>
                    <li>Use generic descriptions instead of specific names</li>
                    <li>Try different music styles or genres</li>
                    <li>Use the retry button to try again with a modified prompt</li>
                </ul>
                <div class="help-actions">
                    <button onclick="closeFailureHelp()" class="btn btn-primary">Got it!</button>
                    <button onclick="retryTrack(${trackId})" class="btn btn-secondary">Retry Now</button>
                    <button onclick="deleteFailedTrack(${trackId})" class="btn btn-danger">Delete Track</button>
                </div>
            </div>
        `;
        
        // Create modal
        const modal = document.createElement('div');
        modal.className = 'modal-overlay';
        modal.innerHTML = helpContent;
        document.body.appendChild(modal);
        
        // Add modal styles
        const style = document.createElement('style');
        style.textContent = `
            .modal-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.8);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                backdrop-filter: blur(10px);
            }
            .failure-help-modal {
                background: #1a1a1a;
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 12px;
                padding: 2rem;
                max-width: 500px;
                color: white;
                box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
            }
            .failure-help-modal h3 {
                color: #ffc107;
                margin-bottom: 1rem;
            }
            .failure-help-modal ul {
                margin: 1rem 0;
                padding-left: 1.5rem;
            }
            .failure-help-modal li {
                margin: 0.5rem 0;
            }
            .help-actions {
                display: flex;
                gap: 1rem;
                margin-top: 1.5rem;
            }
        `;
        document.head.appendChild(style);
    }
    
    // Close failure help modal
    function closeFailureHelp() {
        const modal = document.querySelector('.modal-overlay');
        if (modal) {
            modal.remove();
        }
    }

    // Use global player for track playback
    async function playTrack(audioUrl, title, artist) {
        console.log('🎵 Library playTrack called:', { audioUrl, title, artist });
        
        // Validate audio URL
        if (!audioUrl || audioUrl === 'NULL' || audioUrl === 'null') {
            console.error('🎵 INVALID AUDIO URL:', audioUrl);
            return;
        }
        
        // Use the global player function directly
        if (typeof window.playTrackWithGlobalPlayer === 'function') {
            console.log('🎵 Using playTrackWithGlobalPlayer function');
            try {
                window.playTrackWithGlobalPlayer(audioUrl, title, artist, <?= $_SESSION['user_id'] ?>);
                return;
            } catch (error) {
                console.error('🎵 playTrackWithGlobalPlayer failed:', error);
            }
        }
        
        // Fallback to direct global player
        if (typeof window.globalPlayer !== 'undefined' && typeof window.globalPlayer.playTrack === 'function') {
            console.log('🎵 Using direct global player fallback');
            try {
                window.globalPlayer.wasPlaying = true;
                window.globalPlayer.playTrack(audioUrl, title, artist, <?= $_SESSION['user_id'] ?>);
                return;
            } catch (error) {
                console.error('🎵 Direct global player failed:', error);
            }
        }
        
        console.error('🎵 No global player available for playback');
    }

    // Track play when play button is clicked
    function trackPlay(trackId) {
        fetch('/api_social.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'play', track_id: trackId })
        });
    }

    // Play track from button and record play
    async function playTrackFromButton(button) {
        const audioUrl = button.getAttribute('data-audio-url');
        const title = button.getAttribute('data-title');
        const artist = button.getAttribute('data-artist');
        const trackId = button.closest('.track-card-modern').getAttribute('data-track-id');
        
        console.log('🎵 Play button clicked:', { audioUrl, title, artist, trackId });
        
        // Validate audio URL
        if (!audioUrl || audioUrl === 'NULL' || audioUrl === 'null') {
            console.error('🎵 INVALID AUDIO URL:', audioUrl);
            return;
        }
        
        // Record the play
        trackPlay(trackId);
        
        // Play the track using the global player
        playTrack(audioUrl, title, artist);
    }

    // Download track function
    function downloadTrack(trackId) {
        window.open(`/api_download_track.php?track_id=${trackId}`, '_blank');
    }

    // Show variations modal
    function showVariations(trackId) {
        console.log('🎵 Showing variations for track:', trackId);
        
        // Get track data from PHP
        const trackCard = document.querySelector(`[data-track-id="${trackId}"]`);
        if (!trackCard) {
            console.error('🎵 Track card not found for track ID:', trackId);
            alert('Track not found. Please refresh the page and try again.');
            return;
        }
        
        console.log('🎵 Track card found:', trackCard);
        
        // Get variations data from PHP
        const variationsData = trackCard.getAttribute('data-variations');
        console.log('🎵 Raw variations data:', variationsData);
        
        if (!variationsData || variationsData === '[]') {
            console.error('🎵 No variations data found');
            alert('No variations available for this track.');
            return;
        }
        
        try {
            trackVariations = JSON.parse(variationsData);
            console.log('🎵 Parsed variations:', trackVariations);
            
            if (!Array.isArray(trackVariations) || trackVariations.length === 0) {
                console.error('🎵 No variations in array');
                alert('No variations available for this track.');
                return;
            }
            
            currentTrackId = trackId;
            
            // Get current selection
            const currentSelection = trackCard.getAttribute('data-selected-variation') || '0';
            selectedVariationIndex = parseInt(currentSelection);
            
            console.log('🎵 About to populate variations grid');
            
            // Populate variations grid
            populateVariationsGrid();
            
            console.log('🎵 About to show modal');
            
            // Show modal
            const modal = document.getElementById('variationsModal');
            if (!modal) {
                console.error('🎵 Variations modal not found');
                alert('Modal not found. Please refresh the page and try again.');
                return;
            }
            
            modal.classList.add('active');
            console.log('🎵 Modal should now be visible');
            
        } catch (error) {
            console.error('🎵 Error parsing variations data:', error);
            alert('Error loading variations. Please refresh the page and try again.');
        }
    }

    // Show lyrics modal
    function showLyrics(trackId) {
        // This would need to be implemented based on your lyrics system
        alert('Lyrics feature coming soon!');
    }

    // All other existing functions remain unchanged...
    // (Additional functions would be added here as needed)
</script>

<?php
// Include the existing modals and JavaScript functions
// This ensures all functionality is preserved
include 'includes/footer.php';
?> 

CasperSecurity Mini