<?php

namespace App\Models;

use App\Models\BaseModel;

class StockMovement extends BaseModel
{
    protected $table = 'stock_movements';

    protected $fillable = [
        'company_id','item_id','warehouse_id','voucher_id',
        'movement_date','type','quantity','unit_cost','total_cost',
        'running_qty','running_avg_cost',
    ];

    protected $casts = [
        'movement_date'   => 'date',
        'quantity'        => 'decimal:4',
        'unit_cost'       => 'decimal:6',
        'total_cost'      => 'decimal:2',
        'running_qty'     => 'decimal:4',
        'running_avg_cost'=> 'decimal:6',
    ];

    public function company()   { return $this->belongsTo(Company::class); }
    public function item()      { return $this->belongsTo(Item::class); }
    public function warehouse() { return $this->belongsTo(Warehouse::class); }
    public function voucher()   { return $this->belongsTo(Voucher::class); }

    /**
     * Calculate new weighted average cost after a stock-in movement.
     * Formula: (existing_qty * existing_avg + new_qty * new_cost) / (existing_qty + new_qty)
     */
    public static function calcNewAvgCost(
        float $existingQty,
        float $existingAvg,
        float $newQty,
        float $newUnitCost
    ): float {
        $totalQty = $existingQty + $newQty;
        if ($totalQty <= 0) return $newUnitCost;
        return ($existingQty * $existingAvg + $newQty * $newUnitCost) / $totalQty;
    }
}
