<?php
// course_schedule_details.php
// This page displays the detailed schedule for a single, selected batch,
// protected by the lms_access check.

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

$user_id = $_SESSION['user_id'] ?? null;
$batch_id = filter_var($_GET['batch_id'] ?? null, FILTER_VALIDATE_INT);
$today = date('Y-m-d');

$course_details = null;
$schedules = [];
$message = '';
$is_error = false;
$access_granted = false;
$access_message = '';

if (!$batch_id) {
    $is_error = true;
    $message = "Invalid batch selected.";
}

if (!$is_error) {
    try {
        // 1. Fetch Course Details and Access Status
        $stmt = $pdo->prepare("
            SELECT
                ce.id AS enrollment_id,
                b.batch_name,
                b.start_date,
                c.course_name,
                u.full_name AS instructor_name,
                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.batch_id = ? AND ce.status = 'enrolled'
            LIMIT 1
        ");
        $stmt->execute([$user_id, $batch_id]);
        $course_details = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$course_details) {
            $is_error = true;
            $message = "Enrollment not found for this course batch.";
        } else {
            // 2. Perform Access Check
            $expiry_date = $course_details['access_end_date'];
            $lifetime = $course_details['lifetime_access'];

            if ($lifetime == 1) {
                $access_granted = true;
                $access_message = "Lifetime Access Granted.";
            } elseif ($expiry_date && $expiry_date >= $today) {
                $access_granted = true;
                $remaining_days = (new DateTime($expiry_date))->diff(new DateTime($today))->days;
                $access_message = "Access valid until " . date('M d, Y', strtotime($expiry_date)) . ". ($remaining_days days remaining)";
            } else {
                $access_granted = false;
                $access_message = "Access Expired on " . date('M d, Y', strtotime($expiry_date ?? 'now')) . ". Please complete your payment.";
            }

            // 3. Fetch Schedule if Access is Granted
            if ($access_granted) {
                $schedule_stmt = $pdo->prepare("
                    SELECT
                        id,
                        schedule_date,
                        start_time,
                        end_time,
                        topic,
                        location_or_link AS zoom_link,
                        recording_link 
                    FROM batch_schedules
                    WHERE batch_id = ?
                    ORDER BY schedule_date ASC, start_time ASC
                ");
                $schedule_stmt->execute([$batch_id]);
                $schedules = $schedule_stmt->fetchAll(PDO::FETCH_ASSOC);
            }
        }

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

<div class="p-4">
    <div class="flex justify-between items-center mb-6 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900">
            <?php echo htmlspecialchars($course_details['course_name'] ?? 'Course Schedule'); ?>
        </h1>
        <a href="index.php?page=my_courses" class="text-sm font-semibold text-blue-600 hover:text-blue-800 transition duration-300">
            &larr; Back to My Courses
        </a>
    </div>

    <?php if ($is_error || !$course_details): ?>
        <div class="mb-6 p-6 rounded-md text-center text-xl bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
        </div>
    <?php elseif (!$access_granted): ?>
        <div class="mb-6 p-6 rounded-md bg-yellow-100 border border-yellow-400">
            <h2 class="text-2xl font-bold text-red-600 mb-3">🔒 Access Restricted</h2>
            <p class="text-lg text-gray-800"><?php echo htmlspecialchars($access_message); ?></p>
            <p class="mt-4 text-gray-700">To unlock your course schedule and class links, please ensure your latest monthly payment is successfully verified by the administrator.</p>
            <a href="index.php?page=my_monthly_payments" class="mt-4 inline-block px-6 py-2 bg-blue-600 text-white font-semibold rounded-md hover:bg-blue-700 transition duration-300">
                Go to Payments
            </a>
        </div>
    <?php else: // Access is Granted ?>
        <div class="p-4 rounded-md mb-6 bg-green-50 border border-green-300 text-green-800 font-semibold text-lg">
            ✅ Access Status: <?php echo htmlspecialchars($access_message); ?>
        </div>
        
        <h2 class="text-2xl font-bold mb-4 text-gray-800">
            Batch: <?php echo htmlspecialchars($course_details['batch_name']); ?>
            <span class="text-sm font-normal text-gray-500 ml-3"> (Instructor: <?php echo htmlspecialchars($course_details['instructor_name']); ?>)</span>
        </h2>

        <?php if (!empty($schedules)): ?>
            <div class="space-y-6">
                <?php
                $course_start_date = new DateTime($course_details['start_date']);
                $current_course_week = 0;

                foreach ($schedules as $session):
                    $session_date = new DateTime($session['schedule_date']);
                    $interval = $course_start_date->diff($session_date);
                    $calculated_week = floor($interval->days / 7) + 1;
                    
                    $is_past_class = $session_date < new DateTime($today);
                    $session_class = $is_past_class ? 'bg-gray-100 opacity-80' : 'bg-blue-50 border-blue-200';

                    if ($calculated_week !== $current_course_week) {
                        echo '<h3 class="text-xl font-bold text-gray-700 mt-8 mb-3 p-3 rounded-md bg-indigo-50 border-l-4 border-indigo-400">Course Week ' . $calculated_week . '</h3>';
                        $current_course_week = $calculated_week;
                    }
                ?>
                <div class="border rounded-xl p-5 flex flex-col sm:flex-row justify-between items-start sm:items-center shadow-md <?php echo $session_class; ?>">
                    <div class="mb-3 sm:mb-0 flex-grow">
                        <p class="font-bold text-lg text-gray-900">
                            <?php echo date('D, M d, Y', strtotime($session['schedule_date'])); ?>
                            <span class="text-sm font-normal text-gray-600 ml-2">
                                <?php echo date('h:i A', strtotime($session['start_time'])) . ' - ' . date('h:i A', strtotime($session['end_time'])); ?>
                            </span>
                        </p>
                        <p class="text-base text-gray-700 mt-1">
                            Topic: <span class="font-medium"><?php echo htmlspecialchars($session['topic']); ?></span>
                        </p>
                    </div>
                    
                    <div class="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-3">
                        <?php 
                        // NEW LOGIC HERE: CHECK FOR PAST CLASS AND RECORDING LINK
                        if ($is_past_class): 
                            if (!empty($session['recording_link'])): ?>
                                <a href="<?php echo htmlspecialchars($session['recording_link']); ?>" target="_blank"
                                   class="inline-flex items-center px-5 py-2 bg-green-600 text-white text-sm font-bold rounded-lg hover:bg-green-700 transition duration-300 shadow-lg">
                                    <svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 6a2 2 0 012-2h6a2 2 0 012 2v2a2 2 0 01-2 2H4a2 2 0 01-2-2V6zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2zM4 14a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2z"></path></svg>
                                    View Recording
                                </a>
                            <?php else: ?>
                                <span class="px-4 py-2 text-sm font-semibold text-gray-500 rounded-md">
                                    No Recording Uploaded
                                </span>
                            <?php endif; ?>
                        <?php else: ?>
                            <a href="<?php echo htmlspecialchars($session['zoom_link']); ?>" target="_blank"
                               class="inline-flex items-center px-5 py-2 bg-blue-600 text-white text-sm font-bold rounded-lg hover:bg-blue-700 transition duration-300 shadow-lg">
                                <svg class="w-4 h-4 mr-2" 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 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path></svg>
                                Join Live Class
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="mb-6 p-4 rounded-md text-center text-lg bg-gray-100 text-gray-700 border border-gray-200">
                <p class="italic">No schedule available yet for this batch. Please check back later.</p>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>