<?php

namespace App\Models;

use App\Core\Model;

class Page extends Model
{
    protected string $table = 'pages';

    public function all(): array
    {
        return $this->db->query("SELECT * FROM pages ORDER BY created_at DESC")->fetchAll();
    }

    public function findBySlug(string $slug): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM pages WHERE slug = ? AND is_active = 1");
        $stmt->execute([$slug]);
        return $stmt->fetch() ?: null;
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare(
            "INSERT INTO pages (title, slug, content) VALUES (?, ?, ?)"
        );
        $stmt->execute([$data['title'], $data['slug'], $data['content']]);
        return (int)$this->db->lastInsertId();
    }

    public function update(int $id, array $data): bool
    {
        $stmt = $this->db->prepare(
            "UPDATE pages SET title = ?, content = ?, is_active = ? WHERE id = ?"
        );
        return $stmt->execute([$data['title'], $data['content'], $data['is_active'] ?? 1, $id]);
    }
}
