<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: import.php');
    exit;
}

try {
    // Check if file was uploaded
    if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Please select a valid CSV file');
    }

    $file = $_FILES['csv_file']['tmp_name'];
    $defaultCourseId = !empty($_POST['default_course']) ? intval($_POST['default_course']) : null;
    $skipDuplicates = isset($_POST['skip_duplicates']);
    $autoApprove = isset($_POST['auto_approve']);

    // Validate file type
    $fileType = mime_content_type($file);
    if ($fileType !== 'text/csv' && $fileType !== 'text/plain') {
        throw new Exception('Please upload a valid CSV file');
    }

    // Open and read CSV
    $handle = fopen($file, 'r');
    if (!$handle) {
        throw new Exception('Unable to read the uploaded file');
    }

    // Read header row
    $header = fgetcsv($handle);
    if (!$header) {
        throw new Exception('CSV file appears to be empty');
    }

    // Convert headers to lowercase for case-insensitive matching
    $header = array_map('strtolower', array_map('trim', $header));

    // Required columns
    $requiredColumns = ['title', 'content', 'question_type'];
    foreach ($requiredColumns as $col) {
        if (!in_array($col, $header)) {
            throw new Exception("Required column '$col' is missing from CSV");
        }
    }

    $db->beginTransaction();

    $imported = 0;
    $skipped = 0;
    $errors = [];

    // Process each row
    while (($row = fgetcsv($handle)) !== false) {
        try {
            // Create associative array from header and row
            $data = array_combine($header, $row);
            if (!$data) continue; // Skip malformed rows

            // Trim all values
            $data = array_map('trim', $data);

            // Skip empty rows
            if (empty($data['title']) || empty($data['content']) || empty($data['question_type'])) {
                continue;
            }

            // Check for duplicates if requested
            if ($skipDuplicates) {
                $stmt = $db->prepare("SELECT id FROM questions WHERE title = ? AND instructor_id = ?");
                $stmt->execute([$data['title'], $userId]);
                if ($stmt->fetch()) {
                    $skipped++;
                    continue;
                }
            }

            // Validate question type
            $validTypes = ['mcq_single', 'mcq_multiple', 'true_false', 'essay', 'short_answer', 'matching', 'code', 'fill_blanks'];
            if (!in_array($data['question_type'], $validTypes)) {
                throw new Exception("Invalid question type: {$data['question_type']}");
            }

            // Set defaults
            $difficulty = isset($data['difficulty']) && in_array($data['difficulty'], ['easy', 'medium', 'hard'])
                ? $data['difficulty'] : 'medium';
            $points = isset($data['points']) && is_numeric($data['points']) ? floatval($data['points']) : 1.0;

            // Handle category
            $categoryId = null;
            if (!empty($data['category_name'])) {
                // Try to find existing category
                $stmt = $db->prepare("SELECT id FROM question_categories WHERE name = ?");
                $stmt->execute([$data['category_name']]);
                $category = $stmt->fetch();

                if ($category) {
                    $categoryId = $category['id'];
                } else {
                    // Create new category
                    $categorySlug = strtolower(str_replace(' ', '-', preg_replace('/[^A-Za-z0-9\s]/', '', $data['category_name'])));
                    $stmt = $db->prepare("INSERT INTO question_categories (name, slug) VALUES (?, ?)");
                    $stmt->execute([$data['category_name'], $categorySlug]);
                    $categoryId = $db->lastInsertId();
                }
            }

            // Prepare metadata and other fields
            $metadata = [];
            $hints = [];
            if (!empty($data['hints'])) {
                $hints = array_map('trim', explode(',', $data['hints']));
                $hints = array_filter($hints);
            }

            $status = $autoApprove ? 'approved' : 'draft';
            $reviewStatus = $autoApprove ? 'approved' : 'not_submitted';

            // Insert question
            $stmt = $db->prepare("
                INSERT INTO questions (
                    title, content, question_type, difficulty, points,
                    category_id, course_id, instructor_id, explanation,
                    hints, metadata, status, review_status, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");

            $stmt->execute([
                $data['title'],
                $data['content'],
                $data['question_type'],
                $difficulty,
                $points,
                $categoryId,
                $defaultCourseId,
                $userId,
                $data['explanation'] ?? '',
                json_encode($hints),
                json_encode($metadata),
                $status,
                $reviewStatus
            ]);

            $imported++;

        } catch (Exception $e) {
            $errors[] = "Row " . ($imported + $skipped + count($errors) + 2) . ": " . $e->getMessage();
        }
    }

    fclose($handle);

    $db->commit();

    // Set result message
    $message = "Import completed! Imported: $imported questions";
    if ($skipped > 0) $message .= ", Skipped: $skipped duplicates";
    if (!empty($errors)) $message .= ". Errors: " . count($errors);

    $_SESSION['success_message'] = $message;

    if (!empty($errors)) {
        $_SESSION['import_errors'] = $errors;
    }

    header('Location: index.php');
    exit;

} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    $_SESSION['error_message'] = 'Import failed: ' . $e->getMessage();
    header('Location: import.php');
    exit;
}
?>