<?php

declare(strict_types=1);

session_start();

require_once '../../config.php';

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

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

$conn = getDBConnection();

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

if (!isset($_FILES['csv_file']) || (int) $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {

    echo json_encode(['success'=>false, 'imported'=>0, 'failed'=>0, 'errors'=>['CSV upload failed']]); exit;

}

$handle = fopen((string) $_FILES['csv_file']['tmp_name'], 'rb');

if (!$handle) {

    echo json_encode(['success'=>false, 'imported'=>0, 'failed'=>0, 'errors'=>['Could not read CSV']]); exit;

}

$header = fgetcsv($handle);

$imported = 0;

$failed = 0;

$errors = [];

$subjectStmt = $conn->prepare("SELECT id FROM subjects WHERE subject_code = ? LIMIT 1");

$insertStmt = $conn->prepare(

    "INSERT INTO exam_questions

      (subject_id, class_name, question_type, question, option_a, option_b, option_c, option_d, correct_answer, marks, difficulty, diagram_required, diagram_spec)

     VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"

);

while (($row = fgetcsv($handle)) !== false) {

    if (count(array_filter($row, static fn($v) => trim((string) $v) !== '')) === 0) {

        continue;

    }

    [$subjectCode, $className, $questionType, $question, $optionA, $optionB, $optionC, $optionD, $correctAnswer, $marks, $difficulty, $diagramRequired, $diagramSpec] = array_pad($row, 13, '');

    $subjectCode = trim((string) $subjectCode);

    $className = trim((string) $className);

    $questionType = trim((string) $questionType);

    $question = trim((string) $question);

    $correctAnswer = trim((string) $correctAnswer);

    $marks = max(1, (int) $marks);

    $difficulty = trim((string) $difficulty) !== '' ? trim((string) $difficulty) : 'medium';

    $diagramRequired = (int) (trim((string) ($diagramRequired ?? '')) === '1');

    $diagramSpec = trim((string) ($diagramSpec ?? ''));

    if ($subjectCode === '' || $className === '' || $questionType === '' || $question === '') {

        $failed++;

        $errors[] = 'Missing required fields in CSV row';

        continue;

    }

    $subjectStmt->bind_param('s', $subjectCode);

    $subjectStmt->execute();

    $subjectRow = $subjectStmt->get_result()->fetch_assoc();

    if (!$subjectRow) {

        $failed++;

        $errors[] = "Unknown subject code: {$subjectCode}";

        continue;

    }

    if ($questionType === 'mcq' && $correctAnswer === '') {

        $failed++;

        $errors[] = 'MCQ row missing correct_answer';

        continue;

    }

    if ($questionType !== 'mcq') {

        $optionA = $optionB = $optionC = $optionD = '';

        $correctAnswer = '';

    }

    $subjectId = (int) $subjectRow['id'];

    $insertStmt->bind_param('issssssssisis', $subjectId, $className, $questionType, $question, $optionA, $optionB, $optionC, $optionD, $correctAnswer, $marks, $difficulty, $diagramRequired, $diagramSpec);

    if ($insertStmt->execute()) {

        $imported++;

    } else {

        $failed++;

        $errors[] = $insertStmt->error;

    }

}

fclose($handle);

$subjectStmt->close();

$insertStmt->close();

echo json_encode(['success'=>true, 'imported'=>$imported, 'failed'=>$failed, 'errors'=>$errors]);

