<?php

declare(strict_types=1);

namespace App\Models;

class WhatsAppMetaTemplate extends BaseModel
{
    protected string $table = 'whatsapp_meta_templates';
    protected ?string $tenantColumn = null;

    public function recent(int $limit = 20): array
    {
        $limit = max(1, min(200, $limit));
        $stmt = $this->db()->query(
            'SELECT *
             FROM whatsapp_meta_templates
             ORDER BY id DESC
             LIMIT ' . $limit
        );

        return $stmt->fetchAll() ?: [];
    }

    public function findByName(string $name): ?array
    {
        $stmt = $this->db()->prepare(
            'SELECT *
             FROM whatsapp_meta_templates
             WHERE nombre = :nombre
             LIMIT 1'
        );
        $stmt->execute([
            ':nombre' => trim($name),
        ]);
        $row = $stmt->fetch();

        return $row ?: null;
    }

    public function countByStatus(): array
    {
        $stmt = $this->db()->query(
            'SELECT meta_estado, COUNT(*) AS total
             FROM whatsapp_meta_templates
             GROUP BY meta_estado'
        );
        $rows = $stmt->fetchAll() ?: [];

        $stats = [
            'pendiente' => 0,
            'aprobada' => 0,
            'rechazada' => 0,
            'error' => 0,
        ];

        foreach ($rows as $row) {
            $status = strtolower(trim((string) ($row['meta_estado'] ?? '')));
            $total = (int) ($row['total'] ?? 0);
            if (array_key_exists($status, $stats)) {
                $stats[$status] = max(0, $total);
            }
        }

        return $stats;
    }
}
