<?php

namespace App\Models;

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

class SaleItem extends Model
{
    use Filterable;

    protected $fillable = [
        'sale_id',
        'food_item_id', 'food_item_attribute_id',
        'food_category_id',
        'item_data',
        'item_name',
        'quantity',
        'price',
        'total_amount',
    ];

    protected $casts = [
        'item_data' => 'json',
    ];

    public function sale(): BelongsTo
    {
        return $this->belongsTo(Sale::class, 'sale_id');
    }

    public function foodItem(): BelongsTo
    {
        return $this->belongsTo(FoodItem::class, 'food_item_id');
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(FoodCategory::class, 'food_category_id');
    }

    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;
    }
}
