<?php
// admin_course_batches.php
// Dedicated page for Admins/Instructors to view and filter all 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 either an admin or instructor.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$course_id = $_GET['course_id'] ?? null;
$user_id = $_SESSION['user_id'] ?? null;
$user_role = $_SESSION['user_role'] ?? 'guest';

$course_name = '';
$batches = [];
$message = '';
$is_error = false;

// --- Helper function to determine batch status (Copied from previous solution) ---
function get_batch_status($start_date, $end_date) {
    $now = new DateTime();
    $start = new DateTime($start_date);
    $end = $end_date ? new DateTime($end_date) : null;

    if ($now < $start) {
        return 'opened'; // Registration open, hasn't started
    } elseif ($end && $now > $end) {
        return 'closed'; // Finished
    } else {
        return 'running'; // Currently in progress
    }
}

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

            // Fetch ALL batches for this course, applying instructor filter if necessary
            $sql_batches = "
                SELECT
                    b.id AS batch_id, b.batch_name, b.fees, b.duration, b.modality, b.start_date, b.end_date,
                    u.full_name AS instructor_name, u.id AS instructor_id
                FROM batches b
                LEFT JOIN users u ON b.instructor_id = u.id
                WHERE b.course_id = ?
            ";
            
            $params_batches = [$course_id];

            // If the user is an instructor, filter batches by their ID
            if ($user_role === 'instructor') {
                $sql_batches .= " AND b.instructor_id = ?";
                $params_batches[] = $user_id;
            }

            $sql_batches .= " ORDER BY b.start_date DESC";

            $stmt_batches = $pdo->prepare($sql_batches);
            $stmt_batches->execute($params_batches);
            $raw_batches = $stmt_batches->fetchAll(PDO::FETCH_ASSOC);

            // Calculate status for each batch
            foreach ($raw_batches as $batch) {
                 $batch['status'] = get_batch_status($batch['start_date'], $batch['end_date']);
                 $batches[] = $batch;
            }
            

            if (empty($batches)) {
                $message = "No batches found for this course " . ($user_role === 'instructor' ? 'that you manage.' : '.');
            }
            
        } else {
            $is_error = true;
            $message = "Course not found.";
        }

    } catch (PDOException $e) {
        $is_error = true;
        $message = "Database error fetching batches: " . $e->getMessage();
        error_log("Admin 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=admin_dashboard" class="text-blue-600 hover:text-blue-800 transition duration-300 font-semibold flex items-center">
            <i class="fas fa-arrow-left w-4 h-4 mr-1"></i>
            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="bg-gray-50 p-4 rounded-lg shadow-sm mb-8">
        <h3 class="text-lg font-semibold text-gray-700 mb-3">Filter Batches:</h3>
        <div class="flex flex-wrap gap-4">
            <select id="modality-filter" class="p-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 text-sm">
                <option value="">All Modalities</option>
                <option value="online">Online</option>
                <option value="physical">Physical</option>
            </select>
            <select id="status-filter" class="p-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 text-sm">
                <option value="">All Statuses</option>
                <option value="opened">Opened (Pending Start)</option>
                <option value="running">Running (In Progress)</option>
                <option value="closed">Closed (Finished)</option>
            </select>
            <button onclick="clearFilters()" class="p-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition duration-150 text-sm font-medium">Clear Filters</button>
        </div>
    </div>


    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8" id="batch-list-container">
        <?php if (!empty($batches)): ?>
            <?php foreach ($batches as $batch): 
                $modality_class = $batch['modality'] === 'online' ? 'bg-green-100 text-green-700' : 'bg-indigo-100 text-indigo-700';
                
                $status_class = [
                    'opened' => 'bg-green-100 text-green-700',
                    'running' => 'bg-blue-100 text-blue-700',
                    'closed' => 'bg-red-100 text-red-700',
                ][$batch['status']] ?? 'bg-gray-100 text-gray-700';

            ?>
                <div class="bg-white border border-gray-200 rounded-lg shadow-md overflow-hidden batch-card"
                     data-modality="<?php echo htmlspecialchars($batch['modality']); ?>"
                     data-status="<?php echo htmlspecialchars($batch['status']); ?>"
                     style="display: block;"> <div class="p-6">
                        <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 capitalize <?php echo $modality_class; ?>">
                                 <?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">
                             <span class="text-sm font-medium px-2 py-1 rounded-full capitalize <?php echo $status_class; ?>">
                                 Status: <?php echo htmlspecialchars(ucfirst($batch['status'])); ?>
                             </span>
                        </div>
                        
                        <div class="text-sm text-gray-700 mt-2">
                             <p class="flex items-center mb-1"><i class="fas fa-dollar-sign w-4 h-4 mr-2 text-green-500"></i> Fees: <span class="font-medium ml-1">$<?php echo number_format($batch['fees'], 2); ?></span></p>
                             <p class="flex items-center mb-1"><i class="fas fa-clock w-4 h-4 mr-2 text-orange-500"></i> Duration: <span class="font-medium ml-1"><?php echo htmlspecialchars($batch['duration']); ?></span></p>
                             <p class="flex items-center mb-1"><i class="fas fa-calendar-alt w-4 h-4 mr-2 text-blue-500"></i> Starts: <span class="font-medium ml-1"><?php echo date('M d, Y', strtotime($batch['start_date'])); ?></span></p>
                             <?php if (!empty($batch['end_date'])): ?>
                                <p class="flex items-center"><i class="fas fa-calendar-times w-4 h-4 mr-2 text-red-500"></i> Ends: <span class="font-medium ml-1"><?php echo date('M d, Y', strtotime($batch['end_date'])); ?></span></p>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="p-4 bg-gray-50 border-t border-gray-100 flex justify-around">
                        <a href="index.php?page=manage_batch_students&batch_id=<?php echo htmlspecialchars($batch['batch_id']); ?>" class="text-blue-600 hover:text-blue-800 font-semibold text-sm">Manage Students</a>
                        <a href="index.php?page=edit_batch&batch_id=<?php echo htmlspecialchars($batch['batch_id']); ?>" class="text-yellow-600 hover:text-yellow-800 font-semibold text-sm">Edit Batch</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" id="no-batches-message">
                No batches to display at the moment.
            </div>
        <?php endif; ?>
         <div class="mb-6 p-4 rounded-md text-center text-lg bg-yellow-50 text-yellow-700 border border-yellow-200 col-span-full" id="filtered-no-results" style="display: none;">
            No batches match the selected filters.
        </div>
    </div>
</div>

<div class="h-12"></div>
<footer class="mt-auto bg-gray-200 text-center py-4 text-gray-600">
    <p>&copy; <?php echo date("Y"); ?> LMS Prototype. All rights reserved.</p>
</footer>

<script>
    function applyFilters() {
        const modality = document.getElementById('modality-filter').value;
        const status = document.getElementById('status-filter').value;
        const batchCards = document.querySelectorAll('.batch-card');
        const noResultsMessage = document.getElementById('filtered-no-results');
        const initialMessage = document.getElementById('no-batches-message');
        
        let visibleBatchCount = 0;

        batchCards.forEach(card => {
            const cardModality = card.getAttribute('data-modality');
            const cardStatus = card.getAttribute('data-status');

            // Check visibility based on filters
            const modalityMatch = !modality || cardModality === modality;
            const statusMatch = !status || cardStatus === status;

            if (modalityMatch && statusMatch) {
                card.style.display = 'block'; 
                visibleBatchCount++;
            } else {
                card.style.display = 'none'; 
            }
        });
        
        // Handle "No Results" message display
        if (visibleBatchCount === 0 && batchCards.length > 0) {
            noResultsMessage.style.display = 'block';
        } else {
            noResultsMessage.style.display = 'none';
        }

        // Hide the initial "No batches" message if we are actively filtering existing batches
        if (initialMessage && batchCards.length > 0) {
            initialMessage.style.display = 'none';
        }

        // Re-show initial message if there are no batches at all and no filters
        if (initialMessage && batchCards.length === 0 && !modality && !status) {
             initialMessage.style.display = 'block';
        }
    }

    function clearFilters() {
        document.getElementById('modality-filter').value = '';
        document.getElementById('status-filter').value = '';
        applyFilters(); 
    }

    // Attach event listeners to the filter selects
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('modality-filter').addEventListener('change', applyFilters);
        document.getElementById('status-filter').addEventListener('change', applyFilters);
        
        // Initial call to ensure cards are displayed correctly (optional, but good practice)
        applyFilters(); 
    });
</script>
</body>
</html>