<?php
declare(strict_types=1);

/**
 * Clear the Exam Format Profile for a subject × class.
 *
 * Archives the current profile into exam_format_profile_versions before
 * deleting it, so the sample is never permanently lost. After this,
 * generation for the subject/class reverts to the standard generic rules.
 */
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) ($_POST['subject_id'] ?? 0);
$className = trim((string) ($_POST['class_name'] ?? ''));

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

$stmt = $conn->prepare('SELECT * FROM exam_format_profiles WHERE subject_id = ? AND class_name = ? LIMIT 1');
$stmt->bind_param('is', $subjectId, $className);
$stmt->execute();
$existing = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$existing) {
    echo json_encode(['success' => false, 'message' => 'No format profile found for this subject and class.']);
    exit;
}

$userId = (int) $_SESSION['user_id'];

$archive = $conn->prepare(
    'INSERT INTO exam_format_profile_versions
        (profile_id, subject_id, class_name, source_type, original_filename, stored_filename,
         raw_extracted_text, format_spec_json, summary_text, status, archived_by)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
);
$archive->bind_param(
    'iissssssssi',
    $existing['id'],
    $existing['subject_id'],
    $existing['class_name'],
    $existing['source_type'],
    $existing['original_filename'],
    $existing['stored_filename'],
    $existing['raw_extracted_text'],
    $existing['format_spec_json'],
    $existing['summary_text'],
    $existing['status'],
    $userId
);
$archive->execute();
$archive->close();

if (!empty($existing['stored_filename'])) {
    $path = rtrim(EXAM_UPLOAD_DIR, '/\\') . DIRECTORY_SEPARATOR . 'formats' . DIRECTORY_SEPARATOR . $existing['stored_filename'];
    if (is_file($path)) {
        @unlink($path);
    }
}

$delete = $conn->prepare('DELETE FROM exam_format_profiles WHERE id = ?');
$delete->bind_param('i', $existing['id']);
$delete->execute();
$delete->close();

echo json_encode([
    'success' => true,
    'message' => 'Format profile cleared. Generation will use standard rules until a new sample is uploaded.',
]);
