<?php
// student_dashboard.php
// This is the dedicated dashboard view for students, primarily for exploring all available courses.

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

// Ensure the user is logged in AND is a student.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'student') {
    header("Location: index.php?page=login");
    exit();
}

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


$username = $_SESSION['username'] ?? 'Student';
$user_id = $_SESSION['user_id'] ?? null;

$courses = []; // To store available courses
$message = '';
$is_error = false;

// --- PAYMENT REMINDER FETCH (Dashboard Banner) ---
$payment_reminder_info = null;

if ($_SESSION['user_role'] === 'student' && isset($_SESSION['user_id'])) {
    $student_id = $_SESSION['user_id'];
    
    try {
        // Find the earliest access end date (next payment due date) for the current student
        $stmt_payment = $pdo->prepare("
            SELECT 
                la.access_end_date, 
                b.batch_name
            FROM lms_access la
            JOIN course_enrollments ce ON la.enrollment_id = ce.id
            JOIN batches b ON ce.batch_id = b.id
            WHERE 
                ce.student_id = ? AND 
                la.lifetime_access = 0 AND 
                ce.status = 'approved' AND -- CORRECTED: Changed 'enrolled' to 'approved'
                la.access_end_date IS NOT NULL
            ORDER BY la.access_end_date ASC
            LIMIT 1
        ");
        $stmt_payment->execute([$student_id]);
        $payment_reminder_info = $stmt_payment->fetch(PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        // Log the error but don't stop the dashboard from loading
        error_log("Dashboard Payment Check Error: " . $e->getMessage());
    }
}
// ---------------------------------------------------

try {
    // Fetch ALL available courses for the student to explore
    // Now fetching only the core course information
    $stmt = $pdo->prepare("
        SELECT
            c.id,
            c.course_name,
            c.image_path
        FROM courses c
        ORDER BY c.course_name ASC
    ");
    $stmt->execute();
    $courses = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($courses)) {
        $message = "No courses are currently available for you to explore. Check back later!";
    }

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

?>
<div class="w-full max-w-7xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    
    <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="flex items-center space-x-4 text-lg text-gray-700">
            <span>Your Role: <span class="font-semibold capitalize text-blue-600">Student</span></span>
           
        </div>
    </div>
<?php 
// This block contains the HTML/CSS logic for the banner and is fine as is.
if ($payment_reminder_info):
    $due_date = $payment_reminder_info['access_end_date'];
    $batch_name = htmlspecialchars($payment_reminder_info['batch_name']);
    $days_to_expiry = (strtotime($due_date) - time()) / (60 * 60 * 24);
    $formatted_date = date('F d, Y', strtotime($due_date));

    // Determine color and message based on urgency
    if ($days_to_expiry <= 0) {
        $banner_class = 'bg-red-100 border-red-500 text-red-800';
        $banner_message = "⚠️ **URGENT:** Your access for the **{$batch_name}** batch expired on **{$formatted_date}**! Please submit your payment slip immediately.";
    } elseif ($days_to_expiry <= 7) {
        $banner_class = 'bg-yellow-100 border-yellow-500 text-yellow-800';
        $banner_message = "🔔 **REMINDER:** Your monthly payment for the **{$batch_name}** batch is due on **{$formatted_date}** ({$days_to_expiry} days left). Submit your slip now!";
    } else {
        $banner_class = null; // Don't show the banner
    }

    if ($banner_class):
?>
     <div class="mb-6 p-4 rounded-lg border-l-4 <?php echo $banner_class; ?>" role="alert">
        <p class="font-semibold text-lg">
            <?php echo $banner_message; ?>
        </p>
    </div>
<?php 
    endif;
endif;
?>

    <h2 class="text-2xl font-bold mb-6 text-gray-800">Explore All Available Courses</h2>

    <?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; ?>

    <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">
                    <img src="<?php echo htmlspecialchars($course['image_path'] ?? 'public/images/default-course.png'); ?>" alt="Course Image" class="w-full h-48 object-cover">
                    <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>
                    </div>
                    <div class="p-6 bg-gray-50 border-t border-gray-100">
                        <a href="index.php?page=course_batches&course_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 Available Batches
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <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>
</div>

<script>
    if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    // The service worker file must be located at the highest level possible
    // (root of your application) to control all URLs under it.
    navigator.serviceWorker.register('/service-worker.js')
      .then(registration => {
        console.log('Service Worker registered:', registration.scope);
      })
      .catch(error => {
        console.error('Service Worker registration failed:', error);
      });
  });
}
</script>