<?php

namespace App\Models;

use CodeIgniter\Model;

class NewsModel extends Model
{
    protected $table         = 'news';
    protected $primaryKey    = 'id';
    protected $returnType = 'array';
    protected $allowedFields = ['category', 'tags', 'title', 'slug', 'excerpt', 'content', 'image', 'author', 'published_at', 'status', 'is_featured', 'meta_title', 'meta_description', 'view_count'];
    protected $useTimestamps = true;

    public function getPublished(int $perPage = 6)
    {
        return $this->where('status', 'published')
                    ->orderBy('published_at', 'DESC')
                    ->paginate($perPage);
    }

    public function getBySlug(string $slug)
    {
        return $this->where('status', 'published')
                    ->where('slug', $slug)
                    ->first();
    }

    public function getFeatured(int $limit = 3)
    {
        return $this->where('status', 'published')
                    ->where('is_featured', 1)
                    ->orderBy('published_at', 'DESC')
                    ->findAll($limit);
    }

    public function getRelated($news, int $limit = 3)
    {
        return $this->where('status', 'published')
                    ->where('category', $news['category'])
                    ->where('id !=', $news['id'])
                    ->orderBy('published_at', 'DESC')
                    ->findAll($limit);
    }

    public function search(string $query, int $perPage = 10)
    {
        return $this->where('status', 'published')
                    ->groupStart()
                        ->like('title', $query)
                        ->orLike('content', $query)
                    ->groupEnd()
                    ->orderBy('published_at', 'DESC')
                    ->paginate($perPage);
    }

    public function incrementViews(int $id)
    {
        return $this->db->table($this->table)
                        ->set('view_count', 'view_count + 1', false)
                        ->where('id', $id)
                        ->update();
    }

    public function getPrevPost(int $id, string $publishedAt)
    {
        return $this->where('status', 'published')
                    ->where('id !=', $id)
                    ->where('published_at <=', $publishedAt)
                    ->orderBy('published_at', 'DESC')
                    ->first();
    }

    public function getNextPost(int $id, string $publishedAt)
    {
        return $this->where('status', 'published')
                    ->where('id !=', $id)
                    ->where('published_at >=', $publishedAt)
                    ->orderBy('published_at', 'ASC')
                    ->first();
    }
}
