<?php
// manage_enrollment.php
// This page allows administrators and instructors to view details of a specific
// enrollment request, including payment details, and to approve or reject it.

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

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

require_once 'config/database.php';

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

$current_user_id = $_SESSION['user_id'];
$current_user_role = $_SESSION['user_role'];

if (!$enrollment_id || !is_numeric($enrollment_id)) {
    $message = "Invalid enrollment ID provided.";
    $is_error = true;
} else {
    try {
        // Fetch enrollment details, joining with users (student), batches, courses, and payments.
        // The join to batches is crucial now as it contains instructor, fees, and dates.
        $stmt = $pdo->prepare("
            SELECT
                ce.id AS enrollment_id,
                ce.enrollment_date,
                ce.status,
                s.id AS student_id,
                s.username AS student_username,
                s.full_name AS student_full_name,
                s.email AS student_email,
                b.id AS batch_id,
                b.batch_name,
                b.instructor_id,
                b.fees AS batch_fees,
                b.start_date AS batch_start_date,
                b.duration AS batch_duration,
                b.description AS batch_description,
                u_inst.full_name AS instructor_full_name,
                c.course_name,
                p.id AS payment_id,
                p.bank_name,
                p.branch_code,
                p.slip_number,
                p.payment_date,
                p.payment_amount,
                p.slip_path,
                p.upload_date AS payment_upload_date
            FROM course_enrollments ce
            JOIN users s ON ce.student_id = s.id
            JOIN batches b ON ce.batch_id = b.id
            JOIN courses c ON b.course_id = c.id
            JOIN users u_inst ON b.instructor_id = u_inst.id
            LEFT JOIN payments p ON ce.id = p.enrollment_id
            WHERE ce.id = ?
            LIMIT 1
        ");
        $stmt->execute([$enrollment_id]);
        $enrollment_details = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$enrollment_details) {
            $message = "Enrollment request not found.";
            $is_error = true;
        } else {
            // Authorization check: Instructor can only manage enrollments for their own batches.
            // Admins can manage all.
            if ($current_user_role === 'instructor' && $enrollment_details['instructor_id'] != $current_user_id) {
                $message = "You are not authorized to manage this enrollment. It belongs to a batch managed by another instructor.";
                $is_error = true;
                $enrollment_details = null; // Clear details if unauthorized
            }
        }

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

<div class="w-full max-w-4xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <h2 class="text-3xl font-bold mb-6 text-center text-gray-800">Manage Enrollment Request</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-4"><a href="index.php?page=admin_dashboard" class="text-blue-600 hover:underline">Back to Admin Dashboard</a></p>
        </div>
    <?php endif; ?>

    <?php if ($enrollment_details): ?>
        <div class="flex justify-between items-start mb-6 pb-4 border-b border-gray-200">
            <h3 class="text-2xl font-semibold text-gray-900">
                Enrollment ID: <?php echo htmlspecialchars($enrollment_details['enrollment_id']); ?>
            </h3>
            <span class="px-3 py-1 rounded-full text-sm font-semibold
                <?php
                $status_class = '';
                switch ($enrollment_details['status']) {
                    case 'pending':
                        $status_class = 'bg-yellow-200 text-yellow-800';
                        break;
                    case 'payment_uploaded':
                        $status_class = 'bg-orange-200 text-orange-800';
                        break;
                    case 'enrolled':
                        $status_class = 'bg-green-200 text-green-800';
                        break;
                    case 'rejected':
                        $status_class = 'bg-red-200 text-red-800';
                        break;
                }
                echo $status_class;
                ?>">
                Status: <?php echo ucwords(str_replace('_', ' ', htmlspecialchars($enrollment_details['status']))); ?>
            </span>
        </div>

        <div class="mb-8 p-4 border border-gray-200 rounded-md bg-gray-50">
            <h4 class="text-xl font-bold text-gray-800 mb-4">Student Information</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-gray-700">
                <p><span class="font-semibold">Full Name:</span> <?php echo htmlspecialchars($enrollment_details['student_full_name']); ?></p>
                <p><span class="font-semibold">Username:</span> <?php echo htmlspecialchars($enrollment_details['student_username']); ?></p>
                <p><span class="font-semibold">Email:</span> <?php echo htmlspecialchars($enrollment_details['student_email']); ?></p>
                <p><span class="font-semibold">Requested On:</span> <?php echo date('M d, Y H:i', strtotime($enrollment_details['enrollment_date'])); ?></p>
            </div>
        </div>

        <div class="mb-8 p-4 border border-gray-200 rounded-md bg-gray-50">
            <h4 class="text-xl font-bold text-gray-800 mb-4">Course & Batch Information</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-gray-700">
                <p><span class="font-semibold">Course Name:</span> <?php echo htmlspecialchars($enrollment_details['course_name']); ?></p>
                <p><span class="font-semibold">Batch Name:</span> <?php echo htmlspecialchars($enrollment_details['batch_name']); ?></p>
                <p><span class="font-semibold">Instructor:</span> <?php echo htmlspecialchars($enrollment_details['instructor_full_name']); ?></p>
                <p><span class="font-semibold">Fees:</span> <span class="text-green-700 font-bold">$<?php echo number_format($enrollment_details['batch_fees'], 2); ?></span></p>
                <p><span class="font-semibold">Duration:</span> <?php echo htmlspecialchars($enrollment_details['batch_duration']); ?></p>
                <p><span class="font-semibold">Start Date:</span> <?php echo date('M d, Y', strtotime($enrollment_details['batch_start_date'])); ?></p>
            </div>
            <p class="text-gray-700 mt-4"><span class="font-semibold">Description:</span> <?php echo nl2br(htmlspecialchars($enrollment_details['batch_description'])); ?></p>
        </div>

        <?php if ($enrollment_details['status'] === 'payment_uploaded' || $enrollment_details['status'] === 'enrolled'): ?>
            <div class="mb-8 p-4 border border-blue-300 rounded-md bg-blue-50">
                <h4 class="text-xl font-bold text-blue-800 mb-4">Payment Information</h4>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-blue-700">
                    <p><span class="font-semibold">Bank Name:</span> <?php echo htmlspecialchars($enrollment_details['bank_name']); ?></p>
                    <p><span class="font-semibold">Branch Code:</span> <?php echo htmlspecialchars($enrollment_details['branch_code'] ?: 'N/A'); ?></p>
                    <p><span class="font-semibold">Slip Number:</span> <?php echo htmlspecialchars($enrollment_details['slip_number']); ?></p>
                    <p><span class="font-semibold">Payment Date:</span> <?php echo date('M d, Y', strtotime($enrollment_details['payment_date'])); ?></p>
                    <p><span class="font-semibold">Paid Amount:</span> <span class="text-green-800 font-bold">$<?php echo number_format($enrollment_details['payment_amount'], 2); ?></span></p>
                    <p><span class="font-semibold">Uploaded On:</span> <?php echo date('M d, Y H:i', strtotime($enrollment_details['payment_upload_date'])); ?></p>
                </div>
                <?php if (!empty($enrollment_details['slip_path'])): ?>
                    <div class="mt-4 text-center">
                        <h5 class="text-lg font-semibold text-blue-800 mb-2">Payment Slip:</h5>
                        <a href="<?php echo htmlspecialchars($enrollment_details['slip_path']); ?>" target="_blank" class="inline-block border-2 border-blue-400 p-2 rounded-md hover:border-blue-600 transition duration-300">
                            <img src="<?php echo htmlspecialchars($enrollment_details['slip_path']); ?>" alt="Payment Slip" class="max-w-xs h-auto rounded-md shadow-md" onerror="this.onerror=null;this.src='https://placehold.co/200x150/cccccc/333333?text=Image+Not+Found';" />
                        </a>
                        <p class="mt-2 text-sm text-gray-600">Click image to view full size.</p>
                    </div>
                <?php else: ?>
                    <p class="mt-4 text-center text-red-600">No payment slip uploaded.</p>
                <?php endif; ?>
            </div>
        <?php elseif ($enrollment_details['status'] === 'pending'): ?>
            <div class="mb-8 p-4 border border-yellow-300 rounded-md bg-yellow-50 text-center">
                <p class="text-yellow-800 font-semibold">Payment details are yet to be submitted by the student.</p>
            </div>
        <?php endif; ?>

        <?php if ($enrollment_details['status'] === 'pending' || $enrollment_details['status'] === 'payment_uploaded'): ?>
            <div class="mt-8 pt-6 border-t border-gray-200 flex flex-col sm:flex-row justify-center space-y-4 sm:space-y-0 sm:space-x-4">
                <button id="approveButton"
                        data-enrollment-id="<?php echo htmlspecialchars($enrollment_details['enrollment_id']); ?>"
                        class="px-8 py-3 bg-green-600 text-white font-bold text-lg rounded-md hover:bg-green-700 transition duration-300 shadow-lg">
                    Approve Enrollment
                </button>
                <button id="rejectButton"
                        data-enrollment-id="<?php echo htmlspecialchars($enrollment_details['enrollment_id']); ?>"
                        class="px-8 py-3 bg-red-600 text-white font-bold text-lg rounded-md hover:bg-red-700 transition duration-300 shadow-lg">
                    Reject Enrollment
                </button>
            </div>
            <div id="statusUpdateMessage" class="mt-4 text-center text-sm font-semibold"></div>
        <?php else: ?>
            <div class="mt-8 pt-6 border-t border-gray-200 text-center text-gray-600">
                This enrollment is already <strong><?php echo htmlspecialchars($enrollment_details['status']); ?></strong>. No further action needed here.
            </div>
        <?php endif; ?>

        <div class="mt-8 text-center">
            <a href="index.php?page=admin_dashboard" class="px-6 py-3 bg-gray-200 text-gray-700 font-semibold rounded-md hover:bg-gray-300 transition duration-300">
                Back to Admin Dashboard
            </a>
        </div>

    <?php endif; ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const approveButton = document.getElementById('approveButton');
        const rejectButton = document.getElementById('rejectButton');
        const statusUpdateMessageDiv = document.getElementById('statusUpdateMessage');

        function sendStatusUpdate(enrollmentId, newStatus) {
            statusUpdateMessageDiv.innerHTML = '<span class="text-blue-600">Updating status...</span>';
            if (approveButton) approveButton.disabled = true;
            if (rejectButton) rejectButton.disabled = true;

            fetch('api/update_enrollment_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ enrollment_id: enrollmentId, new_status: newStatus })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    statusUpdateMessageDiv.innerHTML = '<span class="text-green-600">' + data.message + ' Redirecting...</span>';
                    setTimeout(() => {
                        window.location.href = 'index.php?page=admin_dashboard'; // Redirect back to dashboard
                    }, 2000);
                } else {
                    statusUpdateMessageDiv.innerHTML = '<span class="text-red-600">' + (data.message || 'Failed to update status.') + '</span>';
                    if (approveButton) approveButton.disabled = false;
                    if (rejectButton) rejectButton.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error updating status:', error);
                statusUpdateMessageDiv.innerHTML = '<span class="text-red-600">Network error or server issue.</span>';
                if (approveButton) approveButton.disabled = false;
                if (rejectButton) rejectButton.disabled = false;
            });
        }

        if (approveButton) {
            approveButton.addEventListener('click', function() {
                const enrollmentId = this.dataset.enrollmentId;
                sendStatusUpdate(enrollmentId, 'enrolled');
            });
        }

        if (rejectButton) {
            rejectButton.addEventListener('click', function() {
                const enrollmentId = this.dataset.enrollmentId;
                sendStatusUpdate(enrollmentId, 'rejected');
            });
        }
    });
</script>