<?php
namespace App\Services;
use App\Models\StockItem;
use App\Models\StockLedger;
use App\Models\Stockpile;
use App\Models\StockpileMovement;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class StockService {
    public static function stockpileFor(int $quarryId, int $productId): Stockpile {
        return Stockpile::firstOrCreate(['quarry_id' => $quarryId, 'product_id' => $productId],
            ['code' => 'SP-'.str_pad((string) (Stockpile::count() + 1), 4, '0', STR_PAD_LEFT)]);
    }
    public static function moveStockpile(int $pileId, string $date, string $type, float $in, float $out, ?string $refType = null, $refId = null, ?string $remarks = null): StockpileMovement {
        return DB::transaction(function () use ($pileId, $date, $type, $in, $out, $refType, $refId, $remarks) {
            $p = Stockpile::lockForUpdate()->findOrFail($pileId);
            $bal = round($p->current_qty + $in - $out, 3);
            $p->update(['current_qty' => $bal]);
            return StockpileMovement::create(['movement_date' => $date, 'stockpile_id' => $p->id, 'movement_type' => $type,
                'ref_type' => $refType, 'ref_id' => $refId, 'qty_in' => $in, 'qty_out' => $out,
                'balance_after' => $bal, 'remarks' => $remarks, 'created_by' => Auth::id()]);
        });
    }
    public static function postLedger(string $date, int $itemId, int $whId, string $type, float $in, float $out, float $rate = 0, ?string $refType = null, $refId = null, array $cc = [], ?string $remarks = null): StockLedger {
        return DB::transaction(function () use ($date, $itemId, $whId, $type, $in, $out, $rate, $refType, $refId, $cc, $remarks) {
            $item = StockItem::lockForUpdate()->findOrFail($itemId);
            $bal = round($item->current_qty + $in - $out, 3);
            if ($in > 0 && $rate > 0) {
                $oldVal = $item->current_qty * $item->avg_cost_rate;
                $newQty = $item->current_qty + $in;
                $item->avg_cost_rate = $newQty > 0 ? round(($oldVal + $in * $rate) / $newQty, 2) : $rate;
                $item->last_purchase_rate = $rate;
            }
            $item->current_qty = $bal; $item->save();
            return StockLedger::create(['txn_date' => $date, 'item_id' => $itemId, 'warehouse_id' => $whId, 'txn_type' => $type,
                'ref_type' => $refType, 'ref_id' => $refId, 'qty_in' => $in, 'qty_out' => $out, 'rate' => $rate,
                'balance_after' => $bal, 'quarry_id' => $cc['quarry_id'] ?? null, 'project_id' => $cc['project_id'] ?? null,
                'equipment_id' => $cc['equipment_id'] ?? null, 'remarks' => $remarks, 'created_by' => Auth::id()]);
        });
    }
}
