<?php

/**
 * Form Fieldset Class.
 *
 * This code is used to make up Form Fieldsets and their modification
 *
 * @category Forms
 * @package  Mtc_Form_Builder
 * @author   mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
namespace Mtc\Modules\FormBuilder\Classes;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

/**
 * Form Fieldset Class. Defines Form Fieldset model.
 * Basic Eloquent model with question relation.
 *
 * @category Forms
 *
 * @author mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
class FormFieldset extends Model
{
    /**
     * @var string Classes associated table
     */
    protected $table = 'forms_fieldsets';

    /**
     * @var string Classes fillable params
     */
    protected $fillable = [
        'name',
        'css_class',
        'css_id',
        'order',
    ];

    /**
     * @var bool Disables use of eloquent timestamps
     */
    public $timestamps = false;

    /**
     * FormFieldset::questions().
     *
     * Retrieve Fieldset questions
     *
     * @return FormFieldsetQuestionCollection $questions list of Fieldset questions
     */
    public function questions()
    {
        return $this->hasMany(FormQuestion::class, 'fieldset_id');
    }

    /**
     * FormFieldset::unassignedQuestions().
     *
     * Retrieve Questions that are not assigned to any fieldset
     *
     * @access public
     * @static
     * @param  int $form_id Current Form ID
     *
     * @return FormFieldsetQuestionCollection $questions list of Fieldset questions
     */
    public static function unassignedQuestions($form_id)
    {
        return FormQuestion::where('fieldset_id', 0)
            ->where('form_id', $form_id)
            ->orderBy('order', 'ASC')
            ->get();
    }

    /**
     * FormFieldset::getEmpty().
     *
     * Creates a dummy data array for Vue to process.
     * Eloquent doesn't give out object columns unless it is saved.
     * This function gets object columns and adds relations as empty arrays;
     *
     * @access public
     * @static
     * @return array $empty Empty array with object attributes as keys
     */
    public static function getEmpty()
    {
        $temp = new self;
        $empty = Schema::getColumnListing($temp->getTable());
        $empty = array_fill_keys($empty, '');
        $empty['questions'] = [];

        return $empty;
    }
}
