<?php
// app/Livewire/AttachmentTypeController.php
namespace App\Livewire;

use App\Models\AttachmentType;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class AttachmentTypeController extends Component
{
    public $types;
    
    // Form properties
    public $name = '';
    public $description = '';
    public $active = true;
    
    // Edit mode properties
    public $editMode = false;
    public $typeId;
    public $selectedType;

    protected function rules()
    {
        $rules = [
            'name' => [
                'required', 
                'string', 
                'min:2', 
                'max:255'
            ],
            'description' => ['nullable', 'string'],
            'active' => ['boolean'],
        ];
        
        // Add unique rule only when typeId is set (edit mode) or for new records
        if ($this->typeId) {
            $rules['name'][] = Rule::unique('attachment_types', 'name')->ignore($this->typeId);
        } else {
            $rules['name'][] = 'unique:attachment_types,name';
        }
        
        return $rules;
    }

    protected function messages()
    {
        return [
            'name.required' => 'Type name is required.',
            'name.min' => 'Type name must be at least 2 characters.',
            'name.unique' => 'This type name already exists.',
        ];
    }

    public function mount()
    {
        $this->loadTypes();
    }

    public function loadTypes()
    {
        $this->types = AttachmentType::with(['createdBy', 'updatedBy'])
            ->withCount('attachments')
            ->orderBy('name')
            ->get();
    }

    public function resetForm()
    {
        $this->reset(['name', 'description', 'active', 'editMode', 'typeId']);
        $this->active = true;
    }

    public function view($id)
    {
        $this->selectedType = AttachmentType::with(['createdBy', 'updatedBy', 'attachments.file'])
            ->withCount('attachments')
            ->findOrFail($id);
    }

    public function store()
    {
        $this->validate();

        $type = new AttachmentType();
        $type->name = $this->name;
        $type->description = $this->description;
        $type->active = $this->active;
        $type->created_by = Auth::id();
        $type->updated_by = Auth::id();
        $type->save();

        $this->loadTypes();
        $this->resetForm();

        // Dispatch events for modal closing and notifications
        $this->dispatch('type-saved');
        $this->dispatch('close-modal');
        $this->dispatch('show-success', message: 'Attachment type created successfully!');
    }

    public function edit($id)
    {
        $type = AttachmentType::findOrFail($id);
        
        $this->typeId = $type->id;
        $this->name = $type->name;
        $this->description = $type->description;
        $this->active = $type->active;
        $this->editMode = true;
    }

    public function update()
    {
        $this->validate();

        $type = AttachmentType::findOrFail($this->typeId);
        $type->name = $this->name;
        $type->description = $this->description;
        $type->active = $this->active;
        $type->updated_by = Auth::id();
        $type->save();

        $this->loadTypes();
        $this->resetForm();

        // Dispatch events for modal closing and notifications
        $this->dispatch('type-saved');
        $this->dispatch('close-modal');
        $this->dispatch('show-success', message: 'Attachment type updated successfully!');
    }

    public function delete($id)
    {
        $type = AttachmentType::findOrFail($id);
        
        // Check if type has attachments
        if ($type->attachments()->count() > 0) {
            $this->dispatch('show-error', 'Cannot delete attachment type because it has associated attachments.');
            return;
        }
        
        $typeName = $type->name;
        $type->delete();

        $this->loadTypes();
        
        $this->dispatch('refresh-table');
        $this->dispatch('show-success', "Attachment type '{$typeName}' deleted successfully!");
    }

    public function toggleActive($id)
    {
        $type = AttachmentType::findOrFail($id);
        $type->active = !$type->active;
        $type->updated_by = Auth::id();
        $type->save();

        $this->loadTypes();
        $this->dispatch('show-success', 'Attachment type status updated!');
    }

    public function render()
    {
        return view('livewire.attachment-type-controller');
    }
}