<?php

namespace Amwdeveloper\plugins\posts;

use Amwdeveloper\model\layer;

class home extends layer
{
    public function index()
    {
        $posts = $this->table("amw_notice")->columns("title,tag,date,link,slug,description,account")->limit(99)->orderby("id")->all();
        $setPosts = array();

        if ($posts) {
            foreach ($posts as $post) {
                $setPosts[] = [
                    'title' => $post->title,
                    'tag' => $post->tag,
                    'created' => $post->date,
                    'url' => $post->link,
                    'author' => $post->account,
                    'redirect' => __redirect("post/view/{$post->slug}"),
                    'description' => $post->description
                ];
            }

            return $setPosts;
        }

        return null;
    }

    public function verifyexitpost(array $post)
    {
        global $route;
        $post = filter_var($post['slug'], FILTER_SANITIZE_SPECIAL_CHARS);
        $verify = $this->table("amw_notice")->columns("title")->where("slug = :slug", "slug={$post}")->get();
        if (empty($verify)) return $route->redirect("/");
    }

    public function viewpost(array $post)
    {
        $post = filter_var($post['slug'], FILTER_SANITIZE_SPECIAL_CHARS);
        $infopost = $this->table("amw_notice")->columns("id,title,tag,message,account,date,link,comment")->where("slug = :slug", "slug={$post}")->get();

        $postview = array(
            'id' => $infopost->id,
            'title' => $infopost->title,
            'tag_name' => $infopost->tag,
            'message' => $infopost->message,
            'author' => $infopost->account,
            'date' => date('d/m/Y H:i:s', strtotime($infopost->date)),
            'link' => $infopost->link,
            'comment' => $infopost->comment
        );

        return $postview;
    }

    public function commentspost($id)
    {
        $comments  = $this->table("amw_notice_comments")->columns("id_notice,message,date,account")->where("id_notice = :id", "id={$id}")->orderby("date")->all();
        $commentsview = array();

        foreach ($comments as $comment) {
            $commentsview[] = [
                'id' => $comment->id_notice,
                'message' => $comment->message,
                'author' => $comment->account,
                'date' => date('d/m/Y H:i:s', strtotime($comment->date))
            ];
        }

        return $commentsview ?? null;
    }
}
