<?php

declare(strict_types=1);

namespace App\Models;

class GlobalSetting extends BaseModel
{
    protected string $table = 'configuracion_global';
    protected ?string $tenantColumn = null;

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

        $bindings = [];
        $placeholders = [];

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

        $sql = 'SELECT clave, valor
                FROM configuracion_global
                WHERE 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(array $values): void
    {
        if ($values === []) {
            return;
        }

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

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

    public function deleteByKey(string $key): bool
    {
        $stmt = $this->db()->prepare(
            'DELETE FROM configuracion_global
             WHERE clave = :clave'
        );

        return $stmt->execute([
            ':clave' => trim($key),
        ]);
    }
}
