<?php

declare(strict_types=1);

namespace App\Models;

class CompanySetting extends BaseModel
{
    protected string $table = 'configuracion_empresa';

    public function getMany(int $companyId, array $keys): array
    {
        if ($keys === []) {
            return [];
        }

        $bindings = [
            ':empresa_id' => $companyId,
        ];
        $placeholders = [];

        foreach (array_values($keys) as $index => $key) {
            $param = ':clave_' . $index;
            $placeholders[] = $param;
            $bindings[$param] = (string) $key;
        }

        $sql = 'SELECT clave, valor
                FROM configuracion_empresa
                WHERE empresa_id = :empresa_id
                  AND clave IN (' . implode(', ', $placeholders) . ')';

        $stmt = $this->db()->prepare($sql);
        $stmt->execute($bindings);

        $rows = $stmt->fetchAll() ?: [];
        $mapped = [];

        foreach ($rows as $row) {
            $mapped[(string) $row['clave']] = (string) ($row['valor'] ?? '');
        }

        return $mapped;
    }

    public function upsertMany(int $companyId, array $values): void
    {
        if ($values === []) {
            return;
        }

        $stmt = $this->db()->prepare(
            'INSERT INTO configuracion_empresa (empresa_id, clave, valor, created_at, updated_at)
             VALUES (:empresa_id, :clave, :valor, NOW(), NOW())
             ON DUPLICATE KEY UPDATE
                valor = VALUES(valor),
                updated_at = VALUES(updated_at)'
        );

        foreach ($values as $key => $value) {
            $stmt->execute([
                ':empresa_id' => $companyId,
                ':clave' => (string) $key,
                ':valor' => $value !== null ? (string) $value : null,
            ]);
        }
    }
}
