<?php

declare(strict_types=1);

namespace App\Models;

class Product extends BaseModel
{
    protected string $table = 'products';
    protected string $primaryKey = 'id';

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

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

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

        if (!empty($filters['category'])) {
            $where[] = 'category LIKE :category';
            $params['category'] = '%' . $filters['category'] . '%';
        }

        $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)),
        ];
    }
}
