<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;

final class ItemUnitRepository
{
    public function __construct(private PDO $pdo) {}

    public function findItem(int $itemId): array|false
    {
        $st = $this->pdo->prepare("SELECT id, name, default_unit_id FROM items WHERE id=?");
        $st->execute([$itemId]);
        return $st->fetch();
    }

    public function allUnits(): array
    {
        return $this->pdo->query("SELECT id, name FROM units ORDER BY name")->fetchAll();
    }

    public function setBaseUnit(int $itemId, int $baseUnitId): void
    {
        $this->pdo->prepare("UPDATE items SET default_unit_id=? WHERE id=?")->execute([$baseUnitId, $itemId]);
    }

    public function upsertPack(int $itemId, int $unitId, float $factor, ?string $barcode): void
    {
        $this->pdo->prepare("INSERT INTO item_units (item_id, unit_id, factor_to_base, is_base, barcode)
                       VALUES (?,?,?,?,?)
                       ON DUPLICATE KEY UPDATE factor_to_base=VALUES(factor_to_base), barcode=VALUES(barcode)")
            ->execute([$itemId, $unitId, $factor, 0, $barcode]);
    }

    public function deletePack(int $itemId, int $unitId): void
    {
        $this->pdo->prepare("DELETE FROM item_units WHERE item_id=? AND unit_id=?")->execute([$itemId, $unitId]);
    }

    public function packsForItem(int $itemId): array
    {
        $st = $this->pdo->prepare("SELECT iu.unit_id, u.name unit_name, iu.factor_to_base, iu.barcode
                     FROM item_units iu
                     JOIN units u ON u.id=iu.unit_id
                     WHERE iu.item_id=?
                     ORDER BY u.name");
        $st->execute([$itemId]);
        return $st->fetchAll();
    }
}
