<?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()
    {
        $bestChoice = $this->getBestUserChoice();
        return [
            'label' => 'Participant',
            'rules' => ['required', 'exists:Ignite\Core\Entities\User,user_id'],
            'attr' => ['class' => 'select2 js-data-participant-lookup', 'data-key' => $bestChoice],
            'choices' => [],
            'selected' => $bestChoice
        ];
    }

    /**
     * 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;
    }
}
