<?php

header('Content-Type: application/json');

require_once __DIR__ . '/../config/database.php';

$workspace_id = $_POST['workspace_id'] ?? '';
$variants_per_question = isset($_POST['variants_per_question']) ? (int) $_POST['variants_per_question'] : 0;
$selected_questions_json = $_POST['selected_questions_json'] ?? '';

if (empty($workspace_id)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Missing workspace ID.'
    ]);
    exit;
}

if ($variants_per_question < 1 || $variants_per_question > 2) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Variants per question must be 1 or 2.'
    ]);
    exit;
}

if (empty($selected_questions_json)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'No selected questions were provided.'
    ]);
    exit;
}

$selected_questions = json_decode($selected_questions_json, true);

if (!is_array($selected_questions) || count($selected_questions) === 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Selected questions JSON is invalid or empty.'
    ]);
    exit;
}

$required_data_keys = [
    'Question title',
    'Question text',
    'Core condition',
    'Presentation',
    'Skill',
    'Specialty',
    'Summative/Formative',
    'Year'
];

foreach ($selected_questions as $index => $selected_question) {
    if (!is_array($selected_question)) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Selected question payload is invalid at item ' . ($index + 1) . '.'
        ]);
        exit;
    }

    if (!array_key_exists('row_number', $selected_question) || !is_numeric($selected_question['row_number'])) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Selected question payload is invalid at item ' . ($index + 1) . ': row_number is missing or not numeric.'
        ]);
        exit;
    }

    if (!array_key_exists('data', $selected_question) || !is_array($selected_question['data'])) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Selected question payload is invalid at item ' . ($index + 1) . ': data is missing or invalid.'
        ]);
        exit;
    }

    $missing_data_keys = array_values(array_diff($required_data_keys, array_keys($selected_question['data'])));
    if (!empty($missing_data_keys)) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Selected question payload is invalid at item ' . ($index + 1) . ': missing data keys: ' . implode(', ', $missing_data_keys) . '.'
        ]);
        exit;
    }
}

if (count($selected_questions) > 100) {
    echo json_encode([
        'status' => 'error',
        'message' => 'You can select up to 100 questions.'
    ]);
    exit;
}

$total_variants = count($selected_questions) * $variants_per_question;

$job_payload = [
    'job_type' => 'variant',
    'variants_per_question' => $variants_per_question,
    'selected_questions' => $selected_questions
];

$job_payload_json = json_encode($job_payload);

if ($job_payload_json === false) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to encode job payload.'
    ]);
    exit;
}

$sql = "INSERT INTO generation_jobs (
    workspace_id,
    specialty,
    condition_name,
    presentation,
    learning_outcome,
    num_questions,
    questions_completed,
    status,
    skills,
    summative_formative,
    year_level,
    tutor_comments
) VALUES (
    :workspace_id,
    :specialty,
    :condition_name,
    :presentation,
    :learning_outcome,
    :num_questions,
    0,
    'running',
    :skills,
    :summative_formative,
    :year_level,
    :tutor_comments
)";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    'workspace_id' => $workspace_id,
    'specialty' => 'Variant Generation',
    'condition_name' => 'Uploaded RISR Questions',
    'presentation' => 'Variant Batch',
    'learning_outcome' => $job_payload_json,
    'num_questions' => $total_variants,
    'skills' => '',
    'summative_formative' => null,
    'year_level' => null,
    'tutor_comments' => 'Variant generation job'
]);

$job_id = $pdo->lastInsertId();

echo json_encode([
    'status' => 'success',
    'message' => 'Variant generation job created.',
    'job_id' => $job_id,
    'selected_question_count' => count($selected_questions),
    'variants_per_question' => $variants_per_question,
    'total_variants' => $total_variants
]);