<?php

namespace Core\App\Models;

class Page
{
    public function getAll()
    {
        return db()->query("
            SELECT * FROM pages
            ORDER BY created_at DESC
        ")->fetchAll();
    }

    /**
     * Get all pages indexed by a specific key (id or slug)
     */
    public function getAllIndexed(string $key = 'id'): array
    {
        $rows = db()->query("
            SELECT *
            FROM pages
        ")->fetchAll();

        $indexed = [];

        foreach ($rows as $row) {
            if (isset($row[$key])) {
                $indexed[$row[$key]] = $row;
            }
        }

        return $indexed;
    }

    public function getAllPublished()
    {
        return db()->query("SELECT * FROM pages WHERE status = 'published' ORDER BY created_at DESC")->fetchAll();
    }

    public function find($id)
    {
        $stmt = db()->prepare("SELECT * FROM pages WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }

    public function findBySlug($slug)
    {
        $stmt = db()->prepare("
            SELECT * FROM pages
            WHERE slug = ?
              AND status = 'published'
            LIMIT 1
        ");
        $stmt->execute([$slug]);
        return $stmt->fetch();
    }

    public function getMenuPages()
    {
        return db()->query("
            SELECT title, slug
            FROM pages
            WHERE status = 'published'
              AND show_in_menu = 1
            ORDER BY created_at ASC
        ")->fetchAll();
    }

    public function create($data)
    {
        $stmt = db()->prepare("
            INSERT INTO pages
            (title, slug, content, status, meta_title, meta_description, show_in_menu)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");

        return $stmt->execute([
            $data['title'],
            $data['slug'],
            $data['content'],
            $data['status'],
            $data['meta_title'] ?? null,
            $data['meta_description'] ?? null,
            isset($data['show_in_menu']) ? 1 : 0,
        ]);
    }

    public function update($id, $data)
    {
        $stmt = db()->prepare("
            UPDATE pages
            SET title = ?, slug = ?, content = ?, status = ?,
                meta_title = ?, meta_description = ?, show_in_menu = ?
            WHERE id = ?
        ");

        return $stmt->execute([
            $data['title'],
            $data['slug'],
            $data['content'],
            $data['status'],
            $data['meta_title'] ?? null,
            $data['meta_description'] ?? null,
            isset($data['show_in_menu']) ? 1 : 0,
            $id
        ]);
    }

    public function delete($id)
    {
        $stmt = db()->prepare("
            DELETE FROM pages
            WHERE id = ?
        ");

        return $stmt->execute([$id]);
    }
}
