<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;

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

    public function hasAllowNegativeColumn(): bool
    {
        return table_has_column($this->pdo, 'warehouses', 'allow_negative');
    }

    public function all(): array
    {
        $rows = get_warehouses($this->pdo);
        if (!$this->hasAllowNegativeColumn()) {
            return $rows;
        }
        $map = [];
        foreach ($this->pdo->query("SELECT id, allow_negative FROM warehouses") as $r) {
            $map[(int)$r['id']] = (int)$r['allow_negative'];
        }
        foreach ($rows as &$r) {
            $r['allow_negative'] = $map[(int)$r['id']] ?? 0;
        }
        unset($r);
        return $rows;
    }

    public function findById(int $id): array|false
    {
        $cols = "id, COALESCE(code,'') code, name, is_main, is_active";
        if ($this->hasAllowNegativeColumn()) {
            $cols .= ", allow_negative";
        }
        $st = $this->pdo->prepare("SELECT {$cols} FROM warehouses WHERE id=? LIMIT 1");
        $st->execute([$id]);
        return $st->fetch();
    }

    public function clearMainFlag(): void
    {
        $this->pdo->exec("UPDATE warehouses SET is_main=0");
    }

    public function create(array $data): int
    {
        if ($this->hasAllowNegativeColumn()) {
            $this->pdo->prepare("INSERT INTO warehouses (code, name, is_main, is_active, allow_negative) VALUES (?,?,?,?,?)")
                ->execute([$data['code'], $data['name'], $data['is_main'], $data['is_active'], $data['allow_negative']]);
        } else {
            $this->pdo->prepare("INSERT INTO warehouses (code, name, is_main, is_active) VALUES (?,?,?,?)")
                ->execute([$data['code'], $data['name'], $data['is_main'], $data['is_active']]);
        }
        return (int)$this->pdo->lastInsertId();
    }

    public function update(int $id, array $data): void
    {
        if ($this->hasAllowNegativeColumn()) {
            $this->pdo->prepare("UPDATE warehouses SET code=?, name=?, is_main=?, is_active=?, allow_negative=? WHERE id=?")
                ->execute([$data['code'], $data['name'], $data['is_main'], $data['is_active'], $data['allow_negative'], $id]);
        } else {
            $this->pdo->prepare("UPDATE warehouses SET code=?, name=?, is_main=?, is_active=? WHERE id=?")
                ->execute([$data['code'], $data['name'], $data['is_main'], $data['is_active'], $id]);
        }
    }
}
