<?php 
// Debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'db_connect.php';

// Include Header & Sidebar
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; }

try {
    // 1. Fetch all courses the student is enrolled in (Using Enrollments Table)
    $stmt = $pdo->prepare("
        SELECT 
            c.id as course_id, 
            c.title as course_title, 
            s.admission_type,
            e.status as enrollment_status
        FROM enrollments e 
        JOIN courses c ON e.course_id = c.id 
        JOIN students s ON e.student_id = s.id
        WHERE e.student_id = ?
    ");
    $stmt->execute([$student_id]);
    $enrolled_courses = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // ---------------------------------------------------------
    // ⚠️ DYNAMIC LOGIC (Simulation for Last Watched & Progress)
    // ---------------------------------------------------------
    // পরবর্তীতে যখন lesson_tracking টেবিল বানাবেন, তখন এই progress এবং last_watched ডাটাবেস থেকে আসবে
    $courses = [];
    if (!empty($enrolled_courses)) {
        foreach($enrolled_courses as $ec) {
            $courses[] = [
                'id' => $ec['course_id'],
                'title' => $ec['course_title'],
                'batch' => $ec['admission_type'] ?? 'Standard',
                'progress' => 65, // Example: 65% Completed (Will be dynamic later)
                'last_watched' => 'Module 2: Rules of Tajweed', // Example
                'status' => $ec['enrollment_status'] // 'active' or 'completed'
            ];
        }
    }
    
    // Add a dummy completed course for demonstration of the "Completed" tab
    // (আপনি চাইলে এটি মুছে দিতে পারেন যদি ডেমো না দেখাতে চান)
    $courses[] = [
        'id' => 99,
        'title' => 'Basic Arabic Alphabet (Free Crash Course)',
        'batch' => 'Free',
        'progress' => 100, 
        'last_watched' => 'Final Exam & Certificate',
        'status' => 'completed'
    ];

} catch (PDOException $e) {
    die("Error fetching courses: " . $e->getMessage());
}
?>

<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); } }

    /* Custom Tabs */
    .custom-tabs .nav-link { font-weight: 700; color: #64748b; border-radius: 50px; padding: 10px 25px; margin-right: 10px; transition: 0.3s; background: #fff; border: 1px solid #e2e8f0; }
    .custom-tabs .nav-link.active { background: var(--primary); color: #fff; border-color: var(--primary); box-shadow: 0 5px 15px rgba(6, 78, 59, 0.2); }

    /* Course Card */
    .course-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; overflow: hidden; box-shadow: 0 5px 20px rgba(0,0,0,0.02); transition: all 0.3s ease; display: flex; flex-direction: column; height: 100%; }
    .course-card:hover { transform: translateY(-5px); box-shadow: 0 15px 35px rgba(0,0,0,0.06); border-color: #cbd5e1; }
    
    .course-thumbnail { height: 160px; background: linear-gradient(135deg, var(--primary) 0%, #022c22 100%); position: relative; display: flex; align-items: center; justify-content: center; overflow: hidden; padding: 20px; text-align: center; }
    .course-thumbnail i.bg-icon { font-size: 100px; color: rgba(255,255,255,0.05); position: absolute; right: -15px; bottom: -20px; transform: rotate(-15deg); }
    .badge-batch { position: absolute; top: 15px; left: 15px; background: rgba(255,255,255,0.2); backdrop-filter: blur(5px); color: #fff; padding: 5px 12px; border-radius: 50px; font-size: 10px; font-weight: 800; text-transform: uppercase; border: 1px solid rgba(255,255,255,0.3); }

    /* Progress Bar */
    .progress-wrapper { background: #e2e8f0; border-radius: 50px; height: 8px; overflow: hidden; margin-top: 8px; }
    .progress-bar-fill { background: var(--accent); height: 100%; border-radius: 50px; transition: width 1s ease-in-out; }
    .progress-bar-fill.completed { background: #10b981; } /* Green for completed */

    /* Buttons */
    .btn-resume { background: var(--primary); color: #fff; border-radius: 12px; padding: 12px; font-weight: 700; border: none; transition: 0.3s; width: 100%; display: block; text-align: center; text-decoration: none; margin-top: auto; }
    .btn-resume:hover { background: #022c22; color: var(--accent); }
    
    .btn-review { background: #f1f5f9; color: var(--primary); border-radius: 12px; padding: 12px; font-weight: 700; border: 1px solid #cbd5e1; transition: 0.3s; width: 100%; display: block; text-align: center; text-decoration: none; margin-top: auto; }
    .btn-review:hover { background: #e2e8f0; }

    .last-watched { background: #f8fafc; border-left: 3px solid var(--accent); padding: 10px 15px; border-radius: 8px; font-size: 13px; color: #475569; margin: 15px 0; }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="mb-4 pb-2 fade-up">
        <h3 class="fw-bold text-dark mb-1"><i class="fas fa-laptop-code me-2" style="color: var(--accent);"></i> My Courses</h3>
        <p class="text-muted fw-semibold mb-0" style="font-size: 15px;">Pick up exactly where you left off.</p>
    </div>

    <ul class="nav nav-pills custom-tabs mb-4 fade-up" id="courseTabs" role="tablist" style="animation-delay: 0.1s;">
        <li class="nav-item" role="presentation">
            <button class="nav-link active shadow-sm" id="active-tab" data-bs-toggle="pill" data-bs-target="#active-courses" type="button" role="tab">
                <i class="fas fa-play-circle me-1"></i> Active Courses
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link shadow-sm" id="completed-tab" data-bs-toggle="pill" data-bs-target="#completed-courses" type="button" role="tab">
                <i class="fas fa-check-circle me-1"></i> Completed
            </button>
        </li>
    </ul>

    <div class="tab-content fade-up" id="courseTabsContent" style="animation-delay: 0.2s;">
        
        <div class="tab-pane fade show active" id="active-courses" role="tabpanel">
            <div class="row g-4">
                <?php 
                $has_active = false;
                foreach($courses as $c): 
                    if($c['status'] == 'active'): $has_active = true; 
                ?>
                    <div class="col-md-6 col-lg-4">
                        <div class="course-card">
                            <div class="course-thumbnail">
                                <span class="badge-batch"><?= htmlspecialchars($c['batch']) ?> Batch</span>
                                <i class="fas fa-book-reader bg-icon"></i>
                                <h5 class="text-white fw-bold mb-0 position-relative z-1" style="line-height: 1.4;">
                                    <?= htmlspecialchars($c['title']) ?>
                                </h5>
                            </div>
                            
                            <div class="p-4 d-flex flex-column flex-grow-1">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <small class="text-muted fw-bold text-uppercase" style="font-size: 10px;">Progress</small>
                                    <span class="fw-bold" style="color: var(--primary);"><?= $c['progress'] ?>%</span>
                                </div>
                                <div class="progress-wrapper">
                                    <div class="progress-bar-fill" style="width: <?= $c['progress'] ?>%;"></div>
                                </div>

                                <div class="last-watched">
                                    <div class="fw-bold text-dark" style="font-size: 11px; text-transform: uppercase;">Last Watched</div>
                                    <div class="fw-medium mt-1"><i class="far fa-play-circle me-1 text-primary"></i> <?= htmlspecialchars($c['last_watched']) ?></div>
                                </div>

                                <a href="watch_lesson.php?course_id=<?= $c['id'] ?>" class="btn-resume shadow-sm">
                                    Continue Learning <i class="fas fa-arrow-right ms-2"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endif; endforeach; ?>

                <?php if(!$has_active): ?>
                    <div class="col-12 text-center py-5">
                        <div class="p-5 bg-white rounded-4 border shadow-sm">
                            <i class="fas fa-box-open fa-3x text-muted mb-3 opacity-50"></i>
                            <h5 class="fw-bold text-dark">No Active Courses</h5>
                            <p class="text-muted mb-0">You are not enrolled in any active courses right now.</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="tab-pane fade" id="completed-courses" role="tabpanel">
            <div class="row g-4">
                <?php 
                $has_completed = false;
                foreach($courses as $c): 
                    if($c['status'] == 'completed'): $has_completed = true; 
                ?>
                    <div class="col-md-6 col-lg-4">
                        <div class="course-card" style="opacity: 0.9;">
                            <div class="course-thumbnail" style="background: linear-gradient(135deg, #475569 0%, #1e293b 100%);">
                                <span class="badge-batch bg-success border-success">Completed</span>
                                <i class="fas fa-award bg-icon"></i>
                                <h5 class="text-white fw-bold mb-0 position-relative z-1" style="line-height: 1.4;">
                                    <?= htmlspecialchars($c['title']) ?>
                                </h5>
                            </div>
                            
                            <div class="p-4 d-flex flex-column flex-grow-1">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <small class="text-muted fw-bold text-uppercase" style="font-size: 10px;">Progress</small>
                                    <span class="fw-bold text-success">100%</span>
                                </div>
                                <div class="progress-wrapper">
                                    <div class="progress-bar-fill completed" style="width: 100%;"></div>
                                </div>

                                <div class="text-center my-4">
                                    <i class="fas fa-medal fa-2x text-warning mb-2"></i>
                                    <h6 class="fw-bold text-dark mb-0">Course Completed!</h6>
                                    <small class="text-muted">Alhamdulillah, you have finished this course.</small>
                                </div>

                                <a href="watch_lesson.php?course_id=<?= $c['id'] ?>" class="btn-review">
                                    Review Materials <i class="fas fa-history ms-2"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endif; endforeach; ?>

                <?php if(!$has_completed): ?>
                    <div class="col-12 text-center py-5">
                        <div class="p-5 bg-white rounded-4 border shadow-sm">
                            <i class="fas fa-graduation-cap fa-3x text-muted mb-3 opacity-50"></i>
                            <p class="text-muted mb-0">You haven't completed any courses yet. Keep learning!</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

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