<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;
use PDO;

class PageController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_PAGES');
    }

    public function index()
    {
        $pages = db()->query("SELECT P.* FROM Pages P ORDER BY P.id DESC");
        $pages = $pages->fetchAll(PDO::FETCH_ASSOC);

        return view('pages.index', compact('pages'));
    }

    public function create()
    {
        return view('pages.create');
    }

    public function store()
    {
        validate([
            'title' => 'required',
            'content' => 'required'
        ]);
	    
		    $slug = slugify(input("title"));

        $insertPages = db()->prepare("INSERT INTO Pages (title, slug, content, isActive, creationDate) VALUES (?, ?, ?, ?, ?)");
        $insertPages->execute(array(input("title"), $slug, filteredContent($_POST["content"]), 1, datetime()));
        return back()->flash("success", t__('Page has been added successfully!'));
    }

    public function edit($id)
    {
        $page = db()->prepare("SELECT * FROM Pages WHERE id = ?");
        $page->execute(array($id));
        $page = $page->fetch();

        if (!$page) return view('404');

        return view('pages.edit', compact('page'));
    }

    public function update($id)
    {
        validate([
            'title' => 'required',
            'slug' => 'required',
            'content' => 'required',
            'isActive' => 'required'
        ]);

        $updatePages = db()->prepare("UPDATE Pages SET title = ?, slug = ?, content = ?, isActive = ? WHERE id = ?");
        $updatePages->execute(array(input("title"), input("slug"), filteredContent($_POST["content"]), input("isActive"), $id));
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

    public function destroy($id)
    {
        $deletePage = db()->prepare("DELETE FROM Pages WHERE id = ?");
        $deletePage->execute(array($id));
        return back();
    }
}