<?php

namespace App\Models;

use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Expense extends Model
{
    use HasFactory, Filterable;

    protected $fillable = ['title', 'amount', 'expense_type_id', 'description', 'expense_date'];

    /**
     * Product category
     *
     * @return     BelongsTo  The belongs to.
     */
    public function expenseType(): BelongsTo
    {
        return $this->belongsTo(ExpenseType::class);
    }

    public function scopeDuration($query, $value, $isLast = false)
    {
        $date = now();
        if ($isLast) {
            if ('year' == $value) {
                $date = $date->subYear();
            } elseif ('month' == $value) {
                $date = $date->subMonth();
            } elseif ('day' == $value) {
                $date = $date->subDay();
            }
        }

        if ('day' == $value) {
            return $query->whereDate('created_at', '=', $date->format('Y-m-d'));
        }
        if ('month' == $value) {
            return $query->whereMonth('created_at', '=', $date->month);
        }
        if ('year' == $value) {
            return $query->whereYear('created_at', '=', $date->year);
        }

        return $query;
    }
}
