<?php

namespace App\Http\Controllers;

use App\Models\IftaQuestion;
use App\Support\SiteContent;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class IftaQuestionController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:180'],
            'category' => ['required', 'string', 'max:80'],
            'body' => ['required', 'string', 'min:20', 'max:4000'],
        ]);

        IftaQuestion::create([
            'user_id' => $request->user()->id,
            'locale' => app()->getLocale(),
            'category' => $data['category'],
            'title' => $data['title'],
            'body' => $data['body'],
            'status' => 'pending',
            'is_approved' => false,
        ]);

        return back()->with('status', SiteContent::ui('question_posted'));
    }

    public function reply(Request $request, IftaQuestion $question): RedirectResponse
    {
        abort_if(! $question->is_approved && ! $request->user()->isAdmin(), 404);

        $data = $request->validate([
            'body' => ['required', 'string', 'min:5', 'max:3000'],
        ]);

        $isOfficial = $request->user()->isAdmin();

        $question->replies()->create([
            'user_id' => $request->user()->id,
            'body' => $data['body'],
            'is_official' => $isOfficial,
            'is_approved' => $isOfficial,
            'approved_at' => $isOfficial ? now() : null,
            'approved_by' => $isOfficial ? $request->user()->id : null,
        ]);

        if ($isOfficial) {
            $question->update([
                'status' => 'answered',
                'is_approved' => true,
                'answered_at' => now(),
                'approved_at' => $question->approved_at ?? now(),
                'approved_by' => $question->approved_by ?? $request->user()->id,
            ]);
        }

        return back()->with('status', SiteContent::ui($isOfficial ? 'official_reply_posted' : 'reply_posted'));
    }
}
