<?php

namespace App\Models;

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

class InventoryCountItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'inventory_count_id',
        'inventory_item_id',
        'expected_quantity',
        'counted_quantity',
        'status',
        'counted_by',
        'counted_at',
        'notes',
    ];

    protected $casts = [
        'expected_quantity' => 'float',
        'counted_quantity' => 'float',
        'counted_at' => 'datetime',
    ];

    public function inventoryCount()
    {
        return $this->belongsTo(InventoryCount::class);
    }

    public function item()
    {
        return $this->belongsTo(InventoryItem::class, 'inventory_item_id');
    }

    public function counter()
    {
        return $this->belongsTo(User::class, 'counted_by');
    }

    // Calculate the discrepancy between system and counted quantities
    public function getDiscrepancyAttribute()
    {
        return $this->counted_quantity - $this->system_quantity;
    }

    // Calculate the discrepancy percentage
    public function getDiscrepancyPercentageAttribute()
    {
        if ($this->system_quantity == 0) {
            return $this->counted_quantity > 0 ? 100 : 0;
        }

        return round(($this->discrepancy / $this->system_quantity) * 100, 2);
    }

    // Check if there is a discrepancy
    public function getHasDiscrepancyAttribute()
    {
        return abs($this->discrepancy) > 0;
    }
}
