<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\IftaQuestion;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class IftaQuestionController extends Controller
{
    public function index(): View
    {
        return view('admin.questions.index', [
            'questions' => IftaQuestion::with([
                'user',
                'replies' => fn ($query) => $query->with('user')->oldest(),
            ])->latest()->paginate(15),
        ]);
    }

    public function update(Request $request, IftaQuestion $question): RedirectResponse
    {
        $data = $request->validate([
            'status' => ['required', Rule::in(['pending', 'open', 'answered', 'closed'])],
            'category' => ['required', 'string', 'max:80'],
            'is_approved' => ['nullable', 'boolean'],
        ]);

        $isApproved = $request->boolean('is_approved');
        $status = $data['status'];

        if ($isApproved && $status === 'pending') {
            $status = 'open';
        }

        if (! $isApproved && $status === 'open') {
            $status = 'pending';
        }

        $question->update([
            'status' => $status,
            'category' => $data['category'],
            'is_approved' => $isApproved,
            'approved_at' => $isApproved ? ($question->approved_at ?? now()) : null,
            'approved_by' => $isApproved ? ($question->approved_by ?? $request->user()->id) : null,
            'answered_at' => $status === 'answered' ? ($question->answered_at ?? now()) : null,
        ]);

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

    public function destroy(IftaQuestion $question): RedirectResponse
    {
        $question->delete();

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