<?php

namespace App\Modules\Admin\Models;

use CodeIgniter\Model;

class BlogModel extends Model
{
    protected $table = 'blog';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'title',
        'slug',
        'excerpt',
        'content',
        'image',
        'category',
        'tags',
        'meta_title',
        'meta_description',
        'status'
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // REGISTER THE CALLBACKS
    protected $beforeInsert = ['generateSlug'];
    protected $beforeUpdate = ['generateSlug'];

    /**
     * Logic to handle slug generation automatically
     */
    protected function generateSlug(array $data): array
    {
        // For Inserts: use title if slug is missing
        // For Updates: only update slug if title is present and slug is empty
        if (isset($data['data']['title'])) {
            if (!isset($data['data']['slug']) || empty($data['data']['slug'])) {
                $data['data']['slug'] = url_title($data['data']['title'], '-', true);
            }
        }

        return $data;
    }

    /**
     * Get published posts for the frontend
     */
    public function getPublished(int $limit = 0)
    {
        $this->where('status', 'published')
             ->orderBy('created_at', 'DESC');
        
        if ($limit > 0) {
            return $this->findAll($limit);
        }
        
        return $this->findAll();
    }

    /**
     * Optimized for Admin Panel (works with CI4 built-in Pagination)
     */
    public function getFilteredPosts($status = 'all')
    {
        if ($status !== 'all') {
            $this->where('status', $status);
        }
        
        return $this->orderBy('created_at', 'DESC');
    }
}