<?php
// course_details.php
// This page displays the detailed information for a specific course.

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

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

require_once 'config/database.php';

$course = null;
$message = '';
$is_error = false;

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

$student_enrollment_status = null; // Stores status of student's enrollment in THIS course
$enrollment_id = null; // Stores the enrollment_id if found

// Check if a course ID is provided in the URL.
$course_id = $_GET['id'] ?? null;

if (!$course_id || !is_numeric($course_id)) {
    $message = "Invalid course ID provided.";
    $is_error = true;
} else {
    try {
        // Fetch course details along with instructor's full name.
        $stmt = $pdo->prepare("
            SELECT
                c.id,
                c.course_name,
                c.description,
                c.fees,
                c.duration,
                c.start_date,
                u.full_name AS instructor_name
            FROM courses c
            JOIN users u ON c.instructor_id = u.id
            WHERE c.id = ?
            LIMIT 1
        ");
        $stmt->execute([$course_id]);
        $course = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$course) {
            $message = "Course not found.";
            $is_error = true;
        } else {
            // If logged in as a student, check enrollment status
            if ($user_role === 'student' && $user_id) {
                $stmt_enrollment = $pdo->prepare("SELECT id, status FROM course_enrollments WHERE student_id = ? AND course_id = ?");
                $stmt_enrollment->execute([$user_id, $course_id]);
                $enrollment_info = $stmt_enrollment->fetch(PDO::FETCH_ASSOC);

                if ($enrollment_info) {
                    $student_enrollment_status = $enrollment_info['status'];
                    $enrollment_id = $enrollment_info['id']; // Store enrollment ID
                    if ($student_enrollment_status === 'pending') {
                        $message = "You have a pending enrollment for this course. Please proceed to payment.";
                    } elseif ($student_enrollment_status === 'payment_uploaded') {
                        $message = "You have already submitted payment details. Your enrollment is pending verification.";
                    } elseif ($student_enrollment_status === 'enrolled') {
                        $message = "You are already enrolled in this course!";
                    } elseif ($student_enrollment_status === 'rejected') {
                        $message = "Your previous enrollment for this course was rejected. You may re-enroll if needed.";
                    }
                }
            }
        }

    } catch (PDOException $e) {
        $message = "Database error fetching course details or enrollment status: " . $e->getMessage();
        $is_error = true;
        error_log("Course Details/Enrollment Fetch Error: " . $e->getMessage());
    }
}
?>

<!-- Main content container for the course details page -->
<div class="w-full max-w-4xl mx-auto p-6 bg-white rounded-lg shadow-xl">

    <?php if ($is_error || !$course): ?>
        <!-- Display error message if course not found or invalid ID -->
        <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; ?>
            <p class="mt-4"><a href="index.php?page=dashboard" class="text-blue-600 hover:underline">Back to Dashboard</a></p>
        </div>
    <?php else: ?>
        <!-- Course Title and Back Link -->
        <div class="flex justify-between items-start mb-8 pb-4 border-b border-gray-200">
            <h1 class="text-3xl font-extrabold text-gray-900 leading-tight">
                <?php echo htmlspecialchars($course['course_name']); ?>
            </h1>
            <a href="index.php?page=student_dashboard" class="px-4 py-2 bg-gray-200 text-gray-700 font-semibold rounded-md hover:bg-gray-300 transition duration-300">
                Back to Courses
            </a>
        </div>

        <!-- Course Meta Info (Instructor, Fees, Duration, Start Date) -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
            <div class="flex items-center text-lg text-gray-700">
                <svg class="w-6 h-6 mr-3 text-blue-600" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg>
                <span class="font-semibold">Instructor:</span> <span class="ml-2"><?php echo htmlspecialchars($course['instructor_name'] ?: 'N/A'); ?></span>
            </div>
            <div class="flex items-center text-lg text-gray-700">
                <svg class="w-6 h-6 mr-3 text-green-600" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 002 2v4a2 2 0 002 2V6a2 2 0 00-2-2H4zm10 0a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6a2 2 0 012-2h10zM4 14a2 2 0 00-2 2v4a2 2 0 002 2h12a2 2 0 002-2v-4a2 2 0 00-2-2H4z" clip-rule="evenodd"></path></svg>
                <span class="font-semibold">Fees:</span> <span class="ml-2">$<?php echo number_format($course['fees'], 2); ?></span>
            </div>
            <div class="flex items-center text-lg text-gray-700">
                <svg class="w-6 h-6 mr-3 text-orange-600" 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 class="font-semibold">Duration:</span> <span class="ml-2"><?php echo htmlspecialchars($course['duration']); ?></span>
            </div>
            <div class="flex items-center text-lg text-gray-700">
                <svg class="w-6 h-6 mr-3 text-blue-600" 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 class="font-semibold">Starts On:</span> <span class="ml-2"><?php echo date('M d, Y', strtotime($course['start_date'])); ?></span>
            </div>
        </div>

        <!-- Course Description Section -->
        <div class="mb-8">
            <h3 class="text-xl font-bold mb-3 text-gray-800 border-b pb-2">Course Overview</h3>
            <p class="text-gray-700 leading-relaxed"><?php echo nl2br(htmlspecialchars($course['description'])); ?></p>
        </div>

        <?php if (!empty($message)): ?>
            <!-- Display status message (e.g., pending, payment_uploaded, enrolled) -->
            <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; ?>

        <!-- Enrollment/Payment Action Section -->
        <?php if ($user_role === 'student'): ?>
            <div class="text-center mt-6">
                <?php if ($student_enrollment_status === null || $student_enrollment_status === 'rejected'): ?>
                    <!-- Student not enrolled or rejected, allow to start enrollment -->
                    <p class="text-gray-600 mb-4">By clicking "Enroll Now", you agree to the course terms and conditions.</p>
                    <button id="enrollButton"
                            data-course-id="<?php echo htmlspecialchars($course['id']); ?>"
                            class="px-8 py-3 bg-indigo-600 text-white font-bold text-lg rounded-md hover:bg-indigo-700 transition duration-300 shadow-lg">
                        Enroll Now
                    </button>
                    <div id="enrollMessage" class="mt-4 text-center text-sm font-semibold"></div>
                <?php elseif ($student_enrollment_status === 'pending'): ?>
                    <!-- Student has pending enrollment, direct to payment submission -->
                    <p class="text-gray-600 mb-4">Your enrollment request is pending. Please submit your payment details to proceed.</p>
                    <a href="index.php?page=submit_payment&course_id=<?php echo htmlspecialchars($course['id']); ?>"
                       class="inline-block px-8 py-3 bg-purple-600 text-white font-bold text-lg rounded-md hover:bg-purple-700 transition duration-300 shadow-lg">
                        Submit Payment Details
                    </a>
                <?php else: ?>
                    <!-- Other statuses (payment_uploaded, enrolled) - just display message from PHP -->
                    <p class="text-gray-500 text-sm mt-2">
                        <?php if ($student_enrollment_status === 'payment_uploaded'): ?>
                            Payment details submitted and awaiting admin verification.
                        <?php elseif ($student_enrollment_status === 'enrolled'): ?>
                            You are successfully enrolled!
                        <?php endif; ?>
                    </p>
                <?php endif; ?>
            </div>
        <?php else: ?>
             <!-- For admin/instructor view, no enrollment action needed here -->
            <div class="text-center mt-6">
                <p class="text-gray-500 text-sm mt-2">No student enrollment action available for your role here.</p>
            </div>
        <?php endif; ?>

    <?php endif; ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const enrollButton = document.getElementById('enrollButton');
        const enrollMessageDiv = document.getElementById('enrollMessage');

        if (enrollButton) {
            enrollButton.addEventListener('click', async function() {
                const courseId = this.dataset.courseId;
                enrollMessageDiv.innerHTML = '<span class="text-blue-600">Submitting enrollment request...</span>';
                this.disabled = true; // Disable button to prevent multiple clicks

                try {
                    const response = await fetch('api/enroll_course.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ course_id: courseId })
                    });

                    const data = await response.json();

                    if (data.success) {
                        enrollMessageDiv.innerHTML = '<span class="text-green-600">' + data.message + ' Redirecting to payment...</span>';
                        // Redirect to payment page after successful initial enrollment request
                        setTimeout(() => {
                            window.location.href = 'index.php?page=submit_payment&course_id=' + courseId;
                        }, 2000);
                    } else {
                        enrollMessageDiv.innerHTML = '<span class="text-red-600">' + (data.message || 'Enrollment failed. Please try again.') + '</span>';
                        this.disabled = false; // Re-enable button on error
                    }
                } catch (error) {
                    console.error('Error during enrollment:', error);
                    enrollMessageDiv.innerHTML = '<span class="text-red-600">Network error or server issue during enrollment.</span>';
                    this.disabled = false; // Re-enable button on network error
                }
            });
        }
    });
</script>
