<?php
// enrollment_request.php - UPDATED
// This page shows a student the details of a batch and confirms their intent to enroll.

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

$batch_id = $_GET['batch_id'] ?? null;
$batch_details = null;
$is_error = false;
$message = '';

// Check if a batch ID is provided
if (!$batch_id || !is_numeric($batch_id)) {
    $is_error = true;
    $message = "Invalid batch ID provided. Please go back to the course list.";
} else {
    try {
        // Fetch details of the specific batch and its parent course
        $stmt = $pdo->prepare("
            SELECT
                b.id,
                b.batch_name,
                b.fees,
                b.duration,
                b.start_date,
                b.modality,
                c.course_name
            FROM batches b
            JOIN courses c ON b.course_id = c.id
            WHERE b.id = ?
        ");
        $stmt->execute([$batch_id]);
        $batch_details = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$batch_details) {
            $is_error = true;
            $message = "Batch not found.";
        }
    } catch (PDOException $e) {
        $is_error = true;
        $message = "Database error fetching batch details: " . $e->getMessage();
        error_log("Enrollment Request Fetch Error: " . $e->getMessage());
    }
}
?>

<div class="w-full max-w-2xl 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">
            Confirm Enrollment
        </h1>
    </div>

    <?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>
        <div class="text-center">
             <a href="index.php?page=student_dashboard" class="text-blue-600 hover:underline">Go back to courses</a>
        </div>
    <?php else: ?>
        <div class="bg-gray-50 p-6 rounded-lg border border-gray-200 mb-6">
            <h2 class="text-2xl font-bold text-gray-800 mb-4">You are enrolling in:</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-gray-700">
                <div>
                    <p class="font-medium text-gray-500">Course Name</p>
                    <p class="text-lg font-semibold text-gray-900"><?php echo htmlspecialchars($batch_details['course_name']); ?></p>
                </div>
                <div>
                    <p class="font-medium text-gray-500">Batch Name</p>
                    <p class="text-lg font-semibold text-gray-900"><?php echo htmlspecialchars($batch_details['batch_name']); ?></p>
                </div>
                <div>
                    <p class="font-medium text-gray-500">Modality</p>
                    <p class="text-lg font-semibold capitalize"><?php echo htmlspecialchars($batch_details['modality']); ?></p>
                </div>
                <div>
                    <p class="font-medium text-gray-500">Start Date</p>
                    <p class="text-lg font-semibold"><?php echo date('M d, Y', strtotime($batch_details['start_date'])); ?></p>
                </div>
                <div class="md:col-span-2">
                    <p class="font-medium text-gray-500">Fees</p>
                    <p class="text-2xl font-bold text-green-700">$<?php echo number_format($batch_details['fees'], 2); ?></p>
                </div>
            </div>
        </div>

        <div id="enrollment-message" class="mb-4 p-3 rounded-md hidden"></div>

        <button id="enroll-button" data-batch-id="<?php echo htmlspecialchars($batch_id); ?>" class="w-full px-6 py-3 bg-blue-600 text-white text-center font-bold rounded-md hover:bg-blue-700 transition duration-300">
            Confirm and Submit Enrollment Request
        </button>

        <a id="payment-link" href="#" class="hidden w-full px-6 py-3 bg-green-600 text-white text-center font-bold rounded-md hover:bg-green-700 transition duration-300">
            Proceed to Payment
        </a>
        
        <p class="text-sm text-center text-gray-500 mt-4">Note: Your enrollment will be submitted as 'pending' and requires admin approval.</p>
    <?php endif; ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const enrollButton = document.getElementById('enroll-button');
        const paymentLink = document.getElementById('payment-link');
        const messageDiv = document.getElementById('enrollment-message');

        if (enrollButton) {
            enrollButton.addEventListener('click', async function() {
                const batchId = this.dataset.batchId;

                // Disable button and show loading state
                this.disabled = true;
                this.textContent = 'Submitting...';
                messageDiv.classList.add('hidden');
                paymentLink.classList.add('hidden'); // Ensure link is hidden initially

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

                    const result = await response.json();

                    messageDiv.textContent = result.message;
                    messageDiv.classList.remove('hidden');

                    if (result.success) {
                        messageDiv.classList.add('bg-green-100', 'text-green-700');
                        messageDiv.classList.remove('bg-red-100', 'text-red-700');
                        this.textContent = 'Request Submitted!';
                        
                        // ✅ Update link to new page with enrollment ID and show it
                        paymentLink.href = `index.php?page=submit_payment_page&enrollment_id=${result.enrollment_id}`;
                        paymentLink.classList.remove('hidden');

                    } else {
                        messageDiv.classList.add('bg-red-100', 'text-red-700');
                        messageDiv.classList.remove('bg-green-100', 'text-green-700');
                        this.textContent = 'Enroll Again';
                        this.disabled = false;
                        if (result.enrollment_id) {
                            // ✅ If already enrolled, provide link to make payment
                            paymentLink.href = `index.php?page=submit_payment_page&enrollment_id=${result.enrollment_id}`;
                            paymentLink.textContent = 'Proceed to Payment';
                            paymentLink.classList.remove('hidden');
                        }
                    }

                } catch (error) {
                    messageDiv.textContent = 'An error occurred. Please try again.';
                    messageDiv.classList.add('bg-red-100', 'text-red-700');
                    messageDiv.classList.remove('hidden');
                    this.textContent = 'Enroll Again';
                    this.disabled = false;
                    console.error('Enrollment API Error:', error);
                }
            });
        }
    });
</script>