<?php
// submit_payment_page.php
// This page allows students to upload a payment slip and details for a pending enrollment.

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

$enrollment_id = $_GET['enrollment_id'] ?? null;
$enrollment_details = null;
$message = '';
$is_error = false;

// Check if a valid enrollment ID is provided.
if (!$enrollment_id || !is_numeric($enrollment_id)) {
    $is_error = true;
    $message = "Invalid enrollment ID. Please go back to your dashboard.";
} else {
    try {
        // Fetch the enrollment details to show the student what they are paying for.
        // Also fetch the latest payment details if they exist.
        $stmt = $pdo->prepare("
            SELECT
                ce.id,
                ce.status,
                b.batch_name,
                b.fees,
                c.course_name,
                p.payment_amount,
                p.slip_path
            FROM course_enrollments ce
            JOIN batches b ON ce.batch_id = b.id
            JOIN courses c ON b.course_id = c.id
            LEFT JOIN payments p ON ce.id = p.enrollment_id
            WHERE ce.id = ? AND ce.student_id = ?
            ORDER BY p.upload_date DESC
            LIMIT 1
        ");
        $stmt->execute([$enrollment_id, $_SESSION['user_id']]);
        $enrollment_details = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$enrollment_details) {
            $is_error = true;
            $message = "Enrollment record not found or you are not authorized to view it.";
        } elseif ($enrollment_details['status'] === 'enrolled') {
            $message = "You are already fully enrolled in this course. You do not need to submit a payment.";
            $is_error = true;
        } elseif ($enrollment_details['status'] === 'payment_uploaded') {
            $message = "You have already submitted a payment slip. It is pending admin approval.";
            $is_error = true;
        }

    } catch (PDOException $e) {
        $is_error = true;
        $message = "Database error fetching enrollment details: " . $e->getMessage();
        error_log("Payment Page Fetch Error: " . $e->getMessage());
    }
}
?>

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

    <?php if (!empty($message)): ?>
        <div id="status-message" class="mb-6 p-4 rounded-md text-center text-lg <?php echo $is_error ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'; ?>">
            <?php echo $message; ?>
        </div>
        <div class="text-center">
            <a href="index.php?page=student_dashboard" class="text-blue-600 hover:underline">Go back to dashboard</a>
        </div>
    <?php else: ?>
        <div class="bg-gray-50 p-6 rounded-lg border border-gray-200 mb-6">
            <h3 class="text-xl font-bold text-gray-800 mb-2">Payment for:</h3>
            <p class="text-lg font-semibold text-gray-900"><?php echo htmlspecialchars($enrollment_details['course_name'] . ' - ' . $enrollment_details['batch_name']); ?></p>
            <p class="text-2xl font-bold text-green-700 mt-2">Fees: $<?php echo number_format($enrollment_details['fees'], 2); ?></p>
            
            <?php if ($enrollment_details['status'] === 'payment_uploaded' && $enrollment_details['payment_amount']): ?>
                <hr class="my-4">
                <p class="text-lg font-bold text-gray-800">Last Submitted Payment:</p>
                <p class="text-xl font-bold text-blue-700 mt-2">Amount Paid: $<?php echo number_format($enrollment_details['payment_amount'], 2); ?></p>
                <?php if ($enrollment_details['slip_path']): ?>
                    <p class="mt-2 text-sm text-gray-600">
                        <a href="<?php echo htmlspecialchars($enrollment_details['slip_path']); ?>" target="_blank" class="text-blue-600 hover:underline">View Submitted Slip</a>
                    </p>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <form id="payment-form" action="api/process_payment.php" method="POST" enctype="multipart/form-data" class="space-y-4">
            <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" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label for="slip_number" class="block text-gray-700 text-sm font-semibold mb-2">Slip/Reference Number:</label>
                <input type="text" id="slip_number" name="slip_number" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label for="amount_paid" class="block text-gray-700 text-sm font-semibold mb-2">Amount Paid:</label>
                <input type="number" id="amount_paid" name="amount_paid" required min="0" step="0.01" value="<?php echo htmlspecialchars($enrollment_details['fees']); ?>"
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label for="payment_date" class="block text-gray-700 text-sm font-semibold mb-2">Date of Payment:</label>
                <input type="date" id="payment_date" name="payment_date" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label for="payment_slip" class="block text-gray-700 text-sm font-semibold mb-2">Upload Payment Slip:</label>
                <input type="file" id="payment_slip" name="payment_slip" accept="image/*,.pdf" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div id="submission-message" class="mb-4 p-3 rounded-md hidden"></div>

            <button type="submit" class="w-full py-2 px-4 bg-blue-600 text-white font-semibold rounded-md hover:bg-blue-700 transition duration-300">
                Submit Payment Slip
            </button>
        </form>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('payment-form');
    const messageDiv = document.getElementById('submission-message');

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

            const formData = new FormData(this);
            const submitButton = this.querySelector('button[type="submit"]');

            submitButton.disabled = true;
            submitButton.textContent = 'Submitting...';
            messageDiv.classList.add('hidden');

            try {
                const response = await fetch(this.action, {
                    method: this.method,
                    body: formData
                });

                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');
                    submitButton.textContent = 'Submitted!';
                    
                    // The main fix: Hide the form and show the updated status
                    document.querySelector('.bg-gray-50').innerHTML = `
                        <h3 class="text-xl font-bold text-gray-800 mb-2">Payment for:</h3>
                        <p class="text-lg font-semibold text-gray-900"><?php echo htmlspecialchars($enrollment_details['course_name'] . ' - ' . $enrollment_details['batch_name']); ?></p>
                        <hr class="my-4">
                        <p class="text-lg font-bold text-gray-800">Last Submitted Payment:</p>
                        <p class="text-xl font-bold text-blue-700 mt-2">Amount Paid: $${parseFloat(formData.get('amount_paid')).toFixed(2)}</p>
                        <p class="mt-2 text-sm text-gray-600">Your payment slip has been uploaded and is pending admin approval.</p>
                    `;
                    form.classList.add('hidden');
                } else {
                    messageDiv.classList.add('bg-red-100', 'text-red-700');
                    messageDiv.classList.remove('bg-green-100', 'text-green-700');
                    submitButton.textContent = 'Try Again';
                    submitButton.disabled = false;
                }

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