<?php
declare(strict_types=1);

namespace App\Repository;

use PDO;

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

    public function listActivePrinters(): array
    {
        $stmt = $this->pdo->query('SELECT * FROM printers WHERE is_active = 1 ORDER BY name');
        return $stmt->fetchAll();
    }

    public function listActiveMaterials(): array
    {
        $stmt = $this->pdo->query('SELECT * FROM materials WHERE is_active = 1 ORDER BY code');
        return $stmt->fetchAll();
    }

    public function getPrinterById(int $printerId): ?array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM printers WHERE id = :id');
        $stmt->execute(['id' => $printerId]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function listMaterialsForPrinter(int $printerId): array
    {
        $sql = 'SELECT m.*, pms.support_level, pms.partial_reason, pms.extra_info
                FROM materials m
                LEFT JOIN printer_material_support pms
                  ON pms.material_id = m.id AND pms.printer_id = :pid
                WHERE m.is_active = 1
                ORDER BY m.code';
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['pid' => $printerId]);
        return $stmt->fetchAll();
    }
}
