<?php
// dashboard.php - Complete Student Dashboard with Quiz, Files & Auto-Enrollment
require_once 'includes/config.php';
require_once 'includes/site-data.php';

if(!isset($_SESSION['user_id'])) {
    header('Location: auth.php');
    exit;
}

// Redirect admin/instructor
if(isset($_SESSION['user_role']) && ($_SESSION['user_role'] == 'admin' || $_SESSION['user_role'] == 'instructor')) {
    header('Location: admin/dashboard.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$user = getUserData($pdo, $user_id);

// Get enrolled courses with progress
$stmt = $pdo->prepare("
    SELECT c.*, e.enrolled_at, e.payment_status,
           (SELECT COUNT(*) FROM lessons WHERE course_id = c.id) as total_lessons,
           (SELECT COUNT(*) FROM lesson_progress lp JOIN lessons l ON lp.lesson_id = l.id WHERE lp.user_id = ? AND l.course_id = c.id AND lp.completed = 1) as completed_lessons,
           (SELECT COUNT(*) FROM quizzes q JOIN lessons l ON q.lesson_id = l.id WHERE l.course_id = c.id) as total_quizzes,
           (SELECT COUNT(*) FROM lessons WHERE course_id = c.id AND attachment_file IS NOT NULL AND attachment_file != '') as file_count
    FROM enrollments e 
    JOIN courses c ON e.course_id = c.id 
    WHERE e.user_id = ? AND e.payment_status IN ('completed', 'pending')
    AND (e.expires_at IS NULL OR e.expires_at >= CURDATE())
    ORDER BY e.enrolled_at DESC
");
$stmt->execute([$user_id, $user_id]);
$courses = $stmt->fetchAll();

// Get certificates
$certificates = $pdo->prepare("SELECT * FROM certificates WHERE user_id = ? ORDER BY created_at DESC");
$certificates->execute([$user_id]);
$certs = $certificates->fetchAll();
$cert_count = count($certs);

// Get pending count
$pending = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE user_id = ? AND payment_status = 'pending'");
$pending->execute([$user_id]);
$pending_count = $pending->fetchColumn();

// Completed lessons
$done = $pdo->prepare("SELECT COUNT(*) FROM lesson_progress WHERE user_id = ? AND completed = 1");
$done->execute([$user_id]);
$completed_lessons = $done->fetchColumn();

// Live today
$live = $pdo->query("SELECT COUNT(*) FROM live_classes WHERE DATE(scheduled_at) = CURDATE()")->fetchColumn();

// Reviews given
$rev = $pdo->prepare("SELECT COUNT(*) FROM reviews WHERE user_id = ?");
$rev->execute([$user_id]);
$review_count = $rev->fetchColumn();

// Dynamic settings
$st = $S['site_title'] ?? 'ONESBD LMS';
$lt = $S['logo_text'] ?? 'ONESBD LMS';
$li = $S['logo_icon'] ?? 'fa-graduation-cap';
$pc = $S['primary_color'] ?? '#6C5CE7';
$ui = $S['use_image_logo'] ?? '0';
$lim = $S['logo_image'] ?? '';
$ft = $S['footer_text'] ?? 'ONESBD LMS | সর্বস্বত্ব সংরক্ষিত';
$ph = $S['phone1'] ?? '';
$em = $S['email1'] ?? '';
$fb = $S['facebook_url'] ?? '#';
$yt = $S['youtube_url'] ?? '#';
$wa = $S['whatsapp_number'] ?? '';
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>ড্যাশবোর্ড - <?=htmlspecialchars($st)?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    <style>
        :root{--primary:<?=$pc?>;--g1:linear-gradient(135deg,<?=$pc?>,<?=$pc?>dd);--g2:linear-gradient(135deg,#f093fb,#f5576c);--g3:linear-gradient(135deg,#4facfe,#00f2fe);--g4:linear-gradient(135deg,#43e97b,#38f9d7);--g5:linear-gradient(135deg,#fa709a,#fee140);--dark:#1a1a2e;--shadow:0 4px 20px rgba(0,0,0,.06)}
        *{margin:0;padding:0;box-sizing:border-box}
        body{background:#f0f2f8;font-family:'Segoe UI','Hind Siliguri',Arial,sans-serif}
        
        .top-bar{background:var(--dark);color:white;padding:5px 0;font-size:.78rem}
        .top-bar a{color:rgba(255,255,255,.8);text-decoration:none;margin:0 8px}
        .navbar{background:rgba(255,255,255,.95);backdrop-filter:blur(15px);box-shadow:0 2px 20px rgba(0,0,0,.06);padding:12px 0;position:sticky;top:0;z-index:1000}
        .navbar-brand{font-weight:800;font-size:1.2rem;background:var(--g1);-webkit-background-clip:text;-webkit-text-fill-color:transparent;text-decoration:none;display:flex;align-items:center;gap:8px}
        .navbar-brand img{height:34px}
        .nav-link{color:#555;text-decoration:none;font-weight:500;margin:0 8px;font-size:.9rem}
        .container-fluid{max-width:1300px;padding:20px}
        
        .sidebar{background:white;border-radius:20px;padding:22px;box-shadow:var(--shadow);position:sticky;top:85px;max-height:82vh;overflow-y:auto}
        .sidebar-user{text-align:center;padding:18px;margin-bottom:15px;border-radius:14px;background:#f8f9ff}
        .sidebar-user img{width:60px;height:60px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);transition:.3s}
        .sidebar-user img:hover{transform:scale(1.08)}
        .sidebar-user h6{font-weight:700;margin:8px 0 2px;color:var(--dark)}
        .sidebar .nav-link{padding:10px 15px;border-radius:12px;margin-bottom:4px;color:#555;font-weight:500;transition:.3s;text-decoration:none;display:flex;align-items:center;gap:10px;font-size:.88rem}
        .sidebar .nav-link:hover,.sidebar .nav-link.active{background:var(--g1);color:white;transform:translateX(4px)}
        .sidebar .nav-link i{width:20px;text-align:center}
        .sidebar hr{margin:10px 0;opacity:.3}
        
        .welcome-banner{background:var(--g1);color:white;border-radius:20px;padding:28px 30px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;margin-bottom:20px;box-shadow:0 10px 40px rgba(108,92,231,.2)}
        .welcome-avatar{width:55px;height:55px;border-radius:50%;background:rgba(255,255,255,.3);display:flex;align-items:center;justify-content:center;font-size:1.5rem;font-weight:700}
        
        .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(100px,1fr));gap:12px;margin-bottom:20px}
        .stat-card{background:white;border-radius:16px;padding:18px 14px;text-align:center;box-shadow:0 2px 10px rgba(0,0,0,.04);transition:.3s}
        .stat-card:hover{transform:translateY(-5px);box-shadow:var(--shadow)}
        .stat-value{font-size:1.4rem;font-weight:800;color:var(--dark)}
        .stat-label{font-size:.72rem;color:#888}
        
        .quick-actions{background:white;border-radius:18px;padding:18px 20px;box-shadow:0 2px 10px rgba(0,0,0,.04);margin-bottom:20px}
        .quick-actions h6{font-weight:700;margin-bottom:12px}
        .action-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 18px;border-radius:50px;font-weight:600;font-size:.82rem;text-decoration:none;transition:.3s;color:white;margin:3px}
        .action-btn:hover{transform:translateY(-2px);box-shadow:0 8px 20px rgba(0,0,0,.15);color:white}
        
        .main-card{background:white;border-radius:18px;padding:22px;box-shadow:0 2px 10px rgba(0,0,0,.04);margin-bottom:18px}
        .section-title{font-weight:700;font-size:1.05rem;margin-bottom:15px;display:flex;justify-content:space-between;align-items:center}
        
        .course-card{border:1px solid #eee;border-radius:14px;padding:16px 18px;margin-bottom:10px;transition:.3s;background:white}
        .course-card:hover{box-shadow:var(--shadow);border-color:rgba(108,92,231,.15)}
        .course-card.pending{border-left:4px solid #ffc107;background:#fffef5}
        .progress{height:7px;border-radius:10px;margin:8px 0;background:#e8eaef}
        .progress-bar{background:var(--g1);border-radius:10px}
        .progress-bar.done{background:var(--g4)}
        
        .cert-card{background:white;border-radius:12px;padding:15px 18px;margin-bottom:8px;border-left:4px solid var(--g4);transition:.3s;display:flex;justify-content:space-between;align-items:center}
        .cert-card:hover{box-shadow:var(--shadow)}
        
        .btn-sm-round{padding:6px 16px;border-radius:50px;font-size:.8rem;font-weight:600;text-decoration:none;transition:.3s;display:inline-flex;align-items:center;gap:5px}
        .btn-purple{background:var(--g1);color:white}.btn-purple:hover{transform:translateY(-2px);box-shadow:0 8px 20px rgba(108,92,231,.3);color:white}
        .btn-green{background:var(--g4);color:#0d4d2b}.btn-green:hover{transform:translateY(-2px)}
        .btn-blue{background:var(--g3);color:white}
        .btn-orange{background:#ffc107;color:#333}
        .btn-outline-sm{border:2px solid var(--primary);color:var(--primary);border-radius:50px;padding:5px 14px;font-size:.78rem;font-weight:600;text-decoration:none}
        
        .badge-status{padding:3px 10px;border-radius:20px;font-size:.7rem;font-weight:600}
        .empty-state{text-align:center;padding:30px;color:#888}
        
        footer{background:var(--dark);color:white;text-align:center;padding:25px;margin-top:40px}
        footer a{color:rgba(255,255,255,.7);text-decoration:none;margin:0 10px}
        
        @media(max-width:991px){.sidebar{position:static;max-height:none;margin-bottom:20px}.stats-grid{grid-template-columns:repeat(3,1fr)}}
        @media(max-width:576px){.stats-grid{grid-template-columns:repeat(2,1fr)}}
    </style>
</head>
<body>

<div class="top-bar"><div class="container-fluid" style="display:flex;justify-content:space-between">
    <span><?php if($ph):?>📞 <?=htmlspecialchars($ph)?><?php endif;?> <?php if($em):?>| ✉️ <?=htmlspecialchars($em)?><?php endif;?></span>
    <span><?php if($fb):?><a href="<?=$fb?>"><i class="fab fa-facebook"></i></a><?php endif;?><?php if($yt):?><a href="<?=$yt?>"><i class="fab fa-youtube"></i></a><?php endif;?></span>
</div></div>

<nav class="navbar"><div class="container-fluid" style="display:flex;justify-content:space-between;align-items:center">
    <a href="index.php" class="navbar-brand"><?php if($ui=='1'&&!empty($lim)&&file_exists('uploads/logo/'.$lim)):?><img src="uploads/logo/<?=$lim?>" alt="<?=htmlspecialchars($st)?>"><?php else:?><i class="fas <?=$li?> me-2"></i><?=htmlspecialchars($lt)?><?php endif;?></a>
    <div style="display:flex;gap:12px"><a href="index.php" class="nav-link">হোম</a><a href="logout.php" class="btn-sm-round" style="background:#ff4757;color:white">লগআউট</a></div>
</div></nav>

<div class="container-fluid py-2"><div class="row">

<!-- SIDEBAR -->
<div class="col-lg-3 mb-3"><div class="sidebar">
    <div class="sidebar-user">
        <img src="uploads/avatars/<?=$user['avatar']?:'default-avatar.png'?>" onerror="this.src='https://ui-avatars.com/api/?name=<?=urlencode($user['full_name'])?>&background=<?=str_replace('#','',$pc)?>&color=fff&size=60'">
        <h6><?=htmlspecialchars($user['full_name'])?></h6>
        <small>🎓 শিক্ষার্থী</small>
    </div>
    <a href="dashboard.php" class="nav-link active"><i class="fas fa-th-large"></i> ড্যাশবোর্ড</a>
    <a href="courses.php" class="nav-link"><i class="fas fa-book"></i> কোর্স ব্রাউজ</a>
    <a href="my-courses.php" class="nav-link"><i class="fas fa-play-circle"></i> আমার কোর্স</a>
    <!-- NEW: Quiz & Files Links -->
    <a href="my-quizzes.php" class="nav-link"><i class="fas fa-question-circle"></i> কুইজ ও ফাইল</a>
    <a href="my-certificates.php" class="nav-link"><i class="fas fa-certificate"></i> সার্টিফিকেট <span class="badge bg-success ms-auto"><?=$cert_count?></span></a>
    <a href="live-classes.php" class="nav-link"><i class="fas fa-video"></i> লাইভ ক্লাস</a>
    <hr>
    <a href="packages.php" class="nav-link"><i class="fas fa-box"></i> প্যাকেজ কিনুন</a>
    <a href="profile.php" class="nav-link"><i class="fas fa-user-edit"></i> প্রোফাইল এডিট</a>
    <a href="contact.php" class="nav-link"><i class="fas fa-headset"></i> সাপোর্ট</a>
</div></div>

<!-- MAIN -->
<div class="col-lg-9">

    <!-- Welcome -->
    <div class="welcome-banner" data-aos="fade-down"><div><h4>👋 স্বাগতম, <?=htmlspecialchars($user['full_name'])?>!</h4><p style="opacity:.9;margin:0">আপনার লার্নিং জার্নি চালিয়ে যান</p></div><div class="welcome-avatar"><?=mb_substr($user['full_name'],0,1)?></div></div>

    <!-- Stats -->
    <div class="stats-grid" data-aos="fade-up">
        <div class="stat-card"><div class="stat-value" style="color:#667eea"><?=count($courses)?></div><div class="stat-label">এনরোল্ড</div></div>
        <div class="stat-card"><div class="stat-value" style="color:#11998e"><?=$completed_lessons?></div><div class="stat-label">লেসন</div></div>
        <div class="stat-card"><div class="stat-value" style="color:#f5576c"><?=$cert_count?></div><div class="stat-label">সার্টিফিকেট</div></div>
        <div class="stat-card"><div class="stat-value" style="color:#e67e22"><?=$pending_count?></div><div class="stat-label">পেন্ডিং</div></div>
        <div class="stat-card"><div class="stat-value" style="color:#4facfe"><?=$review_count?></div><div class="stat-label">রিভিউ</div></div>
    </div>

    <!-- Quick Actions -->
    <div class="quick-actions" data-aos="fade-up">
        <h6>⚡ কুইক অ্যাকশন</h6>
        <a href="courses.php" class="action-btn" style="background:var(--g1)"><i class="fas fa-search"></i> কোর্স খুঁজুন</a>
        <a href="my-quizzes.php" class="action-btn" style="background:var(--g2)"><i class="fas fa-question-circle"></i> কুইজ দিন</a>
        <a href="my-certificates.php" class="action-btn" style="background:var(--g4);color:#0d4d2b"><i class="fas fa-file-alt"></i> ফাইল দেখুন</a>
        <a href="live-classes.php" class="action-btn" style="background:var(--g3)"><i class="fas fa-video"></i> লাইভ ক্লাস</a>
        <a href="packages.php" class="action-btn" style="background:var(--g5);color:#333"><i class="fas fa-box"></i> প্যাকেজ</a>
    </div>

    <!-- My Courses -->
    <div class="main-card" data-aos="fade-up">
        <div class="section-title">📚 আমার কোর্স <a href="my-courses.php" class="btn-outline-sm">সব দেখুন →</a></div>
        <?php if(count($courses)>0): ?>
            <?php foreach(array_slice($courses,0,5) as $c): 
                $percent = $c['total_lessons']>0 ? round(($c['completed_lessons']/$c['total_lessons'])*100) : 0;
                $fullyDone = ($c['total_lessons']>0 && $c['completed_lessons']==$c['total_lessons']);
                $is_pending = ($c['payment_status'] == 'pending');
                $hasCert = false;
                if($fullyDone){$cc=$pdo->prepare("SELECT id FROM certificates WHERE user_id=? AND course_id=?");$cc->execute([$user_id,$c['id']]);$hasCert=($cc->fetch()!=false);}
                $fl=$pdo->prepare("SELECT id FROM lessons WHERE course_id=? ORDER BY order_number LIMIT 1");$fl->execute([$c['id']]);$first=$fl->fetch();
            ?>
                <div class="course-card <?=$is_pending?'pending':''?>">
                    <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
                        <div>
                            <strong><?=htmlspecialchars(mb_substr($c['title_bn'],0,35))?></strong>
                            <br><small class="text-muted"><?=date('d M Y',strtotime($c['enrolled_at']))?> | <?=$c['level']=='beginner'?'🟢':($c['level']=='intermediate'?'🟡':'🔴')?></small>
                        </div>
                        <div class="d-flex gap-1 flex-wrap">
                            <?php if($is_pending):?><span class="badge-status bg-warning text-dark">⏳ অনুমোদন অপেক্ষায়</span><?php endif;?>
                            <?php if($fullyDone && $hasCert):?><span class="badge-status" style="background:#fff8e1;color:#f57f17">🏆 সার্টিফাইড</span><?php elseif($fullyDone):?><span class="badge-status bg-success text-white">✅ সম্পন্ন</span><?php endif;?>
                            <?php if($c['total_quizzes']>0):?><span class="badge-status bg-info text-white">❓ <?=$c['total_quizzes']?> কুইজ</span><?php endif;?>
                            <?php if($c['file_count']>0):?><span class="badge-status bg-secondary text-white">📁 <?=$c['file_count']?> ফাইল</span><?php endif;?>
                        </div>
                    </div>
                    <?php if(!$is_pending):?>
                        <div class="progress"><div class="progress-bar <?=$fullyDone?'done':''?>" style="width:<?=$percent?>%"></div></div>
                        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <small><?=$c['completed_lessons']?>/<?=$c['total_lessons']?> (<?=$percent?>%)</small>
                            <div class="d-flex gap-1">
                                <?php if($first):?><a href="lesson.php?id=<?=$first['id']?>&course=<?=$c['id']?>" class="btn-sm-round btn-purple"><?=$fullyDone?'👁️ রিভিউ':($percent>0?'▶️ চালান':'🚀 শুরু')?></a><?php endif;?>
                                <?php if($c['total_quizzes']>0):?><a href="my-quizzes.php?course=<?=$c['id']?>" class="btn-sm-round btn-blue"><i class="fas fa-question-circle"></i> কুইজ</a><?php endif;?>
                                <?php if($c['file_count']>0):?><a href="my-certificates.php?tab=files&course=<?=$c['id']?>" class="btn-sm-round" style="background:#6c757d;color:white"><i class="fas fa-folder"></i> ফাইল</a><?php endif;?>
                            </div>
                        </div>
                    <?php else:?>
                        <div class="mt-2"><small class="text-warning"><i class="fas fa-info-circle me-1"></i> পেমেন্ট/অনুমোদন সম্পন্ন হলে কোর্স শুরু করতে পারবেন</small></div>
                    <?php endif;?>
                </div>
            <?php endforeach;?>
        <?php else:?>
            <div class="empty-state"><i class="fas fa-book-open" style="font-size:2.5rem;opacity:.3"></i><p>কোন কোর্স এনরোল করা নেই</p><a href="courses.php" class="btn-sm-round btn-purple">কোর্স ব্রাউজ করুন</a></div>
        <?php endif;?>
    </div>

    <!-- Certificates -->
    <?php if($cert_count>0):?>
    <div class="main-card" data-aos="fade-up">
        <div class="section-title">🏆 সাম্প্রতিক সার্টিফিকেট <a href="my-certificates.php" class="btn-outline-sm">সব দেখুন →</a></div>
        <?php foreach(array_slice($certs,0,3) as $cert):?>
            <div class="cert-card">
                <div><strong><?=htmlspecialchars(mb_substr($cert['course_name'],0,30))?></strong><br><small>📅 <?=date('d M Y',strtotime($cert['completion_date']))?> | 🎯 <?=$cert['grade']?></small></div>
                <a href="admin/view-certificate.php?id=<?=$cert['id']?>" target="_blank" class="btn-sm-round btn-green"><i class="fas fa-eye"></i> দেখুন</a>
            </div>
        <?php endforeach;?>
    </div>
    <?php endif;?>
</div></div></div>

<footer><p>&copy; <?=date('Y')?> <?=htmlspecialchars($ft)?></p>
    <div><?php if($fb):?><a href="<?=$fb?>"><i class="fab fa-facebook fa-lg"></i></a><?php endif;?><?php if($yt):?><a href="<?=$yt?>"><i class="fab fa-youtube fa-lg"></i></a><?php endif;?><?php if($wa):?><a href="https://wa.me/<?=$wa?>"><i class="fab fa-whatsapp fa-lg"></i></a><?php endif;?></div>
</footer>

<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<script>AOS.init({duration:700,once:true});</script>
</body>
</html>