<?php
// admin_verify_payments.php
// This page allows administrators and instructors to review and verify
// monthly payment slips uploaded by students.

// 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'; // Assuming this provides a $pdo object

$message = '';
$is_error = false;
$pending_payments = [];

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

try {
    // Base SQL query to fetch payment details and link student, course, and batch.
    $sql_base = "
        SELECT
            mp.id AS monthly_payment_id,
            mp.enrollment_id,
            mp.status,
            mp.paid_amount,
            mp.bank_name,
            mp.branch_code,
            mp.slip_number,
            mp.payment_date,
            mp.slip_path,
            mp.uploaded_at,
            u.full_name AS student_name,
            c.course_name,
            b.batch_name,
            b.fees AS batch_total_fees
        FROM monthly_payments mp
        JOIN course_enrollments ce ON mp.enrollment_id = ce.id
        JOIN users u ON ce.student_id = u.id
        JOIN batches b ON ce.batch_id = b.id
        JOIN courses c ON b.course_id = c.id
        WHERE mp.status = 'uploaded'
    ";

    $params = [];

    // Determine the correct query condition based on the user's role.
    if ($current_user_role === 'admin') {
        // Admins see all pending payments
        $sql = $sql_base . " ORDER BY mp.uploaded_at ASC";
    } else { // instructor
        // Instructors only see payments for batches they are assigned to
        $sql = $sql_base . " AND b.instructor_id = ? ORDER BY mp.uploaded_at ASC";
        $params[] = $current_user_id;
    }
    
    $stmt_payments = $pdo->prepare($sql);
    $stmt_payments->execute($params);
    
    $pending_payments = $stmt_payments->fetchAll(PDO::FETCH_ASSOC);

    if (empty($pending_payments)) {
        $message = "No pending payments to review at this time.";
    }

} catch (PDOException $e) {
    $message = "Database error fetching pending payments: " . $e->getMessage();
    $is_error = true;
    error_log("Admin Verify Payments Fetch Error: " . $e->getMessage());
}
?>

<?php
// admin_verify_payments.php
// This page allows administrators and instructors to review and verify
// monthly payment slips uploaded by students.

// 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'; // Assuming this provides a $pdo object

$message = '';
$is_error = false;
$pending_payments = [];

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

try {
    // Base SQL query to fetch payment details and link student, course, and batch.
    $sql_base = "
        SELECT
            mp.id AS monthly_payment_id,
            mp.enrollment_id,
            mp.status,
            mp.paid_amount,
            mp.bank_name,
            mp.branch_code,
            mp.slip_number,
            mp.payment_date,
            mp.slip_path,
            mp.uploaded_at,
            u.full_name AS student_name,
            c.course_name,
            b.batch_name,
            b.fees AS batch_total_fees
        FROM monthly_payments mp
        JOIN course_enrollments ce ON mp.enrollment_id = ce.id
        JOIN users u ON ce.student_id = u.id
        JOIN batches b ON ce.batch_id = b.id
        JOIN courses c ON b.course_id = c.id
        WHERE mp.status = 'uploaded'
    ";

    $params = [];

    // Determine the correct query condition based on the user's role.
    if ($current_user_role === 'admin') {
        // Admins see all pending payments
        $sql = $sql_base . " ORDER BY mp.uploaded_at ASC";
    } else { // instructor
        // Instructors only see payments for batches they are assigned to
        $sql = $sql_base . " AND b.instructor_id = ? ORDER BY mp.uploaded_at ASC";
        $params[] = $current_user_id;
    }
    
    $stmt_payments = $pdo->prepare($sql);
    $stmt_payments->execute($params);
    
    $pending_payments = $stmt_payments->fetchAll(PDO::FETCH_ASSOC);

    if (empty($pending_payments)) {
        $message = "No pending payments to review at this time.";
    }

} catch (PDOException $e) {
    $message = "Database error fetching pending payments: " . $e->getMessage();
    $is_error = true;
    error_log("Admin Verify Payments Fetch Error: " . $e->getMessage());
}
?>

<div class="w-full max-w-7xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <h2 class="text-3xl font-bold mb-6 text-center text-gray-800">Review Student Payments</h2>

    <div id="paymentOverallMessage" class="mb-4 mt-2 text-center text-sm font-semibold"></div>

    <?php if (!empty($message) && !$is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg 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 text-center text-lg bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if (!empty($pending_payments)): ?>
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border-collapse border border-gray-200 rounded-lg overflow-hidden">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Student</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Course / Batch</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Paid Amount</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Bank Details</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Slip No.</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Payment Date</th>
                        <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Uploaded On</th>
                        <th class="py-3 px-4 text-center text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($pending_payments as $payment): ?>
                        <tr class="hover:bg-gray-50 border-b border-gray-200 last:border-b-0" data-payment-id="<?php echo htmlspecialchars($payment['monthly_payment_id']); ?>">
                            <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($payment['student_name']); ?></td>
                            <td class="py-3 px-4 text-sm text-gray-800">
                                <strong><?php echo htmlspecialchars($payment['course_name']); ?></strong><br>
                                <span class="text-xs text-gray-500"><?php echo htmlspecialchars($payment['batch_name']); ?></span>
                            </td>
                            <td class="py-3 px-4 text-sm text-green-700 font-semibold">Rs. <?php echo number_format($payment['paid_amount'], 2); ?></td>
                            <td class="py-3 px-4 text-sm text-gray-800">
                                <?php echo htmlspecialchars($payment['bank_name']); ?>
                                <?php echo !empty($payment['branch_code']) ? ' (Branch: ' . htmlspecialchars($payment['branch_code']) . ')' : ''; ?>
                            </td>
                            <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($payment['slip_number']); ?></td>
                            <td class="py-3 px-4 text-sm text-gray-800"><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                            <td class="py-3 px-4 text-sm text-gray-800"><?php echo date('M d, Y h:i A', strtotime($payment['uploaded_at'])); ?></td>
                            <td class="py-3 px-4 text-center text-sm whitespace-nowrap">
                                <button type="button" class="view-slip-btn bg-blue-500 text-white px-3 py-1 rounded-md text-xs hover:bg-blue-600 mr-2 transition duration-300"
                                        data-slip-path="<?php echo htmlspecialchars($payment['slip_path']); ?>">
                                    View Slip
                                </button>
                                <button type="button" class="verify-payment-btn bg-green-600 text-white px-3 py-1 rounded-md text-xs hover:bg-green-700 mr-2 transition duration-300"
                                        data-payment-id="<?php echo htmlspecialchars($payment['monthly_payment_id']); ?>">
                                    Verify
                                </button>
                                <button type="button" class="reject-payment-btn bg-red-500 text-white px-3 py-1 rounded-md text-xs hover:bg-red-600 transition duration-300"
                                        data-payment-id="<?php echo htmlspecialchars($payment['monthly_payment_id']); ?>">
                                    Reject
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </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>
</div>

<div id="viewSlipModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden z-50">
    <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-lg mx-4">
        <h3 class="text-xl font-bold mb-4 text-center">Payment Slip</h3>
        <div class="text-center mb-4">
            <img id="slipImageView" src="" alt="Payment Slip" class="max-w-full h-auto rounded-md shadow-md mx-auto" onerror="this.onerror=null;this.src='https://placehold.co/400x300/e0e0e0/333333?text=Image+Not+Found';" />
        </div>
        <div class="flex justify-center">
            <button type="button" id="closeViewSlipModal" class="px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400">Close</button>
        </div>
    </div>
</div>

<div id="verifyPaymentModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden z-50">
    <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-md mx-4">
        <h3 class="text-xl font-bold mb-4 text-green-700">Verify Payment & Set Access</h3>
        <form id="verifyPaymentForm" class="space-y-4">
            <input type="hidden" id="verify_payment_id" name="payment_id">

            <div id="dateInputGroup">
                <label for="access_end_date" class="block text-gray-700 text-sm font-semibold mb-2">Next Payment Due Date (Access End Date):</label>
                <input type="date" id="access_end_date" name="access_end_date" required
                        class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500">
                <p class="text-xs text-gray-500 mt-1">Student access will expire on this date.</p>
            </div>

            <div class="flex items-center">
                <input type="checkbox" id="lifetime_access" name="lifetime_access" value="1" class="h-4 w-4 text-green-600 border-gray-300 rounded focus:ring-green-500">
                <label for="lifetime_access" class="ml-2 block text-sm text-gray-900 font-medium">Grant **LIFETIME** Access (No future payment expected)</label>
            </div>

            <div id="verifyPaymentMessage" class="mt-4 text-center text-sm font-semibold"></div>

            <div class="flex justify-end space-x-3 pt-4">
                <button type="button" id="cancelVerify" class="px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400">Cancel</button>
                <button type="submit" id="confirmVerify" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">Confirm Verification</button>
            </div>
        </form>
    </div>
</div>

<div id="rejectPaymentModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden z-50">
    <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-md mx-4">
        <h3 class="text-xl font-bold mb-4">Reject Payment</h3>
        <form id="rejectPaymentForm" class="space-y-4">
            <input type="hidden" id="reject_payment_id" name="payment_id">
            <div>
                <label for="reject_notes" class="block text-gray-700 text-sm font-semibold mb-2">Reason for Rejection (Optional but recommended):</label>
                <textarea id="reject_notes" name="admin_notes" rows="4"
                            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500"
                            placeholder="e.g., Incorrect amount, Unclear slip, Duplicate payment"></textarea>
            </div>
            <div class="flex justify-end space-x-3">
                <button type="button" id="cancelReject" class="px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400">Cancel</button>
                <button type="submit" id="confirmReject" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700">Confirm Rejection</button>
            </div>
        </form>
        <div id="rejectPaymentMessage" class="mt-4 text-center text-sm font-semibold"></div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // --- Existing Elements ---
        const viewSlipModal = document.getElementById('viewSlipModal');
        const slipImageView = document.getElementById('slipImageView');
        const closeViewSlipModalButton = document.getElementById('closeViewSlipModal');

        const rejectPaymentModal = document.getElementById('rejectPaymentModal');
        const rejectPaymentForm = document.getElementById('rejectPaymentForm');
        const rejectPaymentIdInput = document.getElementById('reject_payment_id');
        const rejectPaymentMessageDiv = document.getElementById('rejectPaymentMessage');
        const cancelRejectButton = document.getElementById('cancelReject');
        const confirmRejectButton = document.getElementById('confirmReject');

        const paymentOverallMessageDiv = document.getElementById('paymentOverallMessage');

        // --- New Elements for Verify Modal ---
        const verifyPaymentModal = document.getElementById('verifyPaymentModal');
        const verifyPaymentForm = document.getElementById('verifyPaymentForm');
        const verifyPaymentIdInput = document.getElementById('verify_payment_id');
        const accessEndDateInput = document.getElementById('access_end_date');
        const lifetimeAccessCheckbox = document.getElementById('lifetime_access');
        const dateInputGroup = document.getElementById('dateInputGroup');
        const verifyPaymentMessageDiv = document.getElementById('verifyPaymentMessage');
        const cancelVerifyButton = document.getElementById('cancelVerify');
        const confirmVerifyButton = document.getElementById('confirmVerify');
        
        // Function to display overall messages
        function displayOverallMessage(message, isError = false) {
            paymentOverallMessageDiv.textContent = message;
            paymentOverallMessageDiv.className = 'mb-4 mt-2 p-2 rounded-md text-center text-sm font-semibold';
            if (isError) {
                paymentOverallMessageDiv.classList.add('bg-red-100', 'text-red-700', 'border', 'border-red-200');
            } else {
                paymentOverallMessageDiv.classList.add('bg-green-100', 'text-green-700', 'border', 'border-green-200');
            }
        }
        
        // Clear overall message when any action is initiated
        function clearOverallMessage() {
            paymentOverallMessageDiv.textContent = '';
            paymentOverallMessageDiv.className = 'mb-4 mt-2 text-center text-sm font-semibold'; // Reset to default invisible
        }

        // -----------------------------------------------------------
        // 1. View Slip Functionality
        // -----------------------------------------------------------
        document.querySelectorAll('.view-slip-btn').forEach(button => {
            button.addEventListener('click', function() {
                clearOverallMessage();
                const slipPath = this.dataset.slipPath;
                if (slipPath) {
                    // NOTE: You might need to adjust the path based on your server's public structure
                    const fullPath = slipPath.startsWith('public') ? slipPath : 'public/uploads/slips/' + slipPath.replace('../', '');
                    slipImageView.src = fullPath;
                    viewSlipModal.classList.remove('hidden');
                } else {
                    displayOverallMessage("No slip path available.", true);
                }
            });
        });

        if (closeViewSlipModalButton) {
            closeViewSlipModalButton.addEventListener('click', function() {
                viewSlipModal.classList.add('hidden');
                slipImageView.src = '';
            });
        }
        
        // -----------------------------------------------------------
        // 2. Verify Payment Functionality (Show Modal)
        // -----------------------------------------------------------
        document.querySelectorAll('.verify-payment-btn').forEach(button => {
            button.addEventListener('click', function() {
                clearOverallMessage();
                const paymentId = this.dataset.paymentId;
                
                verifyPaymentIdInput.value = paymentId;
                accessEndDateInput.value = ''; // Clear previous date
                lifetimeAccessCheckbox.checked = false; // Uncheck lifetime
                verifyPaymentMessageDiv.textContent = ''; // Clear modal message
                dateInputGroup.classList.remove('hidden'); // Ensure date field is visible
                accessEndDateInput.required = true;

                verifyPaymentModal.classList.remove('hidden');
            });
        });

        // Toggle Date Input based on Lifetime Checkbox
        lifetimeAccessCheckbox.addEventListener('change', function() {
            if (this.checked) {
                dateInputGroup.classList.add('hidden');
                accessEndDateInput.required = false;
                accessEndDateInput.value = ''; // Clear date if lifetime is checked
            } else {
                dateInputGroup.classList.remove('hidden');
                accessEndDateInput.required = true;
            }
        });

        // Verify Payment Form Submission
        if (verifyPaymentForm) {
            verifyPaymentForm.addEventListener('submit', async function(event) {
                event.preventDefault();
                
                const paymentId = verifyPaymentIdInput.value;
                const isLifetime = lifetimeAccessCheckbox.checked;
                let accessEndDate = accessEndDateInput.value;

                if (!isLifetime && !accessEndDate) {
                    verifyPaymentMessageDiv.innerHTML = '<span class="text-red-600">Please select a due date or check Lifetime Access.</span>';
                    return;
                }

                // Prepare the data payload
                let actionData = {
                    access_end_date: isLifetime ? null : accessEndDate,
                    lifetime_access: isLifetime ? 1 : 0
                };

                confirmVerifyButton.disabled = true;
                verifyPaymentMessageDiv.innerHTML = '<span class="text-blue-600">Verifying payment...</span>';

                await sendPaymentAction(paymentId, 'verified', null, actionData);
                confirmVerifyButton.disabled = false; // Re-enable if sendPaymentAction fails/doesn't reload
            });
        }

        // Cancel Verify Modal
        if (cancelVerifyButton) {
            cancelVerifyButton.addEventListener('click', function() {
                verifyPaymentModal.classList.add('hidden');
            });
        }
        
        // -----------------------------------------------------------
        // 3. Reject Payment Functionality
        // -----------------------------------------------------------
        document.querySelectorAll('.reject-payment-btn').forEach(button => {
            button.addEventListener('click', function() {
                clearOverallMessage();
                const paymentId = this.dataset.paymentId;
                rejectPaymentIdInput.value = paymentId;
                rejectPaymentForm.reset(); // Clear form fields
                rejectPaymentMessageDiv.textContent = '';
                rejectPaymentModal.classList.remove('hidden');
            });
        });

        // Reject Payment Form Submission
        if (rejectPaymentForm) {
            rejectPaymentForm.addEventListener('submit', async function(event) {
                event.preventDefault();
                confirmRejectButton.disabled = true;
                rejectPaymentMessageDiv.innerHTML = '<span class="text-blue-600">Rejecting payment...</span>';

                const paymentId = rejectPaymentIdInput.value;
                const adminNotes = document.getElementById('reject_notes').value;

                await sendPaymentAction(paymentId, 'rejected', adminNotes);
                confirmRejectButton.disabled = false; // Re-enable if sendPaymentAction fails/doesn't reload
            });
        }

        // Cancel Reject Modal
        if (cancelRejectButton) {
            cancelRejectButton.addEventListener('click', function() {
                rejectPaymentModal.classList.add('hidden');
                rejectPaymentForm.reset();
            });
        }

        // -----------------------------------------------------------
        // 4. Centralized Action API Function
        // -----------------------------------------------------------
        async function sendPaymentAction(paymentId, action, adminNotes = '', extraData = {}) {
            let apiUrl = 'api/verify_payment.php'; // Ensure this file exists and handles the logic
            let successMessage = '';
            let failureMessage = '';
            let loadingMessage = '';
            let modalToClose = null;

            if (action === 'verified') {
                loadingMessage = 'Verifying payment and setting access date...';
                successMessage = 'Payment verified and access set successfully! Reloading...';
                failureMessage = 'Failed to verify payment.';
                modalToClose = verifyPaymentModal;
            } else if (action === 'rejected') {
                loadingMessage = 'Rejecting payment...';
                successMessage = 'Payment rejected successfully! Reloading...';
                failureMessage = 'Failed to reject payment.';
                modalToClose = rejectPaymentModal;
            } else {
                displayOverallMessage('Invalid action.', true);
                return;
            }

            // Display loading in the overall message area (only visible if the modal is hidden)
            if (action === 'verified') {
                modalToClose.classList.add('hidden');
            }
            displayOverallMessage(loadingMessage, false);
            
            // Construct the final data payload
            let bodyData = {
                payment_id: paymentId,
                action: action,
                admin_notes: adminNotes,
                ...extraData
            };

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(bodyData)
                });

                const data = await response.json();
                
                // Determine where to show the in-modal message for failure
                const msgDiv = (action === 'rejected') ? rejectPaymentMessageDiv : verifyPaymentMessageDiv;

                if (data.success) {
                    displayOverallMessage(successMessage, false);
                    
                    if (modalToClose) modalToClose.classList.add('hidden');

                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    // Failure: Display error in the appropriate modal/area
                    const errorMessage = data.message || failureMessage;
                    
                    if (action === 'verified') {
                        // For verification failure, put the error in the overall message area
                        displayOverallMessage(errorMessage, true);
                    } else {
                        // For rejection failure, display the error back in the modal
                        msgDiv.innerHTML = '<span class="text-red-600">' + errorMessage + '</span>';
                    }
                }
            } catch (error) {
                console.error('Network error or server issue:', error);
                const msgDiv = (action === 'rejected') ? rejectPaymentMessageDiv : verifyPaymentMessageDiv;
                msgDiv.innerHTML = '<span class="text-red-600">Network error or server issue. Please try again.</span>';
                
                if (action === 'verified') {
                    // For verification network error, show it in the overall message area
                    displayOverallMessage("Network error or server issue. Please try again.", true);
                }
            }
        }
    });
</script>