<?php

namespace app\foreignone;

use engine\Model;
use app\MarkupUtil;

class Page
    extends Model
{
    const DB_TABLE = 'pages';

    public int $id;
    public int $parentId;
    public string $title;
    public string $md;
    public string $html;
    public int $ts;
    public int $updateTs;
    public bool $visible;
    public bool $renderTitle;
    public string $shortName;

    public function edit(array $fields) {
        $fields['update_ts'] = time();
        if ($fields['md'] != $this->md || $fields['render_title'] != $this->renderTitle || $fields['title'] != $this->title) {
            $md = $fields['md'];
            if ($fields['render_title'])
                $md = '# '.$fields['title']."\n\n".$md;
            $fields['html'] = MarkupUtil::markdownToHtml($md);
        }
        parent::edit($fields);
    }

    public function isUpdated(): bool {
        return $this->updateTs && $this->updateTs != $this->ts;
    }

    public function getHtml(bool $is_retina, string $user_theme): string {
        return MarkupUtil::htmlImagesFix($this->html, $is_retina, $user_theme);
    }

    public function getUrl(): string {
        return "/{$this->shortName}/";
    }

    public function updateHtml(): void {
        $html = MarkupUtil::markdownToHtml($this->md);
        $this->html = $html;
        getDB()->query("UPDATE pages SET html=? WHERE short_name=?", $html, $this->shortName);
    }


    /**
     * Static methods
     */

    public static function add(array $data): bool {
        $db = getDB();
        $data['ts'] = time();
        $data['html'] = MarkupUtil::markdownToHtml($data['md']);
        if (!$db->insert('pages', $data))
            return false;
        return true;
    }

    public static function delete(Page $page): void {
        getDB()->query("DELETE FROM pages WHERE short_name=?", $page->shortName);
        PreviousText::delete(PreviousText::TYPE_PAGE, $page->get_id());
    }

    public static function getById(int $id): ?Page {
        $db = getDB();
        $q = $db->query("SELECT * FROM pages WHERE id=?", $id);
        return $db->numRows($q) ? new Page($db->fetch($q)) : null;
    }

    public static function getByName(string $short_name): ?Page {
        $db = getDB();
        $q = $db->query("SELECT * FROM pages WHERE short_name=?", $short_name);
        return $db->numRows($q) ? new Page($db->fetch($q)) : null;
    }

    /**
     * @return Page[]
     */
    public static function getAll(): array {
        $db = getDB();
        return array_map(static::create_instance(...), $db->fetchAll($db->query("SELECT * FROM pages")));
    }
}
