<?php
// myclass.php - Handles display of enrolled lesson packs and lessons for a student.

require_once 'config.php';
require_login();

// Redirect admin users away from the student-specific page
if (is_admin()) {
    header('Location: dashboard.php');
    exit();
}

// --- Dynamic Variables from URL ---
$studentId = $_SESSION['user_id'];
$selectedPackId = $_GET['pack_id'] ?? null;
$selectedLessonId = $_GET['lesson_id'] ?? null;
$message = $_GET['msg'] ?? '';

// Fetch all granted lesson packs for the logged-in student.
// UPDATED: Removed pdf_count column as per user request.
$stmt = $pdo->prepare("
    SELECT
        lp.id,
        lp.title,
        lp.thumbnail_url,
        lp.description,
        (SELECT COUNT(id) FROM lessons WHERE pack_id = lp.id) as lesson_count
    FROM student_packs sp
    JOIN lesson_packs lp ON sp.pack_id = lp.id
    WHERE sp.student_id = ?
    ORDER BY lp.title
");
$stmt->execute([$studentId]);
$packs = $stmt->fetchAll();

$lessons = [];
$packTitle = 'My Classes';
$currentLesson = null;
$videoId = '';
$error = '';


if ($selectedPackId) {
    // 1. Check if student has access to the selected pack
    $stmt = $pdo->prepare("SELECT COUNT(id) FROM student_packs WHERE student_id = ? AND pack_id = ?");
    $stmt->execute([$studentId, $selectedPackId]);
    $hasAccess = $stmt->fetchColumn() > 0;

    if (!$hasAccess) {
        $message = 'Access denied to this lesson pack.';
        $selectedPackId = null;
    } else {
        // Fetch Pack Title
        $packStmt = $pdo->prepare("SELECT title FROM lesson_packs WHERE id = ?");
        $packStmt->execute([$selectedPackId]);
        $packTitle = $packStmt->fetchColumn() ?: 'Unknown Pack';

        if ($selectedLessonId) {
            // SCENARIO C: Load the specific lesson details for playback
            // UPDATED: Fetching is_live and zoom_link
            $stmt = $pdo->prepare("SELECT id, title, description, youtube_link, is_live, zoom_link FROM lessons WHERE id = ? AND pack_id = ?");
            $stmt->execute([$selectedLessonId, $selectedPackId]);
            $currentLesson = $stmt->fetch();

            if ($currentLesson) {
                // Check if it's a Live Class. If so, we don't need YouTube ID.
                if ((int)($currentLesson['is_live'] ?? 0) === 0) {
                    // Extract YouTube Video ID for recorded video
                    function get_youtube_id($url) {
                        $pattern = '/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?/';
                        if (preg_match($pattern, $url, $matches)) {
                            return $matches[1];
                        }
                        return '';
                    }

                    $videoId = get_youtube_id($currentLesson['youtube_link']);

                    if (empty($videoId) && !empty($currentLesson['youtube_link'])) {
                        $error = "Invalid YouTube link for this lesson.";
                        $currentLesson = null;
                    }
                    // If it is a recorded class but no link is present, $videoId will be empty, which is handled in player_content.php.

                }
                // If it's a live class, $videoId remains empty, which is fine.

            } else {
                $error = "Lesson not found in this pack.";
            }

        } else {
            // SCENARIO B: Fetch Lessons for the Selected Pack (Card view)
            // UPDATED: Fetching is_live and zoom_link
            $stmt = $pdo->prepare("SELECT id, title, description, youtube_link, thumbnail_path, is_live, zoom_link FROM lessons WHERE pack_id = ? ORDER BY id");
            $stmt->execute([$selectedPackId]);
            $lessons = $stmt->fetchAll();
        }
    }
}


// Ensure layout functions are available
require_once 'layouts.php';

// Render the page components
render_header('My Classes');
render_sidebar($_SESSION['user_role'], basename(__FILE__));

// Use the dynamic $packTitle for the topbar
if ($currentLesson) {
    // UPDATED: Topbar reflects type of lesson being viewed
    $lessonType = ((int)($currentLesson['is_live'] ?? 0) === 1) ? 'Live Session: ' : 'Playing: ';
    render_topbar($lessonType . htmlspecialchars($currentLesson['title']));
} else {
    render_topbar(htmlspecialchars($packTitle));
}
?>

<style>
/* Custom style for the pack/lesson image container - Adjusted for 16:9 video aspect ratio */
.pack-image-container {
    /* Enforces 16:9 aspect ratio (9 / 16 = 0.5625) */
    padding-top: 56.25%; 
    height: 0; 
    position: relative; 
    background-size: cover;
    background-position: center;
    overflow: hidden;
}
/* Utility to restrict text lines, used in card descriptions */
.line-clamp-3 {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    -webkit-line-clamp: 3;
}
.line-clamp-2 {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    -webkit-line-clamp: 2;
}

/* Added for Live Class Card Flair */
@keyframes pulse {
    0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); }
    70% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); }
    100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
}
.pulse {
    animation: pulse 2s infinite;
}

/* New style for the pack/lesson title section to separate it from the metadata */
.card-content-section {
    padding: 1rem 1.25rem; /* p-4 / p-5 equivalent */
}

/* New style for the metadata footer */
.card-metadata-footer {
    padding: 1rem 1.25rem; /* p-4 / p-5 equivalent */
    border-top: 1px solid #f3f4f6; /* border-gray-100 equivalent */
}
</style>

<div class="space-y-8">
    <?php if ($message || $error): ?>
        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-lg" role="alert"><?php echo htmlspecialchars($message . $error); ?></div>
    <?php endif; ?>

    <?php if (!$selectedPackId): ?>
        <!-- SCENARIO A: Show all Lesson Pack Cards -->
        <div class="flex items-center mb-6">
            <img src="class.gif" alt="Classes Icon" class="w-8 h-8 mr-3" />
            <h2 class="text-3xl font-extrabold text-gray-900">My Classes</h2>
        </div>

        <?php if ($packs): ?>
            <!-- Responsive Card Grid -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
                <?php foreach ($packs as $pack): ?>
                    <?php
                        $has_thumbnail = !empty($pack['thumbnail_url']);
                        // Set style: use background image URL if available, otherwise use a placeholder
                        $header_style = $has_thumbnail
                            ? "background-image: url('" . htmlspecialchars($pack['thumbnail_url']) . "');"
                            : "background-color: #f3f4f6; background-image: url('https://placehold.co/600x337/374151/ffffff?text=Lesson+Pack');"; // 16:9 placeholder 600x337.5

                        // Static badge for visual flair (since we don't have this data)
                        $is_special = (rand(0, 5) === 0); // Randomly make some packs "SPECIAL" for the visual effect
                        
                        // PDF Count logic removed as requested by the user.
                    ?>
                    <!-- Pack Card -->
                    <a href="?pack_id=<?php echo $pack['id']; ?>"
                       class="group block bg-white rounded-2xl shadow-xl hover:shadow-2xl transition-all duration-300 transform hover:scale-[1.02] overflow-hidden cursor-pointer border-4 border-transparent hover:border-red-500">

                        <!-- Visual Header Area (16:9 ratio) - Banner Style -->
                        <div class="pack-image-container relative flex flex-col justify-end"
                             style="<?php echo $header_style; ?>">
                            <!-- Optional gradient overlay for text visibility -->
                            <div class="absolute inset-0 bg-gradient-to-t from-black/20 via-black/0 to-black/0"></div>
                            
                            <?php if ($is_special): ?>
                                <!-- Red "SPECIAL" badge on the top right -->
                                <span class="absolute top-3 right-3 text-xs font-bold text-white px-3 py-1 rounded-full bg-red-600 shadow-xl z-10">SPECIAL</span>
                            <?php endif; ?>

                        </div>

                        <!-- Details Area (Title and Description) -->
                        <div class="card-content-section">
                            <!-- Pack Title and Active Status -->
                            <div class="flex items-center mb-2">
                                <h3 class="flex-grow text-lg font-extrabold text-gray-900 leading-snug line-clamp-2">
                                    <?php echo htmlspecialchars($pack['title']); ?>
                                </h3>
                                <span class="text-xs font-bold text-green-600 ml-3 flex items-center shrink-0">
                                    <!-- Active Icon -->
                                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                    Active
                                </span>
                            </div>

                            <?php if (!empty($pack['description'])): ?>
                            <!-- Dynamic Description: Shorter description for a cleaner look -->
                            <div class="text-xs text-gray-500 mb-2 whitespace-pre-wrap line-clamp-2">
                                <?php echo nl2br(htmlspecialchars($pack['description'])); ?>
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- Card Footer (Metadata) - New Look -->
                        <div class="card-metadata-footer text-xs font-medium text-gray-600">
                            <!-- Completion Status -->
                            <div class="flex items-center mb-2">
                                <svg class="w-4 h-4 text-green-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                Complete Lesson Pack
                            </div>

                            <!-- UPDATED: Removed the justify-between and only show the Video Count -->
                            <div class="flex justify-start items-center text-sm">
                                <!-- Video Count -->
                                <div class="flex items-center text-gray-600">
                                    <svg class="w-4 h-4 text-indigo-500 mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 6a2 2 0 012-2h12a2 2 0 012 2v8a2 2 0 01-2 2H4a2 2 0 01-2-2V6zm4.5 5a.5.5 0 00-.5.5v2a.5.5 0 00.771.419l1.5-1A.5.5 0 008 12.5v-2a.5.5 0 00-.771-.419l-1.5 1z"></path></svg>
                                    <span class="font-bold text-gray-800"><?php echo $pack['lesson_count'] ?? 0; ?> Videos</span>
                                </div>
                                <!-- PDF Count REMOVED -->
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <!-- Custom No Classes View (SCENARIO A) -->
            <div class="flex flex-col items-center justify-center min-h-[50vh] text-center p-8 bg-white rounded-2xl shadow-xl">
                <!-- Using the asset filename provided in the request context -->
                <img src="noclass.gif" alt="No Classes Icon" class="w-32 h-32 mx-auto mb-6 drop-shadow-lg" />
                <h3 class="text-2xl font-bold text-gray-800 mb-2">You haven't Activated any Classes yet!</h3>
                <p class="text-lg text-gray-600 mb-8">Start your learning journey now by selecting a class pack from the store.</p>
                <a href="buyclass.php" class="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-full shadow-lg text-white bg-indigo-600 hover:bg-indigo-700 transition duration-150 ease-in-out transform hover:scale-105">
                    Go to Lessons Store &rarr;
                </a>
            </div>
        <?php endif; ?>

    <?php elseif ($currentLesson): ?>
        <!-- SCENARIO C: Show the Embedded Video Player OR Live Class Link -->
        <?php 
            $is_live = (int)($currentLesson['is_live'] ?? 0);
            
            if ($is_live === 1) {
                // Live Class View: Display Zoom button
                $zoomUrl = htmlspecialchars($currentLesson['zoom_link']);
        ?>
                <!-- Live Class View Block -->
                <div class="flex flex-col items-center justify-center min-h-[70vh] text-center p-8 bg-white rounded-2xl shadow-xl border border-dashed border-red-300">
                    <svg class="w-20 h-20 text-red-600 mb-6 animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                    <h3 class="text-3xl font-extrabold text-red-700 mb-2">Live Class: <?php echo htmlspecialchars($currentLesson['title']); ?></h3>
                    <p class="text-lg text-gray-700 mb-8">This session is conducted live via Zoom. Click below to join the meeting now!</p>
                    <a href="<?php echo $zoomUrl; ?>" target="_blank" rel="noopener noreferrer" 
                        class="inline-flex items-center px-8 py-4 border border-transparent text-lg font-bold rounded-full shadow-xl text-white bg-red-600 hover:bg-red-700 transition duration-150 ease-in-out transform hover:scale-105 active:scale-95">
                        <svg class="w-6 h-6 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101M16.586 7.414l1.102 1.101a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path></svg>
                        Join Zoom Meeting
                    </a>
                    <a href="myclass.php?pack_id=<?php echo htmlspecialchars($selectedPackId); ?>" class="mt-4 text-indigo-500 hover:text-indigo-700 font-medium">
                        &larr; Back to Lessons
                    </a>
                </div>
        <?php
            } else {
                // Recorded Video View: Load player content
                // Note: player_content.php is not provided, assuming it handles video embedding
                include 'player_content.php';
            }
        ?>

    <?php else: ?>
        <!-- SCENARIO B: Show Lessons for the Selected Pack -->
        <div class="flex items-center justify-between pb-4 border-b border-gray-200 mb-6">
            <h2 class="text-3xl font-extrabold text-gray-900"><?php echo htmlspecialchars($packTitle); ?> Lessons</h2>
            <!-- Back button to return to the card grid view -->
            <a href="myclass.php" class="text-indigo-600 hover:text-indigo-800 font-medium flex items-center p-2 rounded-lg transition-colors bg-indigo-50 hover:bg-indigo-100">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
                </svg>
                Back to All Classes
            </a>
        </div>


        <?php if ($lessons): ?>
            <!-- Responsive Card Grid for Lessons (Same layout as packs) -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
                <?php foreach ($lessons as $lesson): ?>
                    <?php
                        // Check for Live Class status
                        $is_live = (int)($lesson['is_live'] ?? 0);

                        // CUSTOM THUMBNAIL LOGIC
                        if ($is_live) {
                            $image_url = 'https://placehold.co/600x337/DC2626/ffffff?text=LIVE+ZOOM+CLASS'; // Red 16:9 placeholder for live
                            $lesson_link = htmlspecialchars($lesson['zoom_link']); // Link directly to Zoom
                            $action_text = 'Open in Zoom';
                            $action_icon = '<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101M16.586 7.414l1.102 1.101a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path></svg>'; // Link/Chain icon
                            $badge_html = '<span class="text-xs font-bold text-white px-3 py-1 rounded-full bg-red-600 absolute top-3 right-3 shadow-lg pulse z-10">LIVE NOW</span>';
                            $target_attr = 'target="_blank" rel="noopener noreferrer"'; // Open Zoom link in new tab
                            $card_color = 'hover:border-red-500';
                        } else {
                            // Video Lesson Logic
                            $has_thumbnail = !empty($lesson['thumbnail_path']);
                            $image_url = $has_thumbnail
                                ? htmlspecialchars($lesson['thumbnail_path'])
                                : 'https://placehold.co/600x337/374151/ffffff?text=Video+Lesson'; // Grey 16:9 placeholder
                                
                            $lesson_link = "myclass.php?pack_id=" . htmlspecialchars($selectedPackId) . "&lesson_id=" . htmlspecialchars($lesson['id']);
                            $action_text = 'Watch Now';
                            $action_icon = '<svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10 12a2 2 0 100-4 2 2 0 000 4z"></path><path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd"></path></svg>';
                            $badge_html = '';
                            $target_attr = '';
                            $card_color = 'hover:border-indigo-500';
                        }
                    ?>
                    <!-- Lesson Card - Links to myclass.php with lesson_id -->
                    <a href="<?php echo $lesson_link; ?>" <?php echo $target_attr; ?>
                        class="group block bg-white rounded-2xl shadow-xl hover:shadow-2xl transition-all duration-300 transform hover:scale-[1.02] overflow-hidden cursor-pointer border-4 border-transparent <?php echo $card_color; ?>">

                        <!-- Visual Header Area (16:9 ratio via .pack-image-container) -->
                        <div class="pack-image-container relative flex flex-col justify-end"
                             style="background-image: url('<?php echo $image_url; ?>'); background-size: cover; background-position: center;">
                            
                            <?php echo $badge_html; // LIVE NOW badge or empty ?>

                            <!-- Play button overlay indicator -->
                            <?php if (!$is_live): ?>
                                <div class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-30 group-hover:bg-opacity-50 transition-opacity">
                                    <svg class="w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path></svg>
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Details Area (Title and Description) -->
                        <div class="card-content-section pt-4">
                            <!-- Lesson Title -->
                            <h3 class="text-lg font-extrabold text-gray-900 mb-1 leading-snug line-clamp-2">
                                <?php echo htmlspecialchars($lesson['title']); ?>
                            </h3>

                            <!-- Lesson Description -->
                            <p class="text-xs text-gray-500 line-clamp-2">
                                <?php echo htmlspecialchars($lesson['description']); ?>
                            </p>
                        </div>
                        
                        <!-- Card Footer (Action Indicator) - New Look -->
                        <div class="card-metadata-footer text-xs font-medium flex justify-between items-center">
                             <!-- Static Checkmark (mimicking the image layout) -->
                            <div class="flex items-center text-gray-600">
                                <svg class="w-4 h-4 text-green-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                Complete Lesson
                            </div>
                            
                            <!-- Action Link -->
                            <div class="flex items-center font-bold text-sm <?php echo $is_live ? 'text-red-600' : 'text-indigo-600'; ?>">
                                <?php echo $action_icon; ?>
                                <?php echo $action_text; ?>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <!-- Custom No Lessons View within Pack (SCENARIO B) -->
            <div class="flex flex-col items-center justify-center min-h-[30vh] text-center bg-white p-8 rounded-2xl shadow-xl border border-dashed border-indigo-300">
                <svg class="w-16 h-16 text-indigo-500 mb-4 animate-bounce" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.46 9.256 5 7.5 5S4.168 5.46 3 6.253v13C4.168 18.46 5.744 18 7.5 18s3.332.46 4.5 1.253m0-13C13.168 5.46 14.744 5 16.5 5s3.332.46 4.5 1.253v13C19.832 18.46 18.256 18 16.5 18s-3.332.46-4.5 1.253"></path></svg>
                <h3 class="text-xl font-bold text-gray-800 mb-1">More Lessons Coming Soon!</h3>
                <p class="text-md text-gray-600">The **<?php echo htmlspecialchars($packTitle); ?>** pack is active, but the instructor hasn't added lessons yet. Please check back later!</p>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<?php render_main_content_end(); ?>