<?php

namespace App\Models;

use CodeIgniter\Model;

class BeritaModel extends Model

{
    protected $table            = 'berita';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'judul',
        'slug',
        'kategori',
        'ringkasan',
        'konten',
        'gambar',
        'penulis',
        'is_published',
        'tanggal_publish'
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation
protected $validationRules = [
    'id'       => 'permit_empty|is_natural_no_zero',

    'judul'    => 'required|min_length[3]',
    'slug'     => 'permit_empty|is_unique[berita.slug,id,{id}]',

    // penting: supaya konten tidak "hilang" / tidak terbuang saat cleanValidationRules = true
    'kategori' => 'required|in_list[pengumuman,kegiatan,prestasi]',
    'ringkasan'=> 'permit_empty|string',
    'konten'   => 'required|string', // <-- ini kuncinya agar [CEK_KELULUSAN] tidak hilang

    'gambar'   => 'permit_empty|string',
    'penulis'  => 'permit_empty|string',
    'is_published'     => 'permit_empty|in_list[0,1]',
    'tanggal_publish'  => 'permit_empty|valid_date',
];

    protected $validationMessages = [
        'judul' => [
            'required'    => 'Judul berita harus diisi',
            'min_length'  => 'Judul minimal 5 karakter',
            'max_length'  => 'Judul maksimal 255 karakter',
        ],
        'kategori' => [
            'required' => 'Kategori harus dipilih',
            'in_list'  => 'Kategori tidak valid',
        ],
        'konten' => [
            'required'   => 'Konten berita harus diisi',
            'min_length' => 'Konten minimal 20 karakter',
        ],
    ];

    protected $skipValidation       = false;
    protected $cleanValidationRules = false;

    // Callbacks
    protected $beforeInsert = ['generateSlug'];
    protected $beforeUpdate = ['generateSlug'];

    /**
     * Generate slug from judul
     */
    protected function generateSlug(array $data)
    {
        if (isset($data['data']['judul']) && empty($data['data']['slug'])) {
            $slug = url_title($data['data']['judul'], '-', true);
            
            // Cek apakah slug sudah ada
            $count = $this->where('slug', $slug)->countAllResults();
            
            if ($count > 0) {
                $slug = $slug . '-' . time();
            }
            
            $data['data']['slug'] = $slug;
        }
        
        return $data;
    }

    /**
     * Get berita by kategori
     */
    public function getByKategori($kategori, $limit = 10, $published = true)
    {
        $builder = $this->where('kategori', $kategori);
        
        if ($published) {
            $builder->where('is_published', 1);
        }
        
        return $builder->orderBy('tanggal_publish', 'DESC')
                       ->orderBy('created_at', 'DESC')
                       ->limit($limit)
                       ->find();
    }

    /**
     * Get semua berita terbaru (untuk halaman "Semua Berita")
     */
    public function getSemuaBeritaTerbaru($limit = 10, $published = true)
    {
        $builder = $this;
        
        if ($published) {
            $builder->where('is_published', 1);
        }
        
        return $builder->orderBy('tanggal_publish', 'DESC')
                       ->orderBy('created_at', 'DESC')
                       ->limit($limit)
                       ->find();
    }

    /**
     * Get berita by slug (untuk detail berita)
     */
    public function getBySlug($slug)
    {
        return $this->where('slug', $slug)
                    ->where('is_published', 1)
                    ->first();
    }

    /**
     * Get berita dengan pagination
     */
    public function getBeritaPaginated($kategori = null, $perPage = 10)
    {
        $builder = $this->where('is_published', 1);
        
        if ($kategori) {
            $builder->where('kategori', $kategori);
        }
        
        return $builder->orderBy('tanggal_publish', 'DESC')
                       ->orderBy('created_at', 'DESC')
                       ->paginate($perPage);
    }

    /**
     * Get berita untuk admin (semua status)
     */
    public function getForAdmin($kategori = null, $perPage = 10)
    {
        $builder = $this;
        
        if ($kategori) {
            $builder->where('kategori', $kategori);
        }
        
        return $builder->orderBy('created_at', 'DESC')
                       ->paginate($perPage);
    }

    /**
     * Count berita by kategori
     */
    public function countByKategori($kategori)
    {
        return $this->where('kategori', $kategori)
                    ->where('is_published', 1)
                    ->countAllResults();
    }
    
}