<?php
// enrollment_verification.php - The VIEW file

// This file is now purely for displaying the HTML content.
// No POST handling or database writes should happen here.

// 1. Setup and Authorization for GET request
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
// Crucial: Only Admin or Instructor should access this page
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['enrollment_id'] ?? null;
$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];
$enrollment = null;
$message = '';
$is_error = false;

// Basic validation for the required ID
if (!$enrollment_id || !is_numeric($enrollment_id)) {
    $message = "Invalid enrollment ID provided.";
    $is_error = true;
}

// 2. Fetch Enrollment Details FIRST
if (!$is_error) {
    try {
        $sql_fetch = "
            SELECT
                ce.id AS enrollment_id, ce.enrollment_date, ce.status, ce.student_id, 
                s.full_name AS student_full_name, s.email AS student_email,
                c.course_name, b.fees AS batch_fees, b.batch_name, b.instructor_id,
                u_inst.full_name AS instructor_name, p.id AS payment_id, p.slip_number, 
                p.bank_name, p.payment_amount, p.slip_path, la.access_end_date, la.lifetime_access
            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
            LEFT JOIN users u_inst ON b.instructor_id = u_inst.id
            LEFT JOIN payments p ON ce.id = p.enrollment_id
            LEFT JOIN lms_access la ON ce.id = la.enrollment_id 
            WHERE ce.id = ?
        ";
        
        if ($user_role === 'instructor') {
            $sql_fetch .= " AND b.instructor_id = ?";
            $params_fetch = [$enrollment_id, $user_id];
        } else {
            $params_fetch = [$enrollment_id];
        }

        $stmt_fetch = $pdo->prepare($sql_fetch);
        $stmt_fetch->execute($params_fetch);
        $enrollment = $stmt_fetch->fetch(PDO::FETCH_ASSOC);

        if (!$enrollment) {
            $message = "Enrollment request not found or you do not have permission to view it.";
            $is_error = true;
        }

    } catch (PDOException $e) {
        $message = "Database error fetching details: " . $e->getMessage();
        $is_error = true;
    }
}

// Get today's date + 1 month for the default date picker value
$default_end_date = date('Y-m-d', strtotime('+1 month'));

?>

<div class="w-full max-w-4xl mx-auto p-6 bg-white rounded-lg shadow-xl">

    <div class="flex justify-between items-center mb-8 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900">
            Enrollment Review #<?php echo htmlspecialchars($enrollment_id); ?>
        </h1>
        <a href="index.php?page=manage_enrollments" class="text-sm font-semibold text-blue-600 hover:text-blue-800 flex items-center">
            <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd"></path></svg>
            Back to Requests
        </a>
    </div>

    <?php if (!empty($message) && !$is_error): ?>
        <div class="mb-6 p-4 rounded-md bg-blue-50 text-blue-700 border border-blue-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if ($is_error): ?>
        <div class="mb-6 p-4 rounded-md bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if ($enrollment): ?>
    
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            
            <div class="p-6 border border-gray-200 rounded-lg bg-gray-50">
                <h3 class="text-xl font-bold mb-4 text-gray-800">Request & Student Info</h3>
                
                <p class="mb-2"><span class="font-semibold text-gray-700">Status:</span> 
                    <span class="px-3 py-1 text-sm font-semibold rounded-full 
                        <?php 
                            if ($enrollment['status'] === 'enrolled') echo 'bg-green-100 text-green-800';
                            else if ($enrollment['status'] === 'rejected') echo 'bg-red-100 text-red-800';
                            else if ($enrollment['status'] === 'payment_uploaded') echo 'bg-orange-100 text-orange-800';
                            else echo 'bg-yellow-100 text-yellow-800';
                        ?>">
                        <?php echo ucwords(str_replace('_', ' ', htmlspecialchars($enrollment['status']))); ?>
                    </span>
                </p>
                <p class="text-sm mb-4"><span class="font-semibold text-gray-700">Requested On:</span> <?php echo date('M d, Y H:i', strtotime($enrollment['enrollment_date'])); ?></p>
                
                <hr class="my-4">

                <h4 class="text-lg font-bold mb-2 text-blue-600">Student Details</h4>
                <div class="space-y-1 text-gray-700 text-sm">
                    <p><span class="font-medium">Name:</span> <?php echo htmlspecialchars($enrollment['student_full_name']); ?></p>
                    <p><span class="font-medium">Email:</span> <?php echo htmlspecialchars($enrollment['student_email']); ?></p>
                    <p><span class="font-medium">Phone:</span> N/A</p>
                </div>
                
                <h4 class="text-lg font-bold my-4 text-blue-600">Course Details</h4>
                <div class="space-y-1 text-gray-700 text-sm">
                    <p><span class="font-medium">Course:</span> <span class="font-bold"><?php echo htmlspecialchars($enrollment['course_name']); ?></span></p>
                    <p><span class="font-medium">Batch:</span> <?php echo htmlspecialchars($enrollment['batch_name']); ?></p>
                    <p><span class="font-medium">Instructor:</span> <?php echo htmlspecialchars($enrollment['instructor_name'] ?: 'TBA'); ?></p>
                    <p><span class="font-medium">Batch Fees:</span> <span class="text-green-700 font-bold">$<?php echo number_format($enrollment['batch_fees'], 2); ?></span></p>
                </div>
            </div>

            <div class="p-6 border border-gray-200 rounded-lg">
                
                <h3 class="text-xl font-bold mb-4 text-gray-800">LMS Access Status</h3>

                <?php if (isset($enrollment['lifetime_access']) || isset($enrollment['access_end_date'])): ?>
                    <div class="p-4 rounded-md 
                        <?php echo ($enrollment['lifetime_access'] == 1) ? 'bg-green-50 border-green-300' : 'bg-blue-50 border-blue-300'; ?>">
                        <p class="font-semibold text-lg mb-1">
                            <?php if ($enrollment['lifetime_access'] == 1): ?>
                                ✅ Lifetime Access Granted
                            <?php else: ?>
                                ⏳ Access Expiry Date
                            <?php endif; ?>
                        </p>
                        <p class="text-sm text-gray-700">
                            <?php 
                            if ($enrollment['lifetime_access'] == 1) {
                                echo "The student has permanent course access.";
                            } elseif (!empty($enrollment['access_end_date'])) {
                                $end_date_time = strtotime($enrollment['access_end_date']);
                                $expiry_text = (time() > $end_date_time) ? 
                                    "<span class='text-red-600 font-bold'>EXPIRED</span> on " : 
                                    "Expires on ";
                                echo $expiry_text . date('F d, Y', $end_date_time);
                            } else {
                                echo "Access record exists but end date is not set (Requires payment update).";
                            }
                            ?>
                        </p>
                    </div>
                <?php else: ?>
                    <div class="p-4 bg-yellow-100 text-yellow-800 border-l-4 border-yellow-500 rounded-md">
                        <p class="font-semibold">LMS Access Not Configured.</p>
                        <p class="text-sm">Access record will be created upon **Approval** with the date you provide.</p>
                    </div>
                <?php endif; ?>

                <h3 class="text-xl font-bold my-4 pt-4 border-t border-gray-200 text-gray-800">Payment Proof</h3>
                
                <?php 
                if (isset($enrollment['payment_id']) && $enrollment['payment_id']): 
                ?>
                    <div class="space-y-2 text-gray-700">
                        <p class="text-lg font-bold text-indigo-700 mb-3">Amount Paid: $<?php echo number_format($enrollment['payment_amount'], 2); ?></p>
                        
                        <?php if (!empty($enrollment['slip_path'])): ?>
                            <p class="text-sm"><span class="font-medium">Bank:</span> <?php echo htmlspecialchars($enrollment['bank_name'] ?? 'N/A'); ?></p>
                            <p class="text-sm"><span class="font-medium">Slip No:</span> <?php echo htmlspecialchars($enrollment['slip_number'] ?? 'N/A'); ?></p>

                            <a href="../<?php echo htmlspecialchars($enrollment['slip_path']); ?>" target="_blank" 
                                class="mt-4 block w-full px-4 py-2 text-center bg-blue-500 text-white font-semibold rounded-md hover:bg-blue-600 transition duration-300">
                                View Payment Slip (Image/PDF)
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="p-4 bg-yellow-100 text-yellow-800 border-l-4 border-yellow-500 rounded-md">
                        <p class="font-semibold">No Payment Slip Uploaded Yet.</p>
                        <p class="text-sm">The student has initiated the enrollment but is yet to submit payment proof.</p>
                    </div>
                <?php endif; ?>
            </div>
            
        </div>
        
        <?php if ($enrollment['status'] === 'pending' || $enrollment['status'] === 'payment_uploaded'): ?>
            <div class="mt-8 pt-6 border-t border-gray-200 flex justify-end space-x-4">
                
                <form id="verificationForm" method="POST" action="index.php?page=enrollment_verification_logic">
                    <input type="hidden" name="enrollment_id" value="<?php echo htmlspecialchars($enrollment_id); ?>">
                    
                    <input type="hidden" name="action" id="action_input" value="">
                    <input type="hidden" name="access_end_date" id="access_end_date" value="">
                    <input type="hidden" name="lifetime_access" id="lifetime_access" value="0">
                    
                    <input type="hidden" name="rejection_reason" id="rejection_reason" value=""> 

                    <button type="button" 
                        onclick="handleRejection();"
                        class="px-6 py-3 bg-red-600 text-white font-semibold rounded-lg hover:bg-red-700 transition duration-300 shadow-md">
                        Reject Enrollment
                    </button>
                    
                    <button type="button" 
                        onclick="handleApproval();"
                        class="px-6 py-3 bg-green-600 text-white font-semibold rounded-lg hover:bg-green-700 transition duration-300 shadow-md">
                        Approve Enrollment
                    </button>
                </form>
            </div>
        <?php else: ?>
            <div class="mt-8 pt-6 border-t border-gray-200">
                    <div class="p-4 rounded-md text-center text-lg bg-blue-50 text-blue-700 border border-blue-200">
                        This enrollment has already been **<?php echo htmlspecialchars(strtoupper($enrollment['status'])); ?>**.
                </div>
            </div>
        <?php endif; ?>

    <?php endif; ?>

    <div id="approvalModal" class="fixed inset-0 bg-gray-600 bg-opacity-75 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <h3 class="text-xl font-bold text-gray-900 mb-4 border-b pb-2">
                Configure Student Access
            </h3>
            
            <p class="text-sm text-gray-600 mb-4">
                Determine the access type based on the student's payment plan.
            </p>

            <div class="space-y-4">
                <div class="flex items-center p-3 border rounded-lg hover:bg-green-50 transition duration-150">
                    <input id="lifetimeCheckbox" type="checkbox" name="lifetime_check" 
                        class="h-5 w-5 text-green-600 border-gray-300 rounded focus:ring-green-500"
                        onchange="toggleAccessDate(this.checked)">
                    <label for="lifetimeCheckbox" class="ml-3 text-base font-medium text-gray-700 cursor-pointer">
                        LIFETIME ACCESS (Full Payment)
                    </label>
                </div>

                <div id="datePickerContainer">
                    <label for="accessEndDateInput" class="block text-sm font-medium text-gray-700 mb-2">
                        Next Payment Due Date (Limited Access)
                    </label>
                    <input type="date" id="accessEndDateInput" 
                        value="<?php echo $default_end_date; ?>"
                        class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                </div>
            </div>

            <div class="mt-6 flex justify-end space-x-3">
                <button type="button" 
                        onclick="document.getElementById('approvalModal').classList.add('hidden')"
                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition duration-150">
                    Cancel
                </button>
                <button type="button" 
                        onclick="submitApprovalForm();"
                        class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition duration-150">
                    Confirm Approval
                </button>
            </div>
        </div>
    </div>
    </div>

<script>
/**
 * Toggles the visibility and required status of the date picker.
 */
function toggleAccessDate(isLifetime) {
    const dateContainer = document.getElementById('datePickerContainer');
    const dateInput = document.getElementById('accessEndDateInput');

    if (isLifetime) {
        // Disable date picker for lifetime access
        dateContainer.classList.add('opacity-50', 'pointer-events-none');
        dateInput.setAttribute('disabled', 'disabled');
        dateInput.removeAttribute('required');
    } else {
        // Enable date picker for limited access
        dateContainer.classList.remove('opacity-50', 'pointer-events-none');
        dateInput.removeAttribute('disabled');
        dateInput.setAttribute('required', 'required');
    }
}

/**
 * Prompts for rejection reason and submits form as reject.
 */
function handleRejection() {
    const confirmReject = confirm("Are you sure you want to REJECT this enrollment? The student will be notified and access denied.");
    if (!confirmReject) return;

    let reason = prompt("Please enter a reason for rejection (this will be sent to the student):");
    
    if (reason === null) {
        alert("Rejection cancelled.");
        return;
    }
    
    document.getElementById('action_input').value = 'reject';
    document.getElementById('rejection_reason').value = reason.trim() || 'No specific reason provided. Please contact administration for details.';
    document.getElementById('verificationForm').submit();
}

/**
 * Shows the new Approval Configuration Modal.
 */
function handleApproval() {
    // Ensure the modal state is clean before showing
    const lifetimeCheckbox = document.getElementById('lifetimeCheckbox');
    lifetimeCheckbox.checked = false; 
    toggleAccessDate(false); // Default to limited access (date visible)
    
    // Show the modal
    document.getElementById('approvalModal').classList.remove('hidden');
}

/**
 * Gathers data from the modal and submits the main form.
 */
function submitApprovalForm() {
    const isLifetime = document.getElementById('lifetimeCheckbox').checked;
    const accessDate = document.getElementById('accessEndDateInput').value;
    const form = document.getElementById('verificationForm');

    // 1. Set the main action
    document.getElementById('action_input').value = 'approve';
    
    // 2. Set the access details
    if (isLifetime) {
        document.getElementById('lifetime_access').value = '1';
        document.getElementById('access_end_date').value = ''; // Clear date if lifetime
    } else {
        // Validation for Limited Access
        if (!accessDate) {
            alert("Please select a valid Next Payment Due Date.");
            return;
        }
        document.getElementById('lifetime_access').value = '0';
        document.getElementById('access_end_date').value = accessDate;
    }

    // 3. Hide the modal and submit
    document.getElementById('approvalModal').classList.add('hidden');
    form.submit();
}

// Initialize state when the page loads
document.addEventListener('DOMContentLoaded', () => {
    // Use 'pointer-events-none' for visual disability on date input
    toggleAccessDate(document.getElementById('lifetimeCheckbox').checked); 
});

</script>