<?php

namespace Ignite\Core\Traits;

use Ignite\Core\Models\Form\ProfileForm;
use Kris\LaravelFormBuilder\Fields\FormField;
use Kris\LaravelFormBuilder\FormBuilder;

trait ReportFormConfiguration
{
    /**
     * Attempt to merge any form label information if form information exists.
     *
     * @return array
     */
    protected function getColumns()
    {
        // Get the columns for the report instance.
        $columns = $this->columns();

        if (! property_exists($this, 'form')) {
            return $columns;
        }

        /** @var ProfileForm $form */
        $form = app(FormBuilder::class)->create($this->form, [], [
            'readonly' => true,
            'renderGroups' => false
        ]);

        foreach ($columns as $key => $column) {
            if (property_exists($this, 'alwaysDisplay') && in_array($key, $this->alwaysDisplay)) {
                continue;
            } else {
                $columns[$key]['visible'] = false;
            }
        }

        foreach ($form->getFields() as $field) {
            $columns[$field->getName()] = $this->decorateColumn($field);
        }

        return $columns;
    }

    /**
     * Decorate the column date.
     *
     * @param  FormField $field
     * @return array
     */
    protected function decorateColumn($field)
    {
        $table = $field->getOption('table');
        $name = $field->getOption('name');
        $key = empty($table) ? $name : "{$table}.{$name}";

        return [
            'name' => $key,
            'title' => $field->getOption('label'),
            'visible' => true,
            'orderable' => true,
            'exportable' => true,
            'searchable' => true,
            'sensitive' => $field->getOption('sensitive', false),
        ];
    }
}
