<?php

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

use App\Casts\OptionalEncrypted;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

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

    /**
     * @var string Classes fillable params
     */
    protected $fillable = [
        'name',
        'email_receiver',
        'button_class',
        'css_class',
        'css_id',
        'no_limit',
        'display_until',
        'callback',
        'callback_class',
        'callback_action',
        'redirect',
        'info_text',
        'success_text',
        'submit_text',
    ];

    protected $casts = [
        'email_receiver' => OptionalEncrypted::class,
    ];

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

    /**
     * Form::questions().
     *
     * define relationship with questions
     *
     * @access public
     * @param  string  $order_by Field by which to order questions
     */
    public function questions($order_by = 'order')
    {
        return $this->hasMany(FormQuestion::class, 'form_id')
            ->orderBy($order_by);
    }

    /**
     * Form::fieldsets().
     *
     * Retrieve form fieldsets
     *
     * @access public
     * @param  string $order_by Field by which to order fieldsets
     */
    public function fieldsets($order_by = 'order')
    {
        return $this->hasMany(FormFieldset::class, 'form_id')
            ->orderBy($order_by);
    }

    /**
     * Form::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'] = [];
        $empty['fieldsets'] = [];

        return $empty;
    }
}
