<?php
// submit_payment.php
// This page allows a student to submit their payment details and upload a slip.

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

// Redirect if not logged in OR not 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';

$message = '';
$is_error = false;
$course_id = $_GET['course_id'] ?? null;
$student_id = $_SESSION['user_id'];
$enrollment_id = null;
$course_name = '';
$course_fees = 0;
$has_pending_enrollment = false;

// Check if a valid course_id is provided and retrieve enrollment details
if (!$course_id || !is_numeric($course_id)) {
    $message = "Invalid course ID provided.";
    $is_error = true;
} else {
    try {
        // Fetch course details and check if there's a pending enrollment for this student/course
        $stmt = $pdo->prepare("
            SELECT
                ce.id AS enrollment_id,
                ce.status,
                c.course_name,
                c.fees
            FROM course_enrollments ce
            JOIN courses c ON ce.course_id = c.id
            WHERE ce.student_id = ? AND ce.course_id = ?
            LIMIT 1
        ");
        $stmt->execute([$student_id, $course_id]);
        $enrollment_info = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$enrollment_info) {
            $message = "You do not have a pending enrollment for this course.";
            $is_error = true;
        } elseif ($enrollment_info['status'] === 'enrolled') {
            $message = "You are already enrolled in '<strong>" . htmlspecialchars($enrollment_info['course_name']) . "</strong>'.";
            $is_error = true;
        } elseif ($enrollment_info['status'] === 'payment_uploaded') {
            $message = "You have already submitted payment details for '<strong>" . htmlspecialchars($enrollment_info['course_name']) . "</strong>'. It is pending admin verification.";
            $is_error = true;
        } elseif ($enrollment_info['status'] === 'rejected') {
            $message = "Your previous enrollment for '<strong>" . htmlspecialchars($enrollment_info['course_name']) . "</strong>' was rejected. Please re-enroll if you wish to try again.";
            $is_error = true;
        } else { // Status is 'pending'
            $has_pending_enrollment = true;
            $enrollment_id = $enrollment_info['enrollment_id'];
            $course_name = $enrollment_info['course_name'];
            $course_fees = $enrollment_info['fees'];
        }

    } catch (PDOException $e) {
        $message = "Database error: " . $e->getMessage();
        $is_error = true;
        error_log("Submit Payment page load error: " . $e->getMessage());
    }
}

// Initial values for form for sticky effect or pre-fill
$bank_name = '';
$branch_code = '';
$slip_number = '';
$payment_date = date('Y-m-d'); // Default to current date
$payment_amount = $course_fees; // Default to course fees
?>

<div class="w-full max-w-2xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <h2 class="text-2xl font-bold mb-6 text-center text-gray-800">Submit Payment for Course</h2>

    <?php if (!empty($message)): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg
            <?php echo $is_error ? 'bg-red-100 text-red-700 border border-red-200' : 'bg-blue-50 text-blue-700 border border-blue-200'; ?>">
            <?php echo $message; ?>
            <p class="mt-2"><a href="index.php?page=student_dashboard" class="text-blue-600 hover:underline">Back to Dashboard</a></p>
        </div>
    <?php endif; ?>

    <?php if ($has_pending_enrollment && !$is_error): ?>
        <p class="text-gray-700 text-lg mb-4 text-center">
            Course: <span class="font-semibold text-blue-700"><?php echo htmlspecialchars($course_name); ?></span><br>
            Amount Due: <span class="font-bold text-green-700">$<?php echo number_format($course_fees, 2); ?></span>
        </p>

        <form id="paymentForm" action="api/submit_payment.php" method="POST" enctype="multipart/form-data" class="space-y-5">
            <input type="hidden" name="enrollment_id" value="<?php echo htmlspecialchars($enrollment_id); ?>">

            <div>
                <label for="bank_name" class="block text-gray-700 text-sm font-semibold mb-2">Bank Name:</label>
                <input type="text" id="bank_name" name="bank_name" value="<?php echo htmlspecialchars($bank_name); ?>" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>

            <div>
                <label for="branch_code" class="block text-gray-700 text-sm font-semibold mb-2">Branch Code (Optional):</label>
                <input type="text" id="branch_code" name="branch_code" value="<?php echo htmlspecialchars($branch_code); ?>"
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>

            <div>
                <label for="slip_number" class="block text-gray-700 text-sm font-semibold mb-2">Payment Slip Number:</label>
                <input type="text" id="slip_number" name="slip_number" value="<?php echo htmlspecialchars($slip_number); ?>" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>

            <div>
                <label for="payment_date" class="block text-gray-700 text-sm font-semibold mb-2">Payment Date:</label>
                <input type="date" id="payment_date" name="payment_date" value="<?php echo htmlspecialchars($payment_date); ?>" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>

            <div>
                <label for="payment_amount" class="block text-gray-700 text-sm font-semibold mb-2">Payment Amount ($):</label>
                <input type="number" id="payment_amount" name="payment_amount" value="<?php echo htmlspecialchars($payment_amount); ?>" step="0.01" min="0" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>

            <div>
                <label for="payment_slip" class="block text-gray-700 text-sm font-semibold mb-2">Upload Payment Slip (Image):</label>
                <input type="file" id="payment_slip" name="payment_slip" accept="image/*" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
            </div>

            <button type="submit" id="submitPaymentButton"
                    class="w-full py-3 px-6 bg-indigo-600 text-white font-bold text-lg rounded-md hover:bg-indigo-700 transition duration-300 shadow-lg">
                Submit Payment Details
            </button>
        </form>
        <div id="paymentFormMessage" class="mt-4 text-center text-sm font-semibold"></div>
    <?php endif; ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const paymentForm = document.getElementById('paymentForm');
        const submitPaymentButton = document.getElementById('submitPaymentButton');
        const paymentFormMessageDiv = document.getElementById('paymentFormMessage');

        if (paymentForm) {
            paymentForm.addEventListener('submit', async function(event) {
                event.preventDefault(); // Prevent default form submission

                const formData = new FormData(this); // Get all form data, including file
                submitPaymentButton.disabled = true;
                paymentFormMessageDiv.innerHTML = '<span class="text-blue-600">Submitting payment details...</span>';

                try {
                    const response = await fetch(this.action, { // Use form's action attribute
                        method: 'POST',
                        body: formData // FormData automatically sets 'Content-Type: multipart/form-data'
                    });

                    const data = await response.json();

                    if (data.success) {
                        paymentFormMessageDiv.innerHTML = '<span class="text-green-600">' + data.message + '</span>';
                        // Optionally redirect or update UI after successful submission
                        setTimeout(() => {
                            window.location.href = 'index.php?page=student_dashboard'; // Redirect to dashboard
                        }, 2000);
                    } else {
                        paymentFormMessageDiv.innerHTML = '<span class="text-red-600">' + (data.message || 'Payment submission failed. Please try again.') + '</span>';
                        submitPaymentButton.disabled = false; // Re-enable button on error
                    }
                } catch (error) {
                    console.error('Error during payment submission:', error);
                    paymentFormMessageDiv.innerHTML = '<span class="text-red-600">Network error or server issue during payment submission.</span>';
                    submitPaymentButton.disabled = false; // Re-enable button on network error
                }
            });
        }
    });
</script>
