<?php
/**
 * Form Response Class.
 *
 * This code is used to process Form Responses
 *
 * @category Forms
 *
 * @author mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
namespace Mtc\Modules\FormBuilder\Classes;

use Illuminate\Database\Eloquent\Model;

/**
 * Form Response Class. Defines Form Response model. Basic Eloquent model with
 * Answer collection. Each successful form submission creates a single Response.
 *
 * @category Forms
 *
 * @author mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
class FormResponse extends Model
{
    /**
     * @var string Classes associated table
     */
    protected $table = 'forms_responses';

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

    /**
     * Form::values().
     *
     * define relationship with answers
     *
     * @access public
     * @return Collection List of Response question answers
     */
    public function values()
    {
        if (!empty($this->form_id)) {
            $question_order = FormQuestion::where('form_id', $this->form_id)
                ->orderBy('order', 'ASC')
                ->pluck('id')
                ->toArray();
            return $this->hasMany(FormAnswer::class, 'response_id')
                ->orderByRaw("FIELD(question_id, ?)", implode(',', $question_order));
        }
        return $this->hasMany(FormAnswer::class, 'response_id');
    }
    
    public static function getValues($id)
    {
        return self::where('form_id', $id)
            ->join('values')
            ->get();

    }
}
