<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SimulationQuestion;
use App\Models\InterviewCategory;
use Illuminate\Http\Request;

class SimulationQuestionController extends Controller
{
    public function index(Request $request)
    {
        $categoryId = $request->get('category_id');
        $categories = InterviewCategory::orderBy('name')->get();

        $questions = SimulationQuestion::with('category')
            ->when($categoryId, fn($q) => $q->where('interview_category_id', $categoryId))
            ->ordered()
            ->paginate(20)
            ->withQueryString();

        $selectedCategory = $categoryId ? InterviewCategory::find($categoryId) : null;

        return view('admin.simulation-questions.index', compact('questions', 'categories', 'selectedCategory', 'categoryId'));
    }

    public function create(Request $request)
    {
        $categories = InterviewCategory::orderBy('name')->get();
        $selectedCategoryId = $request->get('category_id');

        return view('admin.simulation-questions.create', compact('categories', 'selectedCategoryId'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'interview_category_id' => 'required|exists:interview_categories,id',
            'question'              => 'required|string|max:2000',
            'expected_keywords'     => 'nullable|string',
            'sample_answer'         => 'nullable|string|max:5000',
            'points'                => 'required|integer|min:1|max:100',
            'order'                 => 'required|integer|min:0',
        ]);

        // expected_keywords: virgülle ayrılmış metin → JSON array
        $validated['expected_keywords'] = $this->parseKeywords($request->input('expected_keywords', ''));

        SimulationQuestion::create($validated);

        return redirect()
            ->route('admin.simulation-questions.index', ['category_id' => $validated['interview_category_id']])
            ->with('success', 'Soru başarıyla eklendi.');
    }

    public function edit(SimulationQuestion $simulationQuestion)
    {
        $categories = InterviewCategory::orderBy('name')->get();
        $keywordsText = implode(', ', $simulationQuestion->expected_keywords ?? []);

        return view('admin.simulation-questions.edit', compact('simulationQuestion', 'categories', 'keywordsText'));
    }

    public function update(Request $request, SimulationQuestion $simulationQuestion)
    {
        $validated = $request->validate([
            'interview_category_id' => 'required|exists:interview_categories,id',
            'question'              => 'required|string|max:2000',
            'expected_keywords'     => 'nullable|string',
            'sample_answer'         => 'nullable|string|max:5000',
            'points'                => 'required|integer|min:1|max:100',
            'order'                 => 'required|integer|min:0',
        ]);

        $validated['expected_keywords'] = $this->parseKeywords($request->input('expected_keywords', ''));

        $simulationQuestion->update($validated);

        return redirect()
            ->route('admin.simulation-questions.index', ['category_id' => $simulationQuestion->interview_category_id])
            ->with('success', 'Soru başarıyla güncellendi.');
    }

    public function destroy(SimulationQuestion $simulationQuestion)
    {
        $categoryId = $simulationQuestion->interview_category_id;
        $simulationQuestion->delete();

        if (request()->expectsJson()) {
            return response()->json(['success' => true]);
        }

        return redirect()
            ->route('admin.simulation-questions.index', ['category_id' => $categoryId])
            ->with('success', 'Soru silindi.');
    }

    private function parseKeywords(string $raw): array
    {
        if (empty(trim($raw))) {
            return [];
        }

        return array_values(array_filter(
            array_map('trim', explode(',', $raw)),
            fn($k) => $k !== ''
        ));
    }
}
