<?php

namespace Ignite\Core\Http\Forms;

use Exception;
use Ignite\Core\Models\Form\CoreForm;
use Ignite\Core\Models\Form\GroupByTableTrait;
use Illuminate\Http\RedirectResponse;
use Kris\LaravelFormBuilder\Fields\FormField;

class ProfileForm extends CoreForm
{
    use GroupByTableTrait;

    /**
     * Should the values be grouped by table.
     *
     * @var bool
     */
    protected $groupByTable = true;

    /**
     * Build the enrollment form.
     *
     * @return mixed|void
     * @throws Exception
     */
    public function buildForm()
    {
        $this->setFormOptions([
            'id' => 'profile-form',
            'novalidate'
        ]);

        $this->buildFromSchema('enrollment', $this->getData('renderGroups', true));

        if (! empty($type = $this->getFormOption('internal'))) {
            $this->getField('internal')->setOption('selected', $type)->setValue($type);
        }

        if (isset($this->data['readonly'])) {
            /** @var FormField $field */
            foreach ($this->fields as $field) {
                $field->setOption('attr.readonly', true);
                $field->disable();

                if (in_array($field->getType(), ['button', 'submit', 'reset'])) {
                    $this->remove($field->getName());
                }
            }
        }

        /* Remove reCAPTCHA from routes that are unnecessary
         * -------------------------------------------------- */
        if (!in_array(url()->current(), $this->routesForRecaptcha())) {
            $this->remove(config('services.recaptcha.field_name'));
        }
    }

    /**
     * Returns an array of routes in which reCAPTCHA should be used.
     * This is meant to be extended by sites that use more than one
     * enrollment form. It will pass the built-in enrollment form
     * by default.
     *
     * @return array
     */
    public function routesForRecaptcha(): array
    {
        $routes = [];
        if (config('services.recaptcha.sitekey')) {
            $routes[] = route('participant.enroll.create');
        }

        return $routes;
    }
}
