<?php
namespace App\Models;
use App\Core\Model;

class CmsPage extends Model
{
    protected $table = 'cms_pages';
    protected $primaryKey = 'id';

    public function findBySlug($slug)
    {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE slug = ? LIMIT 1");
        $stmt->execute([$slug]);
        return $stmt->fetch(\PDO::FETCH_OBJ);
    }

    public function getPublished()
    {
        $stmt = $this->db->query("SELECT * FROM {$this->table} WHERE status = 'published' ORDER BY title ASC");
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getAll()
    {
        $stmt = $this->db->query("SELECT cp.*, u.name AS created_by_name FROM {$this->table} cp LEFT JOIN users u ON cp.created_by = u.id ORDER BY cp.updated_at DESC");
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function updateContent($id, $data)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET title = ?, content = ?, meta_title = ?, meta_description = ?, status = ?, updated_by = ? WHERE id = ?");
        return $stmt->execute([
            $data['title'],
            $data['content'],
            $data['meta_title'] ?? null,
            $data['meta_description'] ?? null,
            $data['status'],
            $data['updated_by'],
            $id,
        ]);
    }
}
