<?php

declare(strict_types=1);

namespace Lab;

use PDO;

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

    /** @return list<array<string, mixed>> */
    public function active(): array
    {
        return $this->pdo->query(
            "SELECT sku, name, width_cm, height_cm, price_cents, sort
             FROM products WHERE active = 1 AND sku != 'a4' ORDER BY sort, id"
        )->fetchAll() ?: [];
    }

    /** @return list<array<string, mixed>> */
    public function all(): array
    {
        return $this->pdo->query(
            "SELECT * FROM products WHERE sku != 'a4' ORDER BY sort, id"
        )->fetchAll() ?: [];
    }

    public function map(): array
    {
        $out = [];
        foreach ($this->active() as $row) {
            $out[(string) $row['sku']] = $row;
        }

        return $out;
    }

    public function updatePrice(string $sku, int $cents, int $active): void
    {
        $stmt = $this->pdo->prepare(
            'UPDATE products SET price_cents = :cents, active = :active WHERE sku = :sku'
        );
        $stmt->execute([
            'cents' => max(0, $cents),
            'active' => $active ? 1 : 0,
            'sku' => $sku,
        ]);
    }
}
