<?php

namespace App\Livewire\Website;

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

#[Layout('layouts.app')]
#[Title('الشركاء')]
class PartnerManager extends Component
{
    public bool $showForm = false;
    public ?int $editingId = null;

    public string $name = '';
    public string $name_en = '';
    public string $website_url = '';
    public bool $is_active = true;

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

    public function create(): void
    {
        $this->reset(['name', 'name_en', 'website_url', 'is_active', 'editingId']);
        $this->is_active = true;
        $this->showForm = true;
    }

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

        $this->editingId = $id;
        $this->name = $partner->name;
        $this->name_en = $partner->name_en ?? '';
        $this->website_url = $partner->website_url ?? '';
        $this->is_active = $partner->is_active;
        $this->showForm = true;
    }

    public function save(): void
    {
        $this->validate([
            'name' => 'required|string|max:255',
            'website_url' => 'nullable|url|max:500',
        ]);

        $data = [
            'name' => $this->name,
            'name_en' => $this->name_en ?: null,
            'website_url' => $this->website_url ?: null,
            'is_active' => $this->is_active,
        ];

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

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

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

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