<?php

namespace App\Livewire\Website;

use App\Domain\Website\Models\WebsiteFaq;
use App\Domain\Website\Services\WebsiteCacheService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('الأسئلة الشائعة')]
class FaqManager extends Component
{
    public bool $showForm = false;
    public ?int $editingId = null;

    public string $question = '';
    public string $question_en = '';
    public string $answer = '';
    public string $answer_en = '';
    public bool $is_published = true;

    public function mount(): void
    {
        $this->authorize('settings.manage');
    }

    public function create(): void
    {
        $this->reset(['question', 'question_en', 'answer', 'answer_en', 'is_published', 'editingId']);
        $this->is_published = true;
        $this->showForm = true;
    }

    public function edit(int $id): void
    {
        $faq = WebsiteFaq::find($id);
        if (!$faq) return;

        $this->editingId = $id;
        $this->question = $faq->question;
        $this->question_en = $faq->question_en ?? '';
        $this->answer = $faq->answer;
        $this->answer_en = $faq->answer_en ?? '';
        $this->is_published = $faq->is_published;
        $this->showForm = true;
    }

    public function save(): void
    {
        $this->validate([
            'question' => 'required|string|max:500',
            'answer' => 'required|string|max:2000',
        ]);

        $data = [
            'question' => $this->question,
            'question_en' => $this->question_en ?: null,
            'answer' => $this->answer,
            'answer_en' => $this->answer_en ?: null,
            'is_published' => $this->is_published,
        ];

        if ($this->editingId) {
            WebsiteFaq::find($this->editingId)->update($data);
        } else {
            $data['sort_order'] = WebsiteFaq::max('sort_order') + 1;
            WebsiteFaq::create($data);
        }

        app(WebsiteCacheService::class)->invalidate(app('current_academy')->id);
        $this->showForm = false;
        session()->flash('success', __('تم الحفظ بنجاح'));
    }

    public function delete(int $id): void
    {
        WebsiteFaq::find($id)?->delete();
        app(WebsiteCacheService::class)->invalidate(app('current_academy')->id);
        session()->flash('success', __('تم الحذف'));
    }

    public function render()
    {
        return view('livewire.website.faq-manager', [
            'faqs' => WebsiteFaq::orderBy('sort_order')->get(),
        ]);
    }
}
