<?php

namespace App\Livewire\Admin;

use App\Models\EmailTemplateType;
use App\Services\FlashMessageService;
use Livewire\Component;
use Livewire\WithPagination;

class EmailTemplateTypeManagement extends Component
{
    use WithPagination;

    public $search = '';
    public $statusFilter = '';
    public $sortField = 'sort_order';
    public $sortDirection = 'asc';

    protected $queryString = [
        'search' => ['except' => ''],
        'statusFilter' => ['except' => ''],
        'sortField' => ['except' => 'sort_order'],
        'sortDirection' => ['except' => 'asc'],
    ];

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }
        
        $this->sortField = $field;
    }

    public function clearFilters()
    {
        $this->search = '';
        $this->statusFilter = '';
        $this->resetPage();
    }

    public function toggleStatus($typeId)
    {
        $type = EmailTemplateType::findOrFail($typeId);
        $type->update(['is_active' => !$type->is_active]);
        
        FlashMessageService::success('Template type status updated successfully!', 'Status Updated');
        $this->dispatch('flashMessage', 'success', 'Template type status updated successfully!', 'Status Updated', 5000);
    }

    public function deleteType($typeId)
    {
        $type = EmailTemplateType::findOrFail($typeId);
        
        // Check if type has templates
        if ($type->emailTemplates()->count() > 0) {
            FlashMessageService::error('Cannot delete template type that has associated templates. Please delete or reassign templates first.', 'Cannot Delete');
            $this->dispatch('flashMessage', 'error', 'Cannot delete template type that has associated templates. Please delete or reassign templates first.', 'Cannot Delete', 8000);
            return;
        }
        
        $type->delete();
        
        FlashMessageService::success('Template type deleted successfully!', 'Type Deleted');
        $this->dispatch('flashMessage', 'success', 'Template type deleted successfully!', 'Type Deleted', 5000);
    }

    public function render()
    {
        $query = EmailTemplateType::query()
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('name', 'like', '%' . $this->search . '%')
                      ->orWhere('description', 'like', '%' . $this->search . '%')
                      ->orWhere('slug', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->statusFilter !== '', function ($query) {
                $query->where('is_active', $this->statusFilter);
            })
            ->orderBy($this->sortField, $this->sortDirection);

        $types = $query->paginate(10);

        return view('livewire.admin.email-template-type-management', [
            'types' => $types,
        ]);
    }
}