<?php

namespace App\Components\Dsar;

use App\Models\Dsar\DsarType;
use Livewire\Component;

class TypeManager extends Component {
    public $view = 'list';
    public $search = '';

    public $dsarId;
    public $display_name;
    public $description;
    public $content;

    protected $rules = [
        'display_name' => 'required|string|max:255',
        'description' => 'nullable|string|max:500',
        'content' => 'required|string',
    ];

    public function mount(): void {
        $this->authorize('dsars.types.view');
    }

    /**
     * Render the component.
     */
    public function render() {
        return view('components.dsar.type-manager', [
            'dsarTypes' => DsarType::where('display_name', 'like', '%' . $this->search . '%')
                ->latest()
                ->get()
        ]);
    }

    public function create() {
        $this->authorize('dsars.types.create');
        $this->resetForm();
        $this->view = 'form';
    }


    private function resetForm() {
        $this->reset(['dsarId', 'display_name', 'description', 'content']);
    }

    /**
     * Switch to edit form with existing data.
     */
    public function edit($id) {
        $this->authorize('dsars.types.edit');
        $type = DsarType::findOrFail($id);
        $this->dsarId = $type->id;
        $this->display_name = $type->display_name;
        $this->description = $type->description;
        $this->content = $type->content;
        $this->view = 'form';
    }

    /**
     * Save or Update the DSAR DsarType.
     */
    public function save() {
        $this->authorize($this->dsarId ? 'dsars.types.edit' : 'dsars.types.create');
        $this->validate();

        DsarType::updateOrCreate(
            ['id' => $this->dsarId],
            [
                'display_name' => $this->display_name,
                'description' => $this->description,
                'content' => $this->content,
            ]
        );

        $this->resetForm();
        $this->view = 'list';
    }

    /**
     * Delete the record.
     */
    public function delete($id) {
        $this->authorize('dsars.types.delete');
        DsarType::findOrFail($id)->delete();
        session()->flash('message', 'DSAR Type deleted successfully.');
    }

    /**
     * Close form and return to list.
     */
    public function cancel() {
        $this->view = 'list';
        $this->resetForm();
    }
}
