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

require_once 'db_connect.php';

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

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

try {
    // 1. Get Student Info
    $std_info = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $std_info->execute([$student_id]);
    $student_data = $std_info->fetch(PDO::FETCH_ASSOC);

    $student_name = $student_data['name'] ?? 'Student';
    $is_trial = $student_data['is_trial'] ?? 0;
    $trial_attended = $student_data['trial_attended'] ?? 0;

    // 2. Fetch Enrolled Courses using Enrollments Table
    $enroll_query = $pdo->prepare("
        SELECT c.id as course_id, c.title as course_title 
        FROM enrollments e 
        JOIN courses c ON e.course_id = c.id 
        WHERE e.student_id = ? AND e.status = 'active'
    ");
    $enroll_query->execute([$student_id]);
    $enrolled_courses = $enroll_query->fetchAll(PDO::FETCH_ASSOC);

    // If multiple courses, show the first one as primary on Dashboard (or show count)
    $course_name = !empty($enrolled_courses) ? $enrolled_courses[0]['course_title'] : 'No Active Course';
    $primary_course_id = !empty($enrolled_courses) ? $enrolled_courses[0]['course_id'] : 0;
    if (count($enrolled_courses) > 1) {
        $course_name .= " (+" . (count($enrolled_courses) - 1) . " more)";
    }

    // 3. Count Exams & Calculate Avg Score (Dynamic)
    $total_exams = 0; $avg_score = 0;
    if ($pdo->query("SHOW TABLES LIKE 'exam_result'")->rowCount() > 0) {
        $exam_query = $pdo->prepare("SELECT COUNT(*), COALESCE(AVG(GREATEST(percentage, 0)), 0) FROM exam_result WHERE student_id = ?");
        $exam_query->execute([$student_id]);
        $exam_data = $exam_query->fetch(PDO::FETCH_NUM);
        $total_exams = $exam_data[0] ?? 0;
        $avg_score = round($exam_data[1] ?? 0, 2);
    }

    // 4. Count Published Notices (Dynamic)
    $notice_count = 0;
    if ($pdo->query("SHOW TABLES LIKE 'notices'")->rowCount() > 0) {
        $notice_count = $pdo->query("SELECT COUNT(*) FROM notices WHERE status = 'published'")->fetchColumn() ?: 0;
    }

    // 5. Today's Classes & Next Upcoming Class Logic
    $live_class_count = 0;
    $next_class = null;

    if (!empty($enrolled_courses)) {
        // Collect all course IDs the student is enrolled in
        $course_ids = array_column($enrolled_courses, 'course_id');
        $placeholders = implode(',', array_fill(0, count($course_ids), '?'));

        if ($pdo->query("SHOW TABLES LIKE 'live_classes'")->rowCount() > 0) {
            // Count today's classes for all enrolled courses
            $live_query = $pdo->prepare("SELECT COUNT(*) FROM live_classes WHERE course_id IN ($placeholders) AND class_date = CURDATE()");
            $live_query->execute($course_ids);
            $live_class_count = $live_query->fetchColumn() ?: 0;

            // Fetch NEXT Upcoming Live Class for all enrolled courses
            $class_query = $pdo->prepare("
                SELECT * FROM live_classes 
                WHERE course_id IN ($placeholders) AND CONCAT(class_date, ' ', class_time) >= NOW() 
                ORDER BY class_date ASC, class_time ASC LIMIT 1
            ");
            $class_query->execute($course_ids);
            $next_class = $class_query->fetch(PDO::FETCH_ASSOC);
        }
    }

    // 6. Dynamic Progress Percentage Calculation
    $progress_percentage = 0;
    if ($is_trial == 1) {
        $progress_percentage = min(100, round(($trial_attended / 3) * 100)); // Max 3 classes = 100% trial progress
    } else {
        $progress_percentage = min(100, ($total_exams * 5)); // Just a mock formula: 5% progress per exam taken
    }

} catch (PDOException $e) {
    die("Dashboard Error: " . $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.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }
    
    /* Profile Header */
    .profile-header { background: #fff; border-radius: 20px; padding: 20px 30px; box-shadow: 0 5px 20px rgba(0,0,0,0.02); display: flex; align-items: center; justify-content: space-between; border: 1px solid #f1f5f9; }
    .student-avatar { width: 60px; height: 60px; border-radius: 50%; background: rgba(212, 175, 55, 0.2); color: var(--accent); display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: bold; border: 2px solid var(--accent); }
    
    /* Hero Course Card */
    .hero-card { background: linear-gradient(135deg, #022c22 0%, var(--primary) 100%); border-radius: 24px; padding: 35px; color: white; position: relative; overflow: hidden; box-shadow: 0 15px 35px rgba(6, 78, 59, 0.15); }
    .hero-card::before { content: '\f5fc'; font-family: 'Font Awesome 5 Free'; font-weight: 900; position: absolute; right: -20px; bottom: -40px; font-size: 180px; color: rgba(255,255,255,0.04); transform: rotate(-15deg); }
    
    /* Progress Bar */
    .progress-glass { background: rgba(255,255,255,0.1); height: 8px; border-radius: 50px; overflow: hidden; margin-top: 15px; }
    .progress-fill { background: var(--accent); height: 100%; border-radius: 50px; position: relative; transition: width 1s ease-in-out; }
    
    /* Next Class Widget */
    .next-class-box { background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.2); border-radius: 16px; padding: 20px; }
    .live-pulse { display: inline-block; width: 10px; height: 10px; background: #ef4444; border-radius: 50%; margin-right: 8px; animation: pulseRed 1.5s 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); } }

    /* Action Buttons */
    .btn-glass { background: rgba(255,255,255,0.15); color: white; border: 1px solid rgba(255,255,255,0.3); border-radius: 12px; padding: 12px 25px; font-weight: 700; transition: 0.3s; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; }
    .btn-glass:hover { background: white; color: var(--primary); }
    .btn-gold { background: var(--accent); color: #022c22; border-radius: 12px; padding: 12px 25px; font-weight: 800; border: none; transition: 0.3s; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; box-shadow: 0 5px 15px rgba(212, 175, 55, 0.3); }
    .btn-gold:hover { background: #b49124; color: white; transform: translateY(-2px); }

    /* Mini Stats */
    .card-hover { transition: all 0.3s ease; border: 1px solid #e2e8f0; }
    .card-hover:hover { transform: translateY(-5px); box-shadow: 0 15px 35px rgba(0,0,0,0.08) !important; border-color: #cbd5e1; }
    .stat-icon { width: 55px; height: 55px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px; font-size: 22px; transition: 0.3s; }
    .card-hover:hover .stat-icon { transform: scale(1.1); }
    .bg-icon-primary { background: rgba(6, 78, 59, 0.1); color: var(--primary); }
    .bg-icon-accent { background: rgba(212, 175, 55, 0.15); color: var(--accent); }
    .bg-icon-danger { background: rgba(239, 68, 68, 0.1); color: #ef4444; }
    .bg-icon-dark { background: rgba(2, 44, 34, 0.1); color: var(--primary-dark); }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="profile-header mb-4 fade-up">
        <div class="d-flex align-items-center gap-3">
            <div class="student-avatar shadow-sm">
                <?= strtoupper(substr($student_name, 0, 1)) ?>
            </div>
            <div>
                <p class="text-muted fw-bold mb-0 small text-uppercase" style="letter-spacing: 1px;">Welcome Back</p>
                <h4 class="fw-bold text-dark mb-0"><?= htmlspecialchars($student_name) ?></h4>
            </div>
        </div>
        <div class="d-none d-md-block text-end">
            <span class="badge bg-light text-primary border px-3 py-2 rounded-pill fw-bold" style="font-size: 13px;">
                <i class="far fa-calendar-alt me-1"></i> <?= date('d M Y, l') ?>
            </span>
        </div>
    </div>

    <?php if($is_trial == 1): ?>
        <div class="alert alert-warning border-0 shadow-sm rounded-4 d-flex align-items-center p-3 mb-4 fade-up" style="border-left: 5px solid #f59e0b !important; background: #fffbeb; animation-delay: 0.05s;">
            <i class="fas fa-exclamation-circle fa-2x me-3" style="color: #f59e0b;"></i>
            <div>
                <h6 class="fw-bold mb-1" style="color: #b45309;">Free Trial Active (<?= htmlspecialchars($trial_attended) ?>/3 Classes Used)</h6>
                <p class="mb-0 small text-dark">You have <b><?= max(0, 3 - $trial_attended) ?></b> free classes remaining. Please pay the admission fee for full access.</p>
            </div>
            <a href="payment.php" class="btn btn-warning btn-sm ms-auto fw-bold rounded-pill px-3 shadow-sm">Pay Fee</a>
        </div>
    <?php endif; ?>

    <div class="hero-card mb-4 fade-up" style="animation-delay: 0.1s;">
        <div class="row align-items-center position-relative z-1">
            <div class="col-lg-7 mb-4 mb-lg-0">
                <div class="d-inline-block px-3 py-1 rounded-pill mb-3" style="background: rgba(212, 175, 55, 0.2); color: var(--accent); border: 1px solid rgba(212, 175, 55, 0.3); font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 1px;">
                    <i class="fas fa-book-reader me-1"></i> My Active Course
                </div>
                <h2 class="fw-bold mb-2" style="font-size: 1.8rem;"><?= htmlspecialchars($course_name) ?></h2>
                
                <div class="mt-4 pe-lg-5">
                    <div class="d-flex justify-content-between align-items-end mb-1">
                        <span class="fw-medium text-white-50 small">Course Progress</span>
                        <span class="fw-bold text-white fs-5"><?= $progress_percentage ?>%</span>
                    </div>
                    <div class="progress-glass">
                        <div class="progress-fill" style="width: <?= $progress_percentage ?>%;"></div>
                    </div>
                </div>
                
                <div class="mt-4 pt-2">
                    <a href="my_courses.php" class="btn-glass px-4">
                        Continue Learning <i class="fas fa-arrow-right ms-2"></i>
                    </a>
                </div>
            </div>

            <div class="col-lg-5">
                <div class="next-class-box">
                    <h6 class="text-white-50 fw-bold text-uppercase small mb-3" style="letter-spacing: 1px;">
                        <span class="live-pulse"></span> Next Upcoming Class
                    </h6>
                    
                    <?php if($next_class): ?>
                        <h5 class="fw-bold text-white mb-3" style="line-height: 1.4;">
                            <?= htmlspecialchars($next_class['topic']) ?>
                        </h5>
                        <div class="d-flex gap-3 mb-4">
                            <div class="text-white fw-medium">
                                <i class="far fa-calendar text-warning me-1"></i> <?= date('d M', strtotime($next_class['class_date'])) ?>
                            </div>
                            <div class="text-white fw-medium">
                                <i class="far fa-clock text-warning me-1"></i> <?= date('h:i A', strtotime($next_class['class_time'])) ?>
                            </div>
                        </div>
                        <a href="live_classes.php" class="btn-gold w-100">
                            Join Class Room <i class="fas fa-video ms-2"></i>
                        </a>
                    <?php else: ?>
                        <div class="text-center py-4 opacity-75">
                            <i class="fas fa-video-slash fa-2x mb-2 text-white-50"></i>
                            <p class="mb-0 small fw-medium">No upcoming classes scheduled yet.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 g-md-4 fade-up" style="animation-delay: 0.15s;">
        <div class="col-6 col-md-3">
            <div class="card card-hover border-0 shadow-sm rounded-4 p-4 text-center h-100" style="border-bottom: 4px solid var(--primary);">
                <div class="stat-icon bg-icon-primary"><i class="fas fa-file-signature"></i></div>
                <h3 class="fw-bold text-dark mb-1"><?= sprintf("%02d", $total_exams); ?></h3>
                <p class="text-muted fw-bold mb-0" style="font-size: 11px; text-transform: uppercase;">Exams Taken</p>
            </div>
        </div>

        <div class="col-6 col-md-3">
            <div class="card card-hover border-0 shadow-sm rounded-4 p-4 text-center h-100" style="border-bottom: 4px solid var(--accent);">
                <div class="stat-icon bg-icon-accent"><i class="fas fa-chart-pie"></i></div>
                <h3 class="fw-bold text-dark mb-1"><?= $avg_score; ?>%</h3>
                <p class="text-muted fw-bold mb-0" style="font-size: 11px; text-transform: uppercase;">Avg. Score</p>
            </div>
        </div>

        <div class="col-6 col-md-3">
            <div class="card card-hover border-0 shadow-sm rounded-4 p-4 text-center h-100" style="border-bottom: 4px solid #ef4444;">
                <div class="stat-icon bg-icon-danger"><i class="fas fa-video"></i></div>
                <h3 class="fw-bold text-dark mb-1"><?= sprintf("%02d", $live_class_count); ?></h3>
                <p class="text-muted fw-bold mb-0" style="font-size: 11px; text-transform: uppercase;">Today's Classes</p>
            </div>
        </div>

        <div class="col-6 col-md-3">
            <div class="card card-hover border-0 shadow-sm rounded-4 p-4 text-center h-100" style="border-bottom: 4px solid var(--primary-dark);">
                <div class="stat-icon bg-icon-dark"><i class="fas fa-bell"></i></div>
                <h3 class="fw-bold text-dark mb-1"><?= sprintf("%02d", $notice_count); ?></h3>
                <p class="text-muted fw-bold mb-0" style="font-size: 11px; text-transform: uppercase;">New Notices</p>
            </div>
        </div>
    </div>

</div>

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