<?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'];

// Get filter parameters (same as index.php)
$search = $_GET['search'] ?? '';
$type_filter = $_GET['type'] ?? '';
$difficulty_filter = $_GET['difficulty'] ?? '';
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? '';
$course_filter = $_GET['course'] ?? '';

// Build query (same as index.php but without pagination)
$query = "
    SELECT q.*, qc.name as category_name, c.title as course_title,
           GROUP_CONCAT(DISTINCT qt.name) as tag_names
    FROM questions q
    LEFT JOIN question_categories qc ON q.category_id = qc.id
    LEFT JOIN courses c ON q.course_id = c.id
    LEFT JOIN question_tag_assignments qta ON q.id = qta.question_id
    LEFT JOIN question_tags qt ON qta.tag_id = qt.id
    WHERE q.instructor_id = ?
";

$params = [$userId];

if (!empty($search)) {
    $query .= " AND (q.title LIKE ? OR q.content LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($type_filter)) {
    $query .= " AND q.question_type = ?";
    $params[] = $type_filter;
}

if (!empty($difficulty_filter)) {
    $query .= " AND q.difficulty = ?";
    $params[] = $difficulty_filter;
}

if (!empty($category_filter)) {
    $query .= " AND q.category_id = ?";
    $params[] = $category_filter;
}

if (!empty($status_filter)) {
    $query .= " AND q.status = ?";
    $params[] = $status_filter;
}

if (!empty($course_filter)) {
    $query .= " AND q.course_id = ?";
    $params[] = $course_filter;
}

$query .= " GROUP BY q.id ORDER BY q.created_at DESC";

// Get questions
$stmt = $db->prepare($query);
$stmt->execute($params);
$questions = $stmt->fetchAll();

// Set headers for CSV download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=questions_export_' . date('Y-m-d_H-i-s') . '.csv');

// Create output stream
$output = fopen('php://output', 'w');

// Write CSV header
fputcsv($output, [
    'title',
    'content',
    'question_type',
    'difficulty',
    'points',
    'time_limit',
    'category_name',
    'course_title',
    'tags',
    'explanation',
    'hints',
    'status',
    'created_at'
]);

// Write question data
foreach ($questions as $question) {
    // Decode JSON fields
    $hints = json_decode($question['hints'], true);
    $hintsString = is_array($hints) ? implode(', ', $hints) : '';

    $tags = $question['tag_names'] ? $question['tag_names'] : '';

    fputcsv($output, [
        $question['title'],
        $question['content'],
        $question['question_type'],
        $question['difficulty'],
        $question['points'],
        $question['time_limit'],
        $question['category_name'],
        $question['course_title'],
        $tags,
        $question['explanation'],
        $hintsString,
        $question['status'],
        $question['created_at']
    ]);
}

fclose($output);
exit;
?>