<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Morilog\Jalali\Jalalian;

class Storage extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'store_id',
        'uuid',
        'name',
        'address',
    ];

    protected $casts = [
        'store_id' => 'integer',
    ];

    /**
     * additional data
     */
    protected $appends = [
        'product_count',
        'jalali_created_at',
        'jalali_updated_at',
    ];

    public function getProductCountAttribute()
    {
        $products = Product::with('inventories')->where('status', '!=', 'waiting')->where('status', '!=', 'deleted')->where('status', '!=', 'deep_deleted')->where('status', '!=', 'rejected')->whereHas('inventories', function ($query) {
            $query->where('storage_id', $this->id);
        })->get();

        return $products->count();
    }

    public function getJalaliCreatedAtAttribute()
    {
        $date = [
            Jalalian::forge($this->created_at)->format('%d %B %Y'),
            Jalalian::forge($this->created_at)->format('Y/m/d'),
            Jalalian::forge($this->created_at)->format('H:i - Y/m/d'),
            Jalalian::forge($this->created_at)->ago(),
            Jalalian::forge($this->created_at)->getTimestamp(),
        ];
        return $date;
    }

    public function getJalaliUpdatedAtAttribute()
    {
        $date = [
            Jalalian::forge($this->updated_at)->format('%d %B %Y'),
            Jalalian::forge($this->updated_at)->format('Y/m/d'),
            Jalalian::forge($this->updated_at)->format('H:i - Y/m/d'),
            Jalalian::forge($this->updated_at)->ago(),
            Jalalian::forge($this->updated_at)->getTimestamp(),
        ];
        return $date;
    }
    /** end append */

    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'uuid';
    }

    /* relationships **************/
    public function inventories(): HasMany
    {
        return $this->hasMany(Inventory::class);
    }

    public function store(): BelongsTo
    {
        return $this->belongsTo(Store::class);
    }
}
