<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\IftaQuestion;
use App\Models\IftaReply;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class IftaReplyController extends Controller
{
    public function store(Request $request, IftaQuestion $question): RedirectResponse
    {
        $data = $request->validate([
            'body' => ['required', 'string', 'min:5', 'max:3000'],
        ]);

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

        $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', 'Official reply published.');
    }

    public function update(Request $request, IftaReply $reply): RedirectResponse
    {
        $data = $request->validate([
            'body' => ['required', 'string', 'min:5', 'max:3000'],
            'is_official' => ['nullable', 'boolean'],
            'is_approved' => ['nullable', 'boolean'],
        ]);

        $isOfficial = $request->boolean('is_official');
        $isApproved = $isOfficial || $request->boolean('is_approved');

        $reply->update([
            'body' => $data['body'],
            'is_official' => $isOfficial,
            'is_approved' => $isApproved,
            'approved_at' => $isApproved ? ($reply->approved_at ?? now()) : null,
            'approved_by' => $isApproved ? ($reply->approved_by ?? $request->user()->id) : null,
        ]);

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

        return back()->with('status', 'Reply updated.');
    }

    public function destroy(IftaReply $reply): RedirectResponse
    {
        $reply->delete();

        return back()->with('status', 'Reply deleted.');
    }
}
