<?php
require_once 'config.php';
require_admin();

$message = '';

// --- Handle Accept/Decline Actions ---
if (isset($_POST['action'])) {
    $slipId = (int)$_POST['slip_id'];
    $action = $_POST['action']; // 'accept' or 'decline'

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT student_id, pack_id, status FROM slips WHERE id = ?");
        $stmt->execute([$slipId]);
        $slip = $stmt->fetch();

        if ($slip && $slip['status'] === 'pending') {
            $stmt = $pdo->prepare("UPDATE slips SET status = ? WHERE id = ?");
            $stmt->execute([$action, $slipId]);

            if ($action === 'accept') {
                // Grant access to the lesson pack
                $stmt = $pdo->prepare("INSERT INTO student_packs (student_id, pack_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE access_granted_at = NOW()");
                $stmt->execute([$slip['student_id'], $slip['pack_id']]);

                // Log purchase event
                log_analytics($pdo, 'purchase', $slip['student_id'], $slip['pack_id']);

                $message = 'Slip accepted. Student granted access to the lesson pack.';
            } else {
                $message = 'Slip declined.';
            }
        } else {
            $message = 'Slip not found or already processed.';
        }

        $pdo->commit();
    } catch (PDOException $e) {
        $pdo->rollBack();
        $message = 'Transaction failed: ' . $e->getMessage();
    }
}

// --- Fetch All Pending Slip Requests ---
$stmt = $pdo->query("
    SELECT
        s.id AS slip_id,
        s.slip_url,
        s.a_l_year,
        s.created_at,
        -- Changed to fetch student_id instead of concatenating first_name and last_name
        u.id AS student_id,
        lp.title AS pack_name
    FROM slips s
    JOIN users u ON s.student_id = u.id
    JOIN lesson_packs lp ON s.pack_id = lp.id
    WHERE s.status = 'pending'
    ORDER BY s.created_at ASC
");
$slips = $stmt->fetchAll();

require_once 'layouts.php';
render_header('Slip Requests');
render_sidebar($_SESSION['user_role'], basename(__FILE__));
render_topbar('Payment Slip Requests');
?>

<div class="space-y-8">
    <?php if ($message): ?>
        <div class="bg-indigo-100 border-l-4 border-indigo-500 text-indigo-700 p-4 mb-6 rounded-lg" role="alert"><?php echo htmlspecialchars($message); ?></div>
    <?php endif; ?>

    <h2 class="text-2xl font-bold text-gray-900">Pending Requests (<?php echo count($slips); ?>)</h2>
    <div class="bg-white rounded-xl shadow-lg overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <!-- Changed column header from 'Student Name' to 'Student ID' -->
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student ID</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">A/L Year</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lesson Pack</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Slip</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                <?php if ($slips): ?>
                    <?php foreach ($slips as $slip): ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Display student_id instead of student_name -->
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($slip['student_id'] ?? 'N/A'); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($slip['a_l_year'] ?? ''); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-semibold"><?php echo htmlspecialchars($slip['pack_name'] ?? ''); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo date('M d, H:i', strtotime($slip['created_at'] ?? '')); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <button onclick="openSlipPreview('<?php echo htmlspecialchars($slip['slip_url'] ?? ''); ?>')" class="text-indigo-600 hover:text-indigo-900 mr-2"><i class="fa-solid fa-eye"></i> View</button>
                                <a href="<?php echo htmlspecialchars($slip['slip_url'] ?? ''); ?>" download class="text-gray-600 hover:text-gray-900"><i class="fa-solid fa-download"></i> Download</a>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <form method="POST" action="sliprequests.php" class="inline-block space-x-2">
                                    <input type="hidden" name="slip_id" value="<?php echo $slip['slip_id']; ?>">
                                    <button type="submit" name="action" value="accept" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 font-semibold text-xs transition duration-150">Accept</button>
                                    <button type="submit" name="action" value="decline" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 font-semibold text-xs transition duration-150">Decline</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="6" class="px-6 py-4 text-center text-gray-500">No pending slip requests.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Slip Preview Modal -->
<div id="slip-preview-modal" class="fixed inset-0 bg-gray-900 bg-opacity-75 hidden items-center justify-center p-4 z-50">
    <div class="bg-white rounded-xl shadow-2xl max-w-4xl w-full h-5/6 p-6">
        <div class="flex justify-between items-center border-b pb-3 mb-4">
            <h3 class="text-xl font-bold text-gray-900">Payment Slip Preview</h3>
            <button onclick="document.getElementById('slip-preview-modal').classList.add('hidden')" class="text-gray-400 hover:text-gray-600">
                <i class="fa-solid fa-times text-2xl"></i>
            </button>
        </div>
        <div class="h-[90%] w-full flex items-center justify-center">
            <img id="slip-image" src="" alt="Payment Slip" class="max-h-full max-w-full object-contain rounded-lg shadow-lg">
            <!-- Alternative for PDF: could use an iframe here -->
        </div>
    </div>
</div>

<script>
    function openSlipPreview(url) {
        const modal = document.getElementById('slip-preview-modal');
        const img = document.getElementById('slip-image');
        
        // Simple check to determine if it's likely a PDF or image
        if (url.toLowerCase().endsWith('.pdf')) {
            // For PDF, you might use an iframe, but image is simpler for mock-up.
            // For production, you'd handle rendering PDF or showing a PDF viewer.
            // For simplicity, we'll just show the placeholder for non-images
            img.src = 'https://placehold.co/600x400/94a3b8/ffffff?text=PDF+Preview+Unavailable';
        } else {
            img.src = url;
        }

        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }
</script>

<?php render_main_content_end(); ?>