<?php
class Batch extends Model {
    protected static string $table = 'batches';

    public static function forProduct(int $productId): array {
        $stmt = db()->prepare(
            "SELECT * FROM batches WHERE tenant_id=? AND product_id=? ORDER BY expiry_date ASC"
        );
        $stmt->execute([static::tenantId(), $productId]);
        return $stmt->fetchAll();
    }

    public static function findOrCreate(int $productId, string $batchNo, ?string $expiryDate, ?string $mfgDate = null): int {
        $tid  = static::tenantId();
        $stmt = db()->prepare("SELECT id FROM batches WHERE tenant_id=? AND product_id=? AND batch_no=? LIMIT 1");
        $stmt->execute([$tid,$productId,$batchNo]);
        $row = $stmt->fetch();
        if ($row) return (int)$row['id'];
        db()->prepare("INSERT INTO batches (tenant_id,product_id,batch_no,expiry_date,mfg_date) VALUES (?,?,?,?,?)")
             ->execute([$tid,$productId,$batchNo,$expiryDate,$mfgDate]);
        return (int)db()->lastInsertId();
    }
}
