<?php
declare(strict_types=1);

/**
 * Fetch the current Exam Format Profile for a subject × class, if any.
 */
require_once __DIR__ . '/_json_guard.php';
session_start();
require_once '../../config.php';
require_once dirname(__DIR__) . '/lib/exam_format_profile_schema.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$conn = getDBConnection();
if (!$conn instanceof mysqli) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}
ensureExamFormatProfileTables($conn);

$subjectId = (int) ($_GET['subject_id'] ?? $_POST['subject_id'] ?? 0);
$className = trim((string) ($_GET['class_name'] ?? $_POST['class_name'] ?? ''));

if ($subjectId <= 0 || $className === '') {
    echo json_encode(['success' => false, 'message' => 'Subject and class are required']);
    exit;
}

$stmt = $conn->prepare(
    'SELECT p.*, u.full_name AS uploader_name
     FROM exam_format_profiles p
     LEFT JOIN users u ON u.id = p.uploaded_by
     WHERE p.subject_id = ? AND p.class_name = ?
     LIMIT 1'
);
$stmt->bind_param('is', $subjectId, $className);
$stmt->execute();
$profile = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$profile) {
    echo json_encode(['success' => true, 'exists' => false]);
    exit;
}

$rawText    = (string) ($profile['raw_extracted_text'] ?? '');
$decodedSpec = json_decode((string) ($profile['format_spec_json'] ?? ''), true);

echo json_encode([
    'success'           => true,
    'exists'            => true,
    'profile_id'        => (int) $profile['id'],
    'source_type'       => $profile['source_type'],
    'original_filename' => $profile['original_filename'],
    'status'            => $profile['status'],
    'status_note'       => $profile['status_note'],
    'summary_text'      => $profile['summary_text'],
    'format_spec'       => is_array($decodedSpec) ? $decodedSpec : null,
    'raw_word_count'    => str_word_count($rawText),
    'raw_text_preview'  => mb_substr($rawText, 0, 600),
    'uploaded_by'       => $profile['uploader_name'],
    'updated_at'        => $profile['updated_at'],
]);
