<?php

namespace Ignite\Core\Http\Forms\Admin;

use Ignite\Core\Entities\Permission;
use Illuminate\Validation\Rule;
use Kris\LaravelFormBuilder\Form;

class PermissionForm extends Form
{
    public function buildForm()
    {
        $this->add('key', 'text', $this->getKeyOptions());
        $this->add('description', 'textarea', $this->getDescriptionOptions());
        $this->add('status', 'toggle');
        $this->add('submit', 'submit', [
            'attr' => ['class' => 'btn btn-primary pull-right btn-save'],
            'label' => 'Save'
        ]);
    }

    /**
     * The options for the key field.
     *
     * @return array
     */
    private function getKeyOptions()
    {
        $rules = [
            'required',
        ];

        if ($permissionId = $this->getData('permission')) {
            $rules[] = $this->getUniqueRuleFor('key')->ignore($permissionId);
        } else {
            $rules[] = $this->getUniqueRuleFor('key');
        }

        return [
            'rules' => $rules
        ];
    }

    /**
     * The options for the description field.
     *
     * @return array
     */
    private function getDescriptionOptions()
    {
        return [
            'rules' => 'required'
        ];
    }

    /**
     * Create a unique rule for the given field.
     *
     * @param  string $field
     * @return \Illuminate\Validation\Rules\Unique
     */
    private function getUniqueRuleFor($field)
    {
        return Rule::unique(Permission::query()->newModelInstance()->getTable(), $field);
    }
}
