<?php

namespace Ignite\Core\Traits;

use Ignite\Core\Http\Forms\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();

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

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

        // @todo: This needs to be redone to use the schema from the JSON file
        //        directly instead of going through the form. Using the form may slow
        //        down the report because it initializes each field possibly several
        //        times, and if the fields are drop-downs pull from the database, then
        //        it could add a lot of overhead.
        /** @var ProfileForm $form */
        $form = app(FormBuilder::class)->create($this->form, [], [
            'readonly' => true,
            'renderGroups' => false
        ]);

        foreach ($form->getFields() as $field) {
            // static fields are not for reports
            if ('static' == $field->getOption('frontend_type')) {
                continue;
            }
            $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),
        ];
    }
}
