<?php
// my_courses.php
// This page displays all courses a student is currently enrolled in as cards,
// performing a crucial access check using the lms_access table.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'student') {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$username = $_SESSION['username'] ?? 'Student';
$user_id = $_SESSION['user_id'] ?? null;
$today = date('Y-m-d'); // Current date for comparison

$enrolled_courses = [];
$message = '';
$is_error = false;

try {
    $stmt = $pdo->prepare("
        SELECT
            ce.id AS enrollment_id,
            b.id AS batch_id,
            b.batch_name,
            c.course_name,
            c.image_path,
            u.full_name AS instructor_name,
            ce.enrollment_date,
            la.access_end_date,
            la.lifetime_access
        FROM course_enrollments ce
        JOIN batches b ON ce.batch_id = b.id
        JOIN courses c ON b.course_id = c.id
        JOIN users u ON b.instructor_id = u.id
        LEFT JOIN lms_access la ON ce.id = la.enrollment_id
        WHERE ce.student_id = ? AND ce.status = 'enrolled'
        ORDER BY ce.enrollment_date DESC, c.course_name ASC
    ");
    $stmt->execute([$user_id]);
    $enrolled_courses = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($enrolled_courses)) {
        $message = "You are not currently enrolled in any courses. Explore available courses from your dashboard!";
    }

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

// Function to check access status
function check_access($course, $today) {
    if (empty($course['access_end_date']) && $course['lifetime_access'] === null) {
        return ['status' => 'pending', 'message' => 'Pending First Payment Verification.'];
    }
    
    if ($course['lifetime_access'] == 1) {
        return ['status' => 'active', 'message' => 'Lifetime Access'];
    }

    $expiry_date = $course['access_end_date'];
    if ($expiry_date && $expiry_date >= $today) {
        $remaining_days = (new DateTime($expiry_date))->diff(new DateTime($today))->days;
        return ['status' => 'active', 'message' => "Access expires in $remaining_days days (on " . date('M d, Y', strtotime($expiry_date)) . ")"];
    } else {
        return ['status' => 'expired', 'message' => "Access Expired on " . date('M d, Y', strtotime($expiry_date ?? 'now')) . ". Please make your next payment."];
    }
}
?>

<div class="p-4">
    <div class="flex flex-col sm:flex-row justify-between items-center mb-6 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900 mb-2 sm:mb-0">
            My Courses, <span class="text-blue-700"><?php echo htmlspecialchars($username); ?></span>!
        </h1>
        <div class="text-lg text-gray-700">
            Current Date: <span class="font-semibold text-green-600"><?php echo $today; ?></span>
        </div>
    </div>

    <h2 class="text-2xl font-bold mb-6 text-gray-800">Select a Course to View Schedule</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 sm:grid-cols-2 lg:grid-cols-3 gap-8">
        <?php if (!empty($enrolled_courses)): ?>
            <?php foreach ($enrolled_courses as $course): 
                $access = check_access($course, $today);
                $is_active = $access['status'] === 'active';
                $card_classes = $is_active ? 'border-green-400 cursor-pointer hover:shadow-2xl' : 'border-red-400 bg-gray-50 opacity-70 cursor-not-allowed';
                $link_url = $is_active ? "index.php?page=course_schedule_details&batch_id=" . htmlspecialchars($course['batch_id']) : "#";
            ?>

            <a href="<?php echo $link_url; ?>" class="block rounded-xl shadow-lg overflow-hidden transition-all duration-300 border-2 <?php echo $card_classes; ?>">
                <div class="relative h-48 bg-gray-200">
                    <img src="<?php echo htmlspecialchars($course['image_path'] ?? 'https://placehold.co/400x200/4F46E5/FFFFFF?text=LMS+Course'); ?>" 
                         alt="<?php echo htmlspecialchars($course['course_name']); ?>" 
                         class="w-full h-full object-cover">
                </div>
                <div class="p-6">
                    <h3 class="text-xl font-bold mb-1 text-gray-900 leading-tight">
                        <?php echo htmlspecialchars($course['course_name']); ?>
                    </h3>
                    <p class="text-sm text-gray-600 mb-4">
                        Batch: <span class="font-semibold"><?php echo htmlspecialchars($course['batch_name']); ?></span> by <?php echo htmlspecialchars($course['instructor_name']); ?>
                    </p>

                    <div class="p-3 rounded-lg text-sm font-semibold 
                        <?php echo $is_active ? 'bg-green-100 text-green-700 border border-green-300' : 'bg-red-100 text-red-700 border border-red-300'; ?>">
                        <?php if ($is_active): ?>
                            ✅ ACCESS GRANTED: 
                        <?php else: ?>
                            ❌ ACCESS RESTRICTED:
                        <?php endif; ?>
                        <span class="block mt-1 font-normal"><?php echo htmlspecialchars($access['message']); ?></span>
                    </div>

                    <?php if (!$is_active): ?>
                        <a href="index.php?page=my_monthly_payments" 
                           class="mt-4 block w-full text-center py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition duration-300 shadow-md">
                            Go to Payments Page
                        </a>
                    <?php endif; ?>
                </div>
            </a>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="mb-6 p-6 rounded-md text-center text-xl bg-blue-50 text-blue-700 border border-blue-200 col-span-full">
                No courses to display at the moment. Time to enroll!
            </div>
        <?php endif; ?>
    </div>
</div>