<?php

declare(strict_types=1);

namespace App\Models;

class WhatsappTemplate extends BaseModel
{
    protected string $table = 'whatsapp_templates';
    protected string $primaryKey = 'id';

    public function findAllActive(): array
    {
        return $this->query(
            "SELECT * FROM {$this->table} WHERE status = 'active' ORDER BY name LIMIT 200"
        );
    }

    public function findWithPagination(int $page = 1, int $perPage = 20, array $filters = []): array
    {
        $where = [];
        $params = [];

        if (!empty($filters['search'])) {
            $where[] = '(name LIKE :s1 OR content LIKE :s2)';
            $params['s1'] = '%' . $filters['search'] . '%';
            $params['s2'] = '%' . $filters['search'] . '%';
        }

        if (!empty($filters['status'])) {
            $where[] = 'status = :status';
            $params['status'] = $filters['status'];
        }

        $perPage = max(1, $perPage);
        $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
        $offset = ($page - 1) * $perPage;

        $total = (int) $this->queryOne(
            "SELECT COUNT(*) as cnt FROM {$this->table} {$whereClause}",
            $params
        )['cnt'];

        $items = $this->query(
            "SELECT * FROM {$this->table} {$whereClause}
             ORDER BY name ASC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return [
            'items' => $items,
            'total' => $total,
            'page' => $page,
            'per_page' => $perPage,
            'total_pages' => (int) ceil($total / max(1, $perPage)),
        ];
    }
}
