<?php

namespace Ignite\Core\Http\Forms\Admin;

use Ignite\Core\Entities\Participant;
use Illuminate\Support\Arr;
use Kris\LaravelFormBuilder\Form;

class WaitingTransactionForm extends Form
{
    /**
     * Build the form.
     *
     * @return self
     */
    public function buildForm()
    {
        $this->setFormOption('novalidate', 'novalidate');
        $this->add('user_id', 'select', $this->getUserIdOptions());
        $this->add('description', 'text', $this->getDescriptionOptions());
        $this->add('notes', 'textarea', $this->getNotesOptions());
        $this->add('submit', 'submit', $this->getSaveButtonOptions());

        return $this;
    }

    /**
     * The options for the label field.
     *
     * @return array
     */
    protected function getUserIdOptions()
    {
        $choices = Arr::prepend($this->getUserChoices(), 'Please choose a participant...', '');

        return [
            'label' => 'Participant',
            'rules' => ['required', 'exists:Ignite\Core\Entities\User,user_id'],
            'attr' => ['class' => 'select2'],
            'choices' => $choices,
            'selected' => $this->getBestUserChoice()
        ];
    }

    /**
     * The options for the code field.
     *
     * @return array
     */
    protected function getDescriptionOptions()
    {
        return [
            'label' => 'Description',
            'rules' => 'present|nullable|min:4|max:255'
        ];
    }

    /**
     * The options for the code field.
     *
     * @return array
     */
    protected function getNotesOptions()
    {
        return [
            'label' => 'Notes',
            'rules' => 'present|nullable|min:4|max:500'
        ];
    }

    /**
     * The options for the save button.
     *
     * @return array
     */
    protected function getSaveButtonOptions()
    {
        return [
            'attr' => ['class' => 'btn btn-primary'],
            'label' => 'Assign'
        ];
    }

    /**
     * The participants to choose from.
     *
     * @return array
     */
    protected function getUserChoices()
    {
        return Participant::query()
            ->whereNull('deleted_at')
            ->get()
            ->mapWithKeys(function ($participant) {
                return [$participant->getKey() => $participant->fullName()];
            })
            ->toArray();
    }

    /**
     * Attempt to find the best choice based on the current model value.
     *
     * @return int|null
     */
    protected function getBestUserChoice()
    {
        if (! $this->model) {
            return null;
        }

        $result = Participant::query()->where('email', $this->model->identifier)->first();

        return optional($result)->getKey() ?? null;
    }
}
