<?php

namespace App\Modules\Bookings;

use Carbon\Carbon;
use App\Models\ValidationModel;
use App\Modules\Bookings\Task;
use App\Models\User;

class TaskFeedback extends ValidationModel
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['task_id', 'user_id', 'code', 'feedback', 'rating', 'emailed', 'emailed_at','reminder_sent'];

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'task_feedback';

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'code';

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['send_date'];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'task_id' => 'required',
        'code'    => 'required',
        'user_id' => 'required',
    ];

    /**
     * Retrieves the date when it is supposed to be sent out.
     *
     * @return string
     */
    public function getSendDateAttribute()
    {
        return Carbon::parse($this->created_at)->addDay()->toDateTimeString();
    }

    /**
     * Returns the task associated with this feedback.
     *
     * @return App\Modules\Bookings\Task
     */
    public function task()
    {
        return $this->belongsTo(Task::class, 'task_id');
    }

    /**
     * Returns the user associated with this feedback.
     *
     * @return \User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Returns all the feedback that have not been filled yet.
     *
     * @param  Illuminate\Database\Query\Builder $query
     *
     * @return Illuminate\Database\Query\Builder
     */
    public function scopeIncomplete($query)
    {
        return $query->whereNull('rating');
    }

    /**
     * Filter results between specified dates.
     *
     * @param  Illuminate\Database\Query\Builder $query
     * @param  string $start_date
     * @param  string $end_date
     *
     * @return Illuminate\Database\Query\Builder
     */
    public function scopeInterval($query, $start_date = '', $end_date = '')
    {
        if ($start_date && $end_date) {
            $start_date = is_numeric($start_date) ? 
                now()->setTimestamp($start_date)->startOfDay() : 
                now()->parse($start_date)->startOfDay();
            $end_date = is_numeric($end_date) ? 
                now()->setTimestamp($end_date)->endOfDay() : 
                now()->parse($end_date)->endOfDay();

            return $query->whereBetween('task_feedback.created_at', [$start_date, $end_date]);
        }

        return $query->whereBetween('task_feedback.created_at', [
            now()->startOfMonth(),
            now()->endOfMonth()
        ]);
    }
}
