<?php
declare(strict_types=1);

/**
 * List learning_materials for a class × subject as a checkbox fragment, for
 * the exam paper generator's material picker. Deliberately reads
 * learning_materials (not ai_study_materials) — that is the table
 * getLearningMaterialsWithContent() actually consumes at generation time, so
 * the ids a teacher checks here are the same ids the generator resolves.
 */
session_start();
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    exit('<div class="alert alert-danger">Unauthorized</div>');
}

require_once '../config.php';
require_once '../lib/exam_utils.php';

$className = trim((string) ($_POST['class'] ?? ''));
$subjectId  = (int) ($_POST['subject'] ?? 0);

if ($className === '' || $subjectId <= 0) {
    echo '<div class="alert alert-info py-2 small mb-0">Select a class and subject to view materials.</div>';
    exit;
}

$materials = getLearningMaterialsWithContent($className, $subjectId);

if (empty($materials)) {
    echo '<div class="alert alert-info py-2 small mb-0">No study materials uploaded yet for this class and subject. '
       . '<a href="../upload_materials.php" target="_blank">Upload one</a>.</div>';
    exit;
}

foreach ($materials as $material) {
    $hasContent = trim((string) ($material['content_preview'] ?? '')) !== '';
    $badge = $hasContent
        ? '<span class="badge bg-success">Ready</span>'
        : '<span class="badge bg-warning text-dark">No extracted text</span>';
    echo '<div class="form-check border rounded p-2 mb-2">'
       . '<input class="form-check-input" type="checkbox" name="materials[]" value="' . (int) $material['id'] . '" id="mat_' . (int) $material['id'] . '"' . ($hasContent ? ' checked' : '') . '>'
       . '<label class="form-check-label d-flex justify-content-between align-items-center w-100" for="mat_' . (int) $material['id'] . '">'
       . '<span>' . htmlspecialchars((string) ($material['title'] ?? 'Untitled')) . ' <span class="text-muted small">(' . htmlspecialchars((string) ($material['material_type'] ?? '')) . ')</span></span>'
       . $badge
       . '</label>'
       . '</div>';
}
