<?php

namespace App\Http\Controllers;

use App\Services\ExamPdfExportService;
use Illuminate\Http\Request;

class QuestionPreviewController extends Controller
{
    /**
     * 显示预览工具页面
     */
    public function index()
    {
        return view('tools.question-preview');
    }

    /**
     * 生成 PDF 预览
     */
    public function generatePdf(Request $request)
    {
        $request->validate([
            'stem' => 'required|string',
            'options' => 'nullable|array',
            'answer' => 'nullable|string',
            'solution' => 'nullable|string',
        ]);

        try {
            $service = app(ExamPdfExportService::class);

            // 过滤空选项
            $options = array_filter($request->input('options', []), fn($v) => !empty($v));

            // 构建题目数据数组
            $questionData = [
                'stem' => $request->input('stem'),
                'options' => $options,
                'answer' => $request->input('answer'),
                'solution' => $request->input('solution'),
            ];

            $result = $service->generatePreviewPdf($questionData);

            if (!$result || empty($result['url'])) {
                throw new \Exception('PDF 生成失败');
            }

            return response()->json([
                'success' => true,
                'url' => $result['url'],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
