<?php
session_start();
require_once('../config.php');

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

include('../header/header.php');

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];
$username = $_SESSION['username'];
$my_courses = [];
$recent_notes = [];
/* =======================
   DASHBOARD STATISTICS
======================= */

if ($role == 'admin') {

    $total_students = $pdo->query("SELECT COUNT(*) FROM users WHERE role='student'")->fetchColumn();
    $total_courses  = $pdo->query("SELECT COUNT(*) FROM courses")->fetchColumn();
    $total_revenue  = $pdo->query("SELECT IFNULL(SUM(amount_paid),0) FROM payments")->fetchColumn();
    $total_arrears  = $pdo->query("SELECT IFNULL(SUM(total_fee - amount_paid),0) FROM payments")->fetchColumn();

} elseif ($role == 'lecturer') {

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM courses WHERE lecturer_id=?");
    $stmt->execute([$user_id]);
    $my_courses_count = $stmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT COUNT(DISTINCT e.student_id) FROM enrollments e
        JOIN courses c ON e.course_id = c.id
        WHERE c.lecturer_id = ? AND e.status = 'enrolled'
    ");
    $stmt->execute([$user_id]);
    $my_students_count = $stmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM submissions s
        JOIN assignments a ON s.assignment_id = a.id
        JOIN courses c ON a.course_id = c.id
        WHERE c.lecturer_id = ? AND s.status='submitted'
    ");
    $stmt->execute([$user_id]);
    $pending_submissions = $stmt->fetchColumn();

} else {

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE student_id=? AND status = 'enrolled'");
    $stmt->execute([$user_id]);
    $enrolled_count = $stmt->fetchColumn();

    $stmt = $pdo->prepare("SELECT IFNULL(SUM(total_fee - amount_paid),0) FROM payments WHERE student_id=?");
    $stmt->execute([$user_id]);
    $my_arrears = $stmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM assignments a
        JOIN enrollments e ON a.course_id = e.course_id
        WHERE e.student_id=? 
        AND e.status = 'enrolled'
        AND a.id NOT IN (
            SELECT assignment_id FROM submissions 
            WHERE student_id=? AND status IN ('submitted','graded')
        )
    ");
    $stmt->execute([$user_id, $user_id]);
    $pending_assignments = $stmt->fetchColumn();
}

/* =======================
   EXTRA DATA
======================= */

if ($role == 'lecturer') {

    $stmt = $pdo->prepare("
        SELECT c.course_name, AVG(e.progress) as avg_progress
        FROM courses c
        LEFT JOIN enrollments e ON c.id = e.course_id AND e.status = 'enrolled'
        WHERE c.lecturer_id = ?
        GROUP BY c.id
    ");
    $stmt->execute([$user_id]);
    $course_stats = $stmt->fetchAll();

}

if ($role == 'student') {

    try {
        $stmt = $pdo->prepare("
            SELECT c.course_name, e.progress
            FROM enrollments e
            JOIN courses c ON e.course_id = c.id
            WHERE e.student_id = ? AND e.status = 'enrolled'
        ");
        $stmt->execute([$user_id]);
        $my_courses = $stmt->fetchAll();

        $stmt = $pdo->prepare("
            SELECT n.*, c.course_name 
            FROM notes n
            JOIN courses c ON n.course_id = c.id
            JOIN enrollments e ON c.id = e.course_id
            WHERE e.student_id = ? AND e.status = 'enrolled'
            ORDER BY n.uploaded_at DESC
            LIMIT 5
        ");
        $stmt->execute([$user_id]);
        $recent_notes = $stmt->fetchAll();

    } catch (PDOException $e) {
        $my_courses = [];
        $recent_notes = [];
    }
}
?>

<div class="container-fluid py-4">

<!-- HEADER -->
<div class="mb-4">
    <h2 class="fw-bold">Welcome, <?= htmlspecialchars($username); ?></h2>
    <span class="badge bg-dark text-capitalize"><?= $role; ?></span>
</div>

<!-- =======================
     STATS CARDS
======================= -->
<div class="row g-4 mb-5">

<?php if ($role == 'admin'): ?>

<div class="col-md-3">
<div class="dash-card border-start border-4 border-primary">
<h6>Students</h6>
<h3><?= $total_students; ?></h3>
</div>
</div>

<div class="col-md-3">
<div class="dash-card border-start border-4 border-success">
<h6>Revenue</h6>
<h3>KES <?= number_format($total_revenue); ?></h3>
</div>
</div>

<div class="col-md-3">
<div class="dash-card border-start border-4 border-danger">
<h6>Arrears</h6>
<h3>KES <?= number_format($total_arrears); ?></h3>
</div>
</div>

<div class="col-md-3">
<div class="dash-card border-start border-4 border-info">
<h6>Courses</h6>
<h3><?= $total_courses; ?></h3>
</div>
</div>

<?php elseif ($role == 'lecturer'): ?>

<div class="col-md-4">
<a href="my_courses.php" class="text-decoration-none">
<div class="dash-card border-start border-4 border-primary">
<h6>My Courses</h6>
<h3><?= $my_courses_count; ?></h3>
</div>
</a>
</div>

<div class="col-md-4">
<a href="my_students.php" class="text-decoration-none">
<div class="dash-card border-start border-4 border-success">
<h6>My Students</h6>
<h3><?= $my_students_count; ?></h3>
</div>
</a>
</div>

<div class="col-md-4">
<div class="dash-card border-start border-4 border-warning">
<h6>Pending Tasks</h6>
<h3><?= $pending_submissions; ?></h3>
</div>
</div>

<?php else: ?>

<div class="col-md-4">
<div class="dash-card border-start border-4 border-primary">
<h6>Enrolled Courses</h6>
<h3><?= $enrolled_count; ?></h3>
</div>
</div>

<div class="col-md-4">
<div class="dash-card border-start border-4 border-danger">
<h6>Fee Arrears</h6>
<h3>KES <?= number_format($my_arrears); ?></h3>
</div>
</div>

<div class="col-md-4">
<div class="dash-card border-start border-4 border-info">
<h6>Pending Assignments</h6>
<h3><?= $pending_assignments; ?></h3>
</div>
</div>

<?php endif; ?>

</div>

<!-- =======================
     QUICK ACTIONS
======================= -->

<h4 class="mb-3">Quick Actions</h4>
<div class="row g-3 mb-5">

<?php if ($role == 'lecturer'): ?>

<div class="col-md-3">
<a href="add_course.php" class="btn btn-outline-primary w-100">Add Course</a>
</div>

<div class="col-md-3">
<a href="add_module.php" class="btn btn-outline-primary w-100">Add Module</a>
</div>

<div class="col-md-3">
<a href="add_unit.php" class="btn btn-outline-primary w-100">Add Unit</a>
</div>

<div class="col-md-3">
<a href="upload_notes.php" class="btn btn-outline-primary w-100">Upload Notes</a>
</div>

<?php elseif ($role == 'student'): ?>

<div class="col-md-4">
<a href="courses.php" class="btn btn-outline-primary w-100">Browse Courses</a>
</div>

<div class="col-md-4">
<a href="my_learning.php" class="btn btn-outline-primary w-100">My Learning</a>
</div>

<?php endif; ?>

</div>

<!-- =======================
     STUDENT SECTION
======================= -->

<?php if ($role == 'student'): ?>

<div class="row">

<div class="col-md-6">
<div class="card p-3 shadow-sm">
<h5>My Progress</h5>

<?php foreach($my_courses as $c): ?>
<p><?= $c['course_name']; ?> - <?= $c['progress']; ?>%</p>
<?php endforeach; ?>

</div>
</div>

<div class="col-md-6">
<div class="card p-3 shadow-sm">
<h5>Recent Notes</h5>

<ul>
<?php foreach($recent_notes as $n): ?>
<li>
<?= $n['file_name']; ?>
<a href="../uploads/<?= $n['file_path']; ?>" download>Download</a>
</li>
<?php endforeach; ?>
</ul>

</div>
</div>

</div>

<?php endif; ?>

</div>

<?php include('../footer/footer.php'); ?>
