<?php

declare(strict_types=1);

namespace App\Models;

class TechnicalMaterial extends BaseModel
{
    protected string $table = 'technical_materials';
    protected string $primaryKey = 'id';

    public function findByToken(string $token): ?array
    {
        $rows = $this->query(
            "SELECT * FROM {$this->table} WHERE public_token = :token LIMIT 1",
            ['token' => $token]
        );
        return $rows[0] ?? null;
    }

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

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

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

        if (!empty($filters['category_id'])) {
            $where[] = 'm.category_id = :category_id';
            $params['category_id'] = (int) $filters['category_id'];
        }

        if (!empty($filters['status'])) {
            $where[] = 'm.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} m {$whereClause}",
            $params
        )['cnt'];

        $items = $this->query(
            "SELECT m.*, u.name as created_by_name, mc.name as category_name
             FROM {$this->table} m
             LEFT JOIN users u ON m.created_by = u.id
             LEFT JOIN material_categories mc ON m.category_id = mc.id
             {$whereClause}
             ORDER BY m.created_at DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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