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

if (is_admin()) {
    header('Location: dashboard.php');
    exit();
}

$studentId = $_SESSION['user_id'];
$message = '';

// Handle Slip Upload
if (isset($_POST['upload_slip'])) {
    $packId = $_POST['pack_id'];
    $aLYear = $_POST['a_l_year'];

    // Basic file upload handling (In a real app, use a dedicated file storage service)
    $slipFile = $_FILES['payment_slip'];

    if ($slipFile['error'] === UPLOAD_ERR_OK) {
        $uploadDir = 'uploads/slips/';
        if (!is_dir($uploadDir)) { mkdir($uploadDir, 0777, true); }

        // Secure file naming
        $fileExtension = pathinfo($slipFile['name'], PATHINFO_EXTENSION);
        $fileName = uniqid('slip_') . '.' . $fileExtension;
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($slipFile['tmp_name'], $targetPath)) {
            try {
                // Check for existing pending slip for this pack
                $stmt = $pdo->prepare("SELECT id FROM slips WHERE student_id = ? AND pack_id = ? AND status = 'pending'");
                $stmt->execute([$studentId, $packId]);
                if ($stmt->fetch()) {
                    $message = 'You already have a pending slip for this lesson pack.';
                } else {
                    $stmt = $pdo->prepare("INSERT INTO slips (student_id, pack_id, a_l_year, slip_url, status) VALUES (?, ?, ?, ?, 'pending')");
                    // Store the relative URL to access the file later
                    $stmt->execute([$studentId, $packId, $aLYear, $targetPath]);
                    $message = 'Payment slip uploaded successfully! It is now pending admin review.';
                }
            } catch (PDOException $e) {
                $message = 'Error submitting slip: ' . $e->getMessage();
            }
        } else {
            $message = 'Error moving uploaded file.';
        }
    } else {
        $message = 'Error uploading file. Please try again. Error Code: ' . $slipFile['error'];
    }
}

// Fetch all lesson packs
$stmt = $pdo->prepare("SELECT id, title, description, thumbnail_url, price FROM lesson_packs ORDER BY id DESC");
$stmt->execute();
$packs = $stmt->fetchAll();

// Fetch student's A/L Year
$stmt = $pdo->prepare("SELECT a_l_year FROM users WHERE id = ?");
$stmt->execute([$studentId]);
$studentALYear = $stmt->fetchColumn();

// Fetch packs student already has access to
$stmt = $pdo->prepare("SELECT pack_id FROM student_packs WHERE student_id = ?");
$stmt->execute([$studentId]);
$grantedPacks = array_column($stmt->fetchAll(), 'pack_id');

require_once 'layouts.php';
render_header('Buy Classes');
render_sidebar($_SESSION['user_role'], basename(__FILE__));
render_topbar('Lesson Store');
?>

<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-4 rounded-lg" role="alert">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>
        <div class="flex items-center mb-6">
            <img src="buy.gif" alt="Classes Icon" class="w-8 h-8 mr-3" />
            <h2 class="text-2xl font-extrabold text-gray-900">Buy Classes</h2>
        </div>
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php if ($packs): ?>
            <?php foreach ($packs as $pack):
                $isGranted = in_array($pack['id'], $grantedPacks);
            ?>
                <!-- MODIFIED CARD STRUCTURE TO MATCH IMAGE -->
                <div class="bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition duration-300 flex flex-col">
                    <!-- Image (Top Half - Assumed to contain the stylized graphic) -->
                    <div class="relative w-full h-56"> <!-- Taller height for the graphic -->
                        <img src="<?php echo htmlspecialchars($pack['thumbnail_url']); ?>" alt="<?php echo htmlspecialchars($pack['title']); ?>" class="w-full h-full object-cover">
                    </div>

                    <!-- Details Body (Bottom Half) -->
                    <div class="p-4 flex flex-col flex-grow">
                        <!-- Class Type Label (The small pink label in the image) -->
                        <div class="text-xs font-semibold uppercase tracking-wider text-pink-600 mb-2">
                            Class
                        </div>

                        <!-- Title and Price -->
                        <div class="flex justify-between items-start mb-2">
                            <h3 class="text-lg font-bold text-gray-900 leading-tight pr-2">
                                <?php echo htmlspecialchars($pack['title']); ?>
                            </h3>
                            <!-- Price formatted without decimals, as seen in the image -->
                            <p class="text-xl font-extrabold text-green-600 whitespace-nowrap">
                                Rs. <?php echo number_format($pack['price'], 0); ?>
                            </p>
                        </div>

                        <!-- Description (Compact Sinhala description line) -->
                        <p class="text-gray-600 text-xs line-clamp-2 mb-3 h-8">
                            <?php echo htmlspecialchars($pack['description']); ?>
                        </p>

                        <!-- Meta Bar & Button (The bottom row in the image) -->
                        <div class="mt-auto flex justify-between items-center text-sm border-t pt-3 border-gray-100">
                            <!-- Left Side: Icons (Duration and Video/Zoom) -->
                            <div class="flex items-center text-gray-500 space-x-3">
                                <span class="flex items-center text-xs">
                                    <i class="fa-regular fa-clock mr-1 text-gray-400"></i>
                                    30 Days
                                </span>
                                <span class="flex items-center text-xs">
                                    <i class="fa-solid fa-video mr-1 text-gray-400"></i>
                                    Zoom + Video
                                </span>
                            </div>

                            <!-- Right Side: Button/Status -->
                            <?php if ($isGranted): ?>
                                <span class="text-green-600 font-semibold text-xs py-1 px-2 border border-green-200 bg-green-50 rounded-full">
                                    <i class="fa-solid fa-check mr-1"></i> Access Granted
                                </span>
                            <?php else: ?>
                                <button onclick="openSlipModal(<?php echo $pack['id']; ?>, '<?php echo htmlspecialchars(addslashes($pack['title'])); ?>')"
                                        class="py-2 px-3 text-xs bg-indigo-600 text-white rounded-full hover:bg-indigo-700 transition duration-150 font-semibold shadow-md">
                                    Upload Slip
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="md:col-span-3 bg-yellow-100 p-6 rounded-xl shadow-lg text-yellow-800">
                <p>No lesson packs are currently available for purchase.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Upload Slip Modal -->
<div id="slip-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-lg w-full p-8">
        <div class="flex justify-between items-center mb-6 border-b pb-3">
            <h3 class="text-2xl font-bold text-gray-900">Upload Payment Slip</h3>
            <button onclick="closeSlipModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fa-solid fa-times text-2xl"></i>
            </button>
        </div>
        <form method="POST" action="buyclass.php" enctype="multipart/form-data" class="space-y-4">
            <input type="hidden" name="pack_id" id="modal-pack-id">

            <div>
                <label class="block text-sm font-medium text-gray-700">Lesson Pack</label>
                <p id="modal-pack-title" class="mt-1 text-lg font-semibold text-indigo-600"></p>
            </div>

            <div>
                <label for="a_l_year" class="block text-sm font-medium text-gray-700">A/L Year</label>
                <input id="a_l_year" name="a_l_year" type="text" value="<?php echo htmlspecialchars($studentALYear); ?>" readonly
                        class="mt-1 block w-full px-4 py-2 bg-gray-100 border border-gray-300 rounded-lg shadow-sm">
            </div>

            <div>
                <label for="payment_slip" class="block text-sm font-medium text-gray-700">Payment Slip (Image/PDF)</label>
                <input id="payment_slip" name="payment_slip" type="file" required accept="image/*,application/pdf"
                        class="mt-1 block w-full text-sm text-gray-900 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100">
            </div>

            <button type="submit" name="upload_slip" class="w-full py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold transition duration-150">
                Submit Slip for Review
            </button>
        </form>
    </div>
</div>

<script>
    // JavaScript for Modal functionality
    const slipModal = document.getElementById('slip-modal');
    const modalPackId = document.getElementById('modal-pack-id');
    const modalPackTitle = document.getElementById('modal-pack-title');

    function openSlipModal(packId, packTitle) {
        modalPackId.value = packId;
        modalPackTitle.textContent = packTitle;
        slipModal.classList.remove('hidden');
        slipModal.classList.add('flex');
    }

    function closeSlipModal() {
        slipModal.classList.add('hidden');
        slipModal.classList.remove('flex');
        // Clear file input on close for security and clean state
        document.getElementById('payment_slip').value = ''; 
    }
</script>

<?php render_main_content_end(); ?>