<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ReportHistoryVarience extends Model
{
    protected $guarded = [];

    public function scopeUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function reportHistoryVarienceData()
    {
        return $this->hasMany('App\Models\ReportHistoryVarienceData');
    }

    public function location()
    {
        return $this->belongsTo('App\Models\Location');
    }


    /**
     * format date before displaying
     */
    public function getDateAttribute($date)
    {
        return parse_date_from_db_date($date);
    }

    /**
     * filters with exact match with the serch value 
     * 
     * @param object $query
     * @param string $filterKey
     * @param string $filterValue
     * 
     * @return object
     */
    public function scopeFilterByExactMatch($query, $filterKey, $filterValue)
    {
        if (is_array($filterValue)) {
            return  $query->whereIn($filterKey, $filterValue);
        } else {
            return $query->where($filterKey, $filterValue);
        }

        return $query;
    }

    /**
     * filters with date range match with the serch value
     * 
     * @param object $query
     * @param string $filterKey
     * @param string $filterValue
     * 
     * @return object 
     */
    public function scopeFilterByDateRangeMatch($query, $filterKey, $filterValue)
    {
        if (strpos($filterKey, '_from') !== false) {
            $query = $query->where(str_replace('_from', '', $filterKey), '>=', convert_to_db_date($filterValue));
        }

        if (strpos($filterKey, '_to') !== false) {
            $query = $query->where(str_replace('_to', '', $filterKey), '<=', convert_to_db_date($filterValue));
        }

        return $query;
    }
}
