<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class StockOpname extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'opname_number',
        'opname_date',
        'status',
        'notes',
        'created_by',
        'approved_by',
        'approved_at',
    ];

    protected $dates = [
        'opname_date',
        'approved_at',
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    protected $casts = [
        'opname_date' => 'date',       // agar bisa ->format()
        'approved_at' => 'datetime',   // jika ingin pakai format waktu
    ];

    /**
     * Relasi ke items
     */
    public function items()
    {
        return $this->hasMany(StockOpnameItem::class);
    }

    /**
     * User yang membuat stock opname
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * User yang approve stock opname
     */
    public function approver()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    /**
     * Scope untuk hanya menampilkan draft
     */
    public function scopeDraft($query)
    {
        return $query->where('status', 'draft');
    }

    /**
     * Scope untuk hanya menampilkan yang sudah completed
     */
    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }

    /**
     * Hitung total selisih fisik
     */
    public function getTotalDifferenceAttribute()
    {
        return $this->items->sum('difference');
    }

    /**
     * Hitung jumlah item yang surplus
     */
    public function getSurplusCountAttribute()
    {
        return $this->items->where('difference_type', 'surplus')->count();
    }

    /**
     * Hitung jumlah item yang shortage
     */
    public function getShortageCountAttribute()
    {
        return $this->items->where('difference_type', 'shortage')->count();
    }
}
