<?php
// dashboard.php
// This page serves as the user's main dashboard, dynamically displaying courses
// and offering relevant actions based on the user's role.

// Ensure session is started only once.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not logged in. This is a crucial security check.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: index.php?page=login");
    exit();
}

// Include database connection.
require_once 'config/database.php';

// Retrieve user details from session
$username = $_SESSION['username'] ?? 'Guest';
$user_role = $_SESSION['user_role'] ?? 'student'; // Default to student if role not set
$user_id = $_SESSION['user_id'] ?? null; // Get the logged-in user's ID

$courses = []; // Array to hold course data fetched from the database.
$pending_enrollments = []; // Array to hold pending enrollment requests for admin/instructor.
$message = ''; // Message for feedback (e.g., no courses found).
$is_error = false; // Flag to determine if the message is an error.

try {
    // --- Fetch Courses based on User Role ---
    $sql_courses = "
        SELECT
            c.id,
            c.course_name,
            c.description,
            c.fees,
            c.duration,
            c.start_date,
            u.full_name AS instructor_name,
            u.id AS instructor_id
        FROM courses c
        JOIN users u ON c.instructor_id = u.id
    ";
    $params_courses = [];

    if ($user_role === 'instructor') {
        $sql_courses .= " WHERE c.instructor_id = ?";
        $params_courses[] = $user_id;
    }
    $sql_courses .= " ORDER BY c.start_date DESC, c.course_name ASC";

    $stmt_courses = $pdo->prepare($sql_courses);
    $stmt_courses->execute($params_courses);
    $courses = $stmt_courses->fetchAll(PDO::FETCH_ASSOC);

    if (empty($courses)) {
        if ($user_role === 'instructor') {
            $message = "You have not created or been assigned any courses yet. Use the 'Create New Course' button to add one!";
        } else {
            $message = "No courses are currently available in the system. Please check back later!";
        }
    }

    // --- Fetch Pending Enrollments for Admin/Instructor ---
    if ($user_role === 'admin' || $user_role === 'instructor') {
        $sql_enrollments = "
            SELECT
                ce.id AS enrollment_id,
                ce.enrollment_date,
                s.username AS student_username,
                s.full_name AS student_full_name,
                s.email AS student_email,
                c.course_name,
                c.fees,
                c.id AS course_id,
                c.instructor_id
            FROM course_enrollments ce
            JOIN users s ON ce.student_id = s.id
            JOIN courses c ON ce.course_id = c.id
            WHERE ce.status = 'pending'
        ";
        $params_enrollments = [];

        if ($user_role === 'instructor') {
            // Instructors only see pending enrollments for their own courses
            $sql_enrollments .= " AND c.instructor_id = ?";
            $params_enrollments[] = $user_id;
        }

        $sql_enrollments .= " ORDER BY ce.enrollment_date ASC";

        $stmt_enrollments = $pdo->prepare($sql_enrollments);
        $stmt_enrollments->execute($params_enrollments);
        $pending_enrollments = $stmt_enrollments->fetchAll(PDO::FETCH_ASSOC);
    }

} catch (PDOException $e) {
    $message = "Database error: " . $e->getMessage();
    $is_error = true;
    error_log("Dashboard Data Fetch Error: " . $e->getMessage());
}

?>

<!-- Main content container for the dashboard. This div will be inserted into the <main> tag in index.php -->
<div class="w-full max-w-7xl mx-auto p-6 bg-white rounded-lg shadow-xl">

    <!-- Dashboard Header Section -->
    <div class="flex flex-col sm:flex-row justify-between items-center mb-8 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900 mb-2 sm:mb-0">
            Welcome, <span class="text-blue-700"><?php echo htmlspecialchars($username); ?></span>!
        </h1>
        <div class="text-lg text-gray-700">
            Your Role: <span class="font-semibold capitalize text-blue-600"><?php echo htmlspecialchars($user_role); ?></span>
        </div>
    </div>

    <?php if (!empty($message) && !$is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-blue-50 text-blue-700 border border-blue-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if ($is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <!-- Pending Enrollments Section (Admin/Instructor View) -->
    <?php if (($user_role === 'admin' || $user_role === 'instructor') && !empty($pending_enrollments)): ?>
        <h2 class="text-2xl font-bold mb-6 text-gray-800">Pending Enrollment Requests</h2>
        <div class="mb-8 grid grid-cols-1 md:grid-cols-2 gap-6">
            <?php foreach ($pending_enrollments as $enrollment): ?>
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg shadow-sm p-6 flex flex-col">
                    <h3 class="text-xl font-bold text-yellow-800 mb-2">Enrollment #<?php echo htmlspecialchars($enrollment['enrollment_id']); ?></h3>
                    <p class="text-gray-700 text-sm mb-1"><span class="font-semibold">Student:</span> <?php echo htmlspecialchars($enrollment['student_full_name'] ?: $enrollment['student_username']); ?></p>
                    <p class="text-gray-700 text-sm mb-1"><span class="font-semibold">Email:</span> <?php echo htmlspecialchars($enrollment['student_email']); ?></p>
                    <p class="text-gray-700 text-sm mb-1"><span class="font-semibold">Course:</span> <?php echo htmlspecialchars($enrollment['course_name']); ?></p>
                    <p class="text-gray-700 text-sm mb-3"><span class="font-semibold">Requested On:</span> <?php echo date('M d, Y H:i', strtotime($enrollment['enrollment_date'])); ?></p>
                    <div class="flex-grow"></div> <!-- Spacer -->
                    <a href="index.php?page=manage_enrollment&id=<?php echo htmlspecialchars($enrollment['enrollment_id']); ?>"
                       class="mt-4 block w-full px-4 py-2 bg-yellow-600 text-white text-center font-semibold rounded-md hover:bg-yellow-700 transition duration-300">
                        View & Manage Enrollment
                    </a>
                </div>
            <?php endforeach; ?>
        </div>
        <hr class="my-8 border-gray-200"> <!-- Separator between sections -->
    <?php elseif (($user_role === 'admin' || $user_role === 'instructor')): ?>
         <div class="mb-8 p-4 rounded-md text-center text-lg bg-yellow-50 text-yellow-700 border border-yellow-200">
            No pending enrollment requests at this time.
        </div>
        <hr class="my-8 border-gray-200">
    <?php endif; ?>


    <!-- Course Listing Grid (for all users) -->
    <h2 class="text-2xl font-bold mb-6 text-gray-800">
        <?php
            if ($user_role === 'student') {
                echo 'Explore All Courses';
            } elseif ($user_role === 'instructor') {
                echo 'Your Managed Courses';
            } else { // Admin
                echo 'All System Courses';
            }
        ?>
    </h2>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        <?php if (!empty($courses)): ?>
            <?php foreach ($courses as $course): ?>
                <div class="bg-white border border-gray-200 rounded-lg shadow-md overflow-hidden flex flex-col hover:shadow-xl transition-shadow duration-300">
                    <div class="p-6 flex-grow">
                        <h3 class="text-xl font-bold mb-2 text-gray-900 leading-tight">
                            <?php echo htmlspecialchars($course['course_name']); ?>
                        </h3>
                        <p class="text-sm text-gray-600 mb-3">
                            Instructor: <span class="font-medium text-blue-600"><?php echo htmlspecialchars($course['instructor_name'] ?: 'N/A'); ?></span>
                        </p>
                        <p class="text-gray-700 text-sm mb-4 line-clamp-3">
                            <?php echo htmlspecialchars($course['description']); ?>
                        </p>

                        <div class="flex items-center text-sm text-gray-600 mb-2">
                            <svg class="w-4 h-4 mr-2 text-green-500" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 002 2v4a2 2 0 002 2V6a2 2 0 00-2-2H4zm10 0a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6a2 2 0 012-2h10zM4 14a2 2 0 00-2 2v4a2 2 0 002 2h12a2 2 0 002-2v-4a2 2 0 00-2-2H4z" clip-rule="evenodd"></path></svg>
                            <span>Fees: <span class="font-medium">$<?php echo number_format($course['fees'], 2); ?></span></span>
                        </div>
                        <div class="flex items-center text-sm text-gray-600 mb-2">
                            <svg class="w-4 h-4 mr-2 text-orange-500" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l3 3a1 1 0 001.414-1.414L11 9.586V6z" clip-rule="evenodd"></path></svg>
                            <span>Duration: <span class="font-medium"><?php echo htmlspecialchars($course['duration']); ?></span></span>
                        </div>
                        <div class="flex items-center text-sm text-gray-600 mb-4">
                            <svg class="w-4 h-4 mr-2 text-blue-500" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd"></path></svg>
                            <span>Starts: <span class="font-medium"><?php echo date('M d, Y', strtotime($course['start_date'])); ?></span></span>
                        </div>
                    </div>
                    <div class="p-6 bg-gray-50 border-t border-gray-100">
                        <a href="index.php?page=course_details&id=<?php echo htmlspecialchars($course['id']); ?>" class="block px-4 py-2 bg-blue-600 text-white text-center font-semibold rounded-md hover:bg-blue-700 transition duration-300">View Course</a>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php elseif ($user_role !== 'admin' && $user_role !== 'instructor'): ?>
            <div class="mb-6 p-4 rounded-md text-center text-lg bg-blue-50 text-blue-700 border border-blue-200 col-span-full">
                No courses to display at the moment.
            </div>
        <?php endif; ?>
    </div>

    <!-- Role-specific action buttons (Admin/Instructor) -->
    <?php if ($user_role === 'admin' || $user_role === 'instructor'): ?>
        <div class="mt-10 pt-6 border-t border-gray-200 text-center space-y-4 md:space-y-0 md:space-x-4">
            <?php if ($user_role === 'admin'): ?>
                <a href="index.php?page=register_student" class="inline-block px-6 py-3 bg-purple-600 text-white font-semibold rounded-md hover:bg-purple-700 transition duration-300 shadow-md">Register New Student</a>
                <a href="index.php?page=register_instructor" class="inline-block px-6 py-3 bg-indigo-600 text-white font-semibold rounded-md hover:bg-indigo-700 transition duration-300 shadow-md">Register New Instructor</a>
            <?php endif; ?>
            <a href="index.php?page=create_course" class="inline-block px-6 py-3 bg-green-600 text-white font-semibold rounded-md hover:bg-green-700 transition duration-300 shadow-md">Create New Course</a>
        </div>
    <?php endif; ?>
</div>
