<?php

namespace App\Modules\Reminders;

use Illuminate\Support\Facades\Auth;
use App\Models\ValidationModel;
use App\Models\User;

class Reminder extends ValidationModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'reminders';

    /**
     * The number of models to return for pagination.
     *
     * @var int
     */
    protected $perPage = 50;

    /**
     * The relations to eager load on every query.
     *
     * @var array
     */
    protected $with = ['user', 'creator'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['user_id', 'message', 'remind_at', 'completed'];

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->created_by = Auth::user()->id;
            $model->updated_by = Auth::user()->id;
        });

        static::updating(function ($model) {
            $model->updated_by = Auth::user()->id;
        });
    }

    /**
     * Defines the relationship with the user model.
     *
     * @return \User
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Defines the relationship with the user model.
     *
     * @return \User
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Applies filters to retrieve the first record.
     *
     * @param  \Illuminate\Database\Query\Builder $query
     *
     * @return \Illuminate\Database\Query\Builder
     */
    public function scopeFuture($query)
    {
        return $query->where('remind_at', '>=', date('Y-m-d H:i:s'));
    }

    /**
     * Add a condition to restrict the results to the logged in user.
     *
     * @param  \Illuminate\Database\Query\Builder $query
     *
     * @return \Illuminate\Database\Query\Builder
     */
    public function scopeOwn($query)
    {
        return $query->where('user_id', getAuthUserId());
    }
}
