<?php 
// Debugging (Remove in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka'); // Academy's base timezone

require_once 'db_connect.php';

// ==========================================
// 🛠️ AUTO-FIX DATABASE COLUMNS 
// ==========================================
try {
    $columns = $pdo->query("SHOW COLUMNS FROM live_classes")->fetchAll(PDO::FETCH_COLUMN);
    if(!in_array('duration', $columns)) { $pdo->exec("ALTER TABLE live_classes ADD COLUMN duration VARCHAR(50) DEFAULT '60 mins'"); }
    if(!in_array('platform', $columns)) { $pdo->exec("ALTER TABLE live_classes ADD COLUMN platform VARCHAR(50) DEFAULT 'Zoom'"); }
    if(!in_array('join_link', $columns)) { $pdo->exec("ALTER TABLE live_classes ADD COLUMN join_link VARCHAR(255) DEFAULT ''"); }
} catch (Exception $e) {}

include 'includes/user_header.php'; 
if(file_exists('includes/sidebar.php')) { include 'includes/sidebar.php'; } 

$student_id = $_SESSION['student_id'] ?? null;
if (!$student_id) { echo "<script>window.location.href='login.php';</script>"; exit; }

// ==========================================
// ⚙️ FETCH DYNAMIC LIVE CLASSES
// ==========================================
$upcoming_classes = [];

try {
    // 1. Get enrolled courses for this student
    $stmt = $pdo->prepare("SELECT course_id FROM enrollments WHERE student_id = ? AND status = 'active'");
    $stmt->execute([$student_id]);
    $course_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($course_ids)) {
        $placeholders = implode(',', array_fill(0, count($course_ids), '?'));
        
        // 2. Fetch classes that are upcoming or started recently (within last 2 hours)
        $query = "
            SELECT lc.*, c.title as course_name, t.name as teacher_name
            FROM live_classes lc
            JOIN courses c ON lc.course_id = c.id
            LEFT JOIN teachers t ON lc.teacher_id = t.id
            WHERE lc.course_id IN ($placeholders) 
              AND CONCAT(lc.class_date, ' ', lc.class_time) >= DATE_SUB(NOW(), INTERVAL 2 HOUR)
            ORDER BY lc.class_date ASC, lc.class_time ASC
        ";
        $stmt = $pdo->prepare($query);
        $stmt->execute($course_ids);
        $raw_classes = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($raw_classes as $cls) {
            $datetime_dhaka = $cls['class_date'] . ' ' . $cls['class_time'];
            $class_timestamp = strtotime($datetime_dhaka);
            $current_timestamp = time(); 
            
            // Class is "LIVE" if current time is within 15 mins before start, and 2 hours after start
            $is_live_now = ($current_timestamp >= ($class_timestamp - 900) && $current_timestamp <= ($class_timestamp + 7200));

            $upcoming_classes[] = [
                'id' => $cls['id'],
                'topic' => $cls['topic'] ?? 'Untitled Class',
                'course_name' => $cls['course_name'] ?? 'General',
                'teacher' => $cls['teacher_name'] ?? 'TBA',
                'datetime_dhaka' => $datetime_dhaka,
                'duration' => $cls['duration'] ?? '60 mins',
                'platform' => $cls['platform'] ?? 'Zoom',
                // SAFE FALLBACK: Check for join_link first, then meeting_link, else #
                'link' => $cls['join_link'] ?? $cls['meeting_link'] ?? '#',
                'is_live_now' => $is_live_now
            ];
        }
    }
} catch (PDOException $e) {
    $error = "Error loading classes.";
}
?>

<style>
    :root { --primary: #064e3b; --accent: #d4af37; --bg-color: #f8fafc; }
    .main-content { background-color: var(--bg-color); min-height: 100vh; padding-bottom: 50px; }
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    .class-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; padding: 25px; box-shadow: 0 5px 20px rgba(0,0,0,0.02); transition: 0.3s; position: relative; overflow: hidden; height: 100%; display: flex; flex-direction: column; }
    .class-card:hover { transform: translateY(-3px); box-shadow: 0 10px 30px rgba(0,0,0,0.06); border-color: var(--primary); }
    
    .class-card.live-active { border: 2px solid #ef4444; background: #fffaf9; }
    
    .badge-live { position: absolute; top: 15px; right: -30px; background: #ef4444; color: white; padding: 5px 35px; font-size: 11px; font-weight: 800; transform: rotate(45deg); letter-spacing: 1px; animation: pulseRed 2s infinite; }
    @keyframes pulseRed { 0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); } 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); } }

    .teacher-badge { background: rgba(212, 175, 55, 0.15); color: #9c7614; padding: 6px 15px; border-radius: 50px; font-size: 12px; font-weight: 700; display: inline-flex; align-items: center; margin-bottom: 15px; }
    
    .time-box { background: #f1f5f9; border-left: 3px solid var(--primary); padding: 12px 15px; border-radius: 8px; margin: 15px 0; }
    .local-time { color: var(--primary); font-weight: 800; font-size: 16px; }
    .dhaka-time { color: #64748b; font-size: 12px; font-weight: 600; margin-top: 3px; }

    .btn-join { background: #ef4444; color: white; border-radius: 10px; padding: 12px 20px; font-weight: 700; border: none; transition: 0.3s; width: 100%; display: inline-block; text-align: center; text-decoration: none; margin-top: auto; }
    .btn-join:hover { background: #dc2626; color: white; transform: translateY(-2px); box-shadow: 0 8px 20px rgba(239, 68, 68, 0.3); }
    
    .btn-wait { background: #e2e8f0; color: #64748b; border-radius: 10px; padding: 12px 20px; font-weight: 700; border: none; width: 100%; display: inline-block; text-align: center; text-decoration: none; margin-top: auto; pointer-events: none; }
</style>

<div class="main-content p-3 p-md-4">
    
    <?php if(isset($_GET['error']) && $_GET['error'] == 'limit_reached'): ?>
        <div class="alert alert-danger fw-bold border-0 shadow-sm rounded-3 fade-up border-start border-4 border-danger mb-4">
            <i class="fas fa-exclamation-triangle me-2"></i> Your 3 free trial classes limit has been reached! Please pay the admission fee to continue.
        </div>
    <?php endif; ?>

    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4 pb-2 fade-up">
        <div>
            <h3 class="fw-bold text-dark mb-1"><i class="fas fa-video me-2 text-danger"></i> Live Classes</h3>
            <p class="text-muted fw-semibold mb-0" style="font-size: 15px;">Join your scheduled interactive sessions.</p>
        </div>
        <div class="mt-3 mt-md-0">
            <div class="badge bg-white text-dark border p-2 px-3 shadow-sm rounded-pill fw-bold" style="font-size: 12px;">
                <i class="fas fa-globe-americas text-primary me-1"></i> Your Timezone: <span id="userTimezone" class="text-primary">Detecting...</span>
            </div>
        </div>
    </div>

    <div class="row g-4 fade-up" style="animation-delay: 0.1s;">
        <?php if(!empty($upcoming_classes)): foreach($upcoming_classes as $class): ?>
            <div class="col-md-6 col-lg-4">
                <div class="class-card <?= $class['is_live_now'] ? 'live-active' : '' ?>">
                    
                    <?php if($class['is_live_now']): ?>
                        <div class="badge-live">LIVE NOW</div>
                    <?php endif; ?>

                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="teacher-badge">
                            <i class="fas fa-chalkboard-teacher me-2"></i> <?= htmlspecialchars((string)$class['teacher']) ?>
                        </div>
                    </div>
                    
                    <h5 class="fw-bold text-dark mb-1" style="line-height: 1.4; font-size: 1.2rem;">
                        <?= htmlspecialchars((string)$class['topic']) ?>
                    </h5>
                    <span class="badge bg-light text-primary border mb-2"><i class="fas fa-book me-1"></i> <?= htmlspecialchars((string)$class['course_name']) ?></span>
                    
                    <div class="d-flex align-items-center gap-3 mt-2 mb-2 text-muted fw-medium small">
                        <div><i class="fas fa-desktop me-1 text-primary"></i> <?= htmlspecialchars((string)$class['platform']) ?></div>
                        <div><i class="fas fa-hourglass-half me-1 text-warning"></i> <?= htmlspecialchars((string)$class['duration']) ?></div>
                    </div>

                    <div class="time-box">
                        <div class="small text-uppercase fw-bold text-muted mb-1" style="font-size: 10px;">Class Schedule</div>
                        <div class="local-time js-local-time" data-dhaka-time="<?= $class['datetime_dhaka'] ?>">
                            <i class="fas fa-spinner fa-spin me-1"></i> Calculating your time...
                        </div>
                        <div class="dhaka-time">
                            BD Time: <?= date('d M Y, h:i A', strtotime($class['datetime_dhaka'])) ?>
                        </div>
                    </div>

                    <?php if($class['is_live_now']): ?>
                        <a href="join_class.php?id=<?= $class['id'] ?>" target="_blank" class="btn-join">
                            <i class="fas fa-video me-2"></i> Join Class Now
                        </a>
                    <?php else: ?>
                        <button class="btn-wait">
                            <i class="fas fa-lock me-2"></i> Link Unlocks 15 Mins Before
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; else: ?>
            <div class="col-12 text-center py-5">
                <div class="p-5 bg-white rounded-4 border shadow-sm">
                    <i class="fas fa-video-slash fa-3x text-muted mb-3 opacity-50"></i>
                    <h5 class="fw-bold text-dark">No Live Classes Scheduled</h5>
                    <p class="text-muted mb-0">There are no upcoming live classes for your enrolled courses right now.</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // 1. Detect user's timezone
        const userTZ = Intl.DateTimeFormat().resolvedOptions().timeZone;
        document.getElementById('userTimezone').innerText = userTZ;

        // 2. Convert all class times to user's local time
        const timeElements = document.querySelectorAll('.js-local-time');
        
        timeElements.forEach(function(el) {
            const dhakaTimeStr = el.getAttribute('data-dhaka-time');
            
            // Create a date object treating the string as GMT+6 (Dhaka)
            const isoString = dhakaTimeStr.replace(' ', 'T') + "+06:00";
            const classDate = new Date(isoString);

            // Format it to the user's local timezone nicely
            const options = { 
                weekday: 'short', 
                month: 'short', 
                day: 'numeric', 
                hour: '2-digit', 
                minute: '2-digit',
                timeZoneName: 'short'
            };
            
            const localTimeString = classDate.toLocaleString('en-US', options);
            el.innerHTML = '<i class="far fa-clock me-1"></i> ' + localTimeString;
        });
    });
</script>

<?php include 'includes/user_footer.php'; ?>