<?php
// course_batches.php - UPDATED
// This page displays all available batches for a specific course.

// 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';

$course_id = $_GET['course_id'] ?? null;
$student_id = $_SESSION['user_id']; // Get the logged-in student's ID
$course_name = '';
$batches = [];
$message = '';
$is_error = false;

// Check if a course ID is provided
if (!$course_id || !is_numeric($course_id)) {
    $is_error = true;
    $message = "Invalid course ID provided.";
} else {
    try {
        // First, get the course name to display in the heading
        $stmt_course = $pdo->prepare("SELECT course_name FROM courses WHERE id = ?");
        $stmt_course->execute([$course_id]);
        $course_data = $stmt_course->fetch(PDO::FETCH_ASSOC);

        if ($course_data) {
            $course_name = $course_data['course_name'];

            // ✅ MODIFIED QUERY: Added condition to only select batches where start_date is in the future or today
            $stmt_batches = $pdo->prepare("
                SELECT
                    b.id,
                    b.batch_name,
                    b.fees,
                    b.duration,
                    b.start_date,
                    b.end_date,
                    b.modality,
                    u.full_name AS instructor_name,
                    ce.status AS enrollment_status,
                    ce.id AS enrollment_id
                FROM batches b
                LEFT JOIN users u ON b.instructor_id = u.id
                LEFT JOIN course_enrollments ce ON b.id = ce.batch_id AND ce.student_id = ?
                WHERE b.course_id = ?
                AND b.start_date >= CURDATE()  /* <<< THIS IS THE NEW CONDITION */
                ORDER BY b.start_date ASC
            ");
            $stmt_batches->execute([$student_id, $course_id]);
            $batches = $stmt_batches->fetchAll(PDO::FETCH_ASSOC);

            if (empty($batches)) {
                $message = "No upcoming batches are currently available for this course. Please check back later!";
            }
        } else {
            $is_error = true;
            $message = "Course not found.";
        }

    } catch (PDOException $e) {
        $is_error = true;
        $message = "Database error fetching batches: " . $e->getMessage();
        error_log("Course Batches 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">
            Batches for <span class="text-blue-700"><?php echo htmlspecialchars($course_name); ?></span>
        </h1>
        <a href="index.php?page=student_dashboard" class="text-blue-600 hover:text-blue-800 transition duration-300 font-semibold flex items-center">
            <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd"></path></svg>
            Back to All Courses
        </a>
    </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; ?>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        <?php if (!empty($batches)): ?>
            <?php foreach ($batches as $batch): ?>
                <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">
                        <div class="flex items-center justify-between mb-2">
                             <h3 class="text-xl font-bold text-gray-900 leading-tight">
                                 <?php echo htmlspecialchars($batch['batch_name']); ?>
                             </h3>
                             <span class="text-sm font-medium px-2 py-1 rounded-full <?php echo $batch['modality'] === 'online' ? 'bg-green-100 text-green-700' : 'bg-indigo-100 text-indigo-700'; ?>">
                                 <?php echo htmlspecialchars(ucfirst($batch['modality'])); ?>
                             </span>
                        </div>
                        <p class="text-sm text-gray-600 mb-4">
                            Instructor: <span class="font-medium text-blue-600"><?php echo htmlspecialchars($batch['instructor_name'] ?: 'N/A'); ?></span>
                        </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 d="M10 2a8 8 0 100 16 8 8 0 000-16zM6.5 9.5a.5.5 0 01.5-.5h2a.5.5 0 01.5.5V12a.5.5 0 01-1 0v-2H7a.5.5 0 01-.5-.5z" clip-rule="evenodd"></path></svg>
                            <span>Fees: <span class="font-medium">$<?php echo number_format($batch['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($batch['duration']); ?></span></span>
                        </div>
                        <div class="flex items-center text-sm text-gray-600 mb-2">
                            <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($batch['start_date'])); ?></span></span>
                        </div>
                          <?php if (!empty($batch['end_date'])): ?>
                            <div class="flex items-center text-sm text-gray-600">
                                <svg class="w-4 h-4 mr-2 text-red-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>Ends: <span class="font-medium"><?php echo date('M d, Y', strtotime($batch['end_date'])); ?></span></span>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="p-6 bg-gray-50 border-t border-gray-100">
                        <?php if ($batch['enrollment_status'] === 'enrolled'): ?>
                            <span class="block px-4 py-2 bg-gray-500 text-white text-center font-semibold rounded-md cursor-not-allowed">You are Enrolled!</span>
                        <?php elseif ($batch['enrollment_status'] === 'pending' || $batch['enrollment_status'] === 'payment_uploaded'): ?>
                            <a href="index.php?page=submit_payment_page&enrollment_id=<?php echo htmlspecialchars($batch['enrollment_id']); ?>" class="block px-4 py-2 bg-orange-600 text-white text-center font-semibold rounded-md hover:bg-orange-700 transition duration-300">
                                View Pending Request
                            </a>
                        <?php else: ?>
                            <a href="index.php?page=enrollment_request&batch_id=<?php echo htmlspecialchars($batch['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">
                                Enroll in This Batch
                            </a>
                        <?php endif; ?>
                    </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 upcoming batches to display at the moment.
            </div>
        <?php endif; ?>
    </div>
</div>