<?php
namespace App\Controllers;

use \Core\View;
use App\Models\Post;
use App\Models\Access;
use \Core\Token;
use \Core\Session;
use \Core\Redirect;
use \Core\XSS;
use \Michelf\Markdown;

class Posts
{
    private $post;

    public function __construct()
    {
        $this->model = new Post();
    }

    public function checkValid()
    {
        $date = new \DateTime();
        $now = $date->format("Y-m-d");

        $data = [];

        $valid_data = $this->model->showAll([
            ['valid_at', '<=', $now],
            ['status', '!=', 0]
        ]);
        if ($valid_data != false) {
            if (array_key_exists(0, $valid_data)) {
                $data = $valid_data;
            } else {
                $data[] = $valid_data;
            }

            foreach ($data as $fields) {
                $id = $fields['id'];
                $this->model->update(['status' => 1], $id);
            }

            $data = [];
        }

        $notvalid_data = $this->model->showAll([
            ['valid_at', '>', $now],
            ['status', '!=', 0]
        ]);
        if ($notvalid_data != false) {
            if (array_key_exists(0, $notvalid_data)) {
                $data = $notvalid_data;
            } else {
                $data[] = $notvalid_data;
            }

            foreach ($data as $fields) {
                $id = $fields['id'];
                $this->model->update(['status' => 2], $id);
            }

            $data = [];
        }

        $expired_data = $this->model->showAll([
            ['expired_at', '<', $now],
            ['status', '!=', 0]
        ]);
        if ($expired_data != false) {
            if (array_key_exists(0, $expired_data)) {
                $data = $expired_data;
            } else {
                $data[] = $expired_data;
            }

            foreach ($data as $fields) {
                $id = $fields['id'];
                $this->model->update(['status' => 0], $id);
            }

            $data = [];
        }
    }

    /* Routes */
    public function index($args = '')
    {
        $this->checkValid();

        $datas = [];

        $data = $this->model->showJoin([
            ['pengumuman.status', '=', 1]
        ]);

        $url = 'Data/pengumuman.html';
        $user = [];

        if (Session::exists('userid')) {
            $data = $this->model->showJoin();
            if ($args != '') {
                $data = $this->model->showJoin([
                    ['pengumuman.status', '=', $args]
                ]);
            }
            $user = $_SESSION;
            unset($user['tokens']);
        }

        if ($data !== false) {
            if (array_key_exists(0, $data)) {
                $datas = $data;
            } else {
                $datas[] = $data;
            }

            // Replace \n or \r with <br />
            for ($i=0; $i < count($datas); $i++) {
                $datas[$i]['content'] = preg_replace('/\r\n/', '<br />', $datas[$i]['content']);
            }
        }

        View::render($url, [
            'posts' => $datas,
            'user' => $user,
            'token' => Token::generate()
        ]);
    }

    public function entry()
    {
        if (Session::exists('userid')) {
            $date = new \DateTime();
            $now = $date->format("Y-m-d");

            $get_categories = $this->model->showAll([
                ['status', '!=', 0]
            ], 'kategori');
            $categories = [];

            if ($get_categories) {
                if (array_key_exists(0, $get_categories)) {
                    $categories = $get_categories;
                } else {
                    $categories[] = $get_categories;
                }
            }

            $user = Session::get('userid');

            View::render('Data/entry_pengumuman.html', [
                'categories' => $categories,
                'timestamp' => $now,
                'user' => $user,
                'token' => Token::generate()
            ]);
        } else {
            throw new \Exception("Page not found", 404);
        }
    }

    public function edit($id)
    {
        if (Session::exists('userid')) {
            if ($id) {
                $id = implode('', $id);

                $get_categories = $this->model->showAll([
                    ['status', '=', 1]
                ], 'kategori');

                if (array_key_exists(0, $get_categories)) {
                    $categories = $get_categories;
                } else {
                    $categories[] = $get_categories;
                }

                $post = $this->model->showAll([
                    ['id', '=', $id]
                ]);
                $creator = $post['creator'];
                $editor = $post['editor'];

                // Decode XSS data
                $post = XSS::decode($post);

                $table = 'users';

                $creator = $this->model->showAll([
                    ['id', '=', $creator]
                ], $table);
                $editor = $this->model->showAll([
                    ['id', '=', $editor]
                ], $table);

                $editor_now = $this->model->showAll([
                    ['id', '=', Session::get('userid')]
                ], $table);

                $date = new \DateTime();
                $timestamp = $date->format("Y-m-d");

                View::render(
                    'Data/edit_pengumuman.html',
                    [
                        'post' => $post,
                        'categories' => $categories,
                        'creator' => $creator,
                        'editor' => $editor,
                        'editor_now' => $editor_now,
                        'timestamp' => $timestamp,
                        'token' => Token::generate()
                    ]
                );
            }
        } else {
            throw new \Exception("Page not found", 404);
        }
    }

    public function category($id = null)
    {
        if (Session::exists('userid')) {
            if (Session::get('privilege') != 1)  {
                Session::flash('info', 'Hanya admin yang bisa mengatur kategori');
                Redirect::to('/');
                die();
            }
            $categories = [];
            $values = [];
            $method = '';
            if ($id != null) {
                $id = implode('', $id);
                $get_categories = $this->model->showAll([
                    ['id', '=', $id]
                ], 'kategori');
                $method = 'put';
                $values = $get_categories;
            } else {
                $get_categories = $this->model->showAll([], 'kategori');
                $method = 'post';
            }

            if ($get_categories) {
                if (!array_key_exists(0, $get_categories)) {
                    $categories[] = $get_categories;
                } else {
                    $categories = $get_categories;
                }
            }

            View::render('Data/kategori.html', [
                'categories' => $categories,
                'token' => Token::generate(),
                'method' => $method,
                'value' => $values
            ]);
        } else {
            throw new \Exception("Page not found", 404);
        }
    }

    /* Methods */
    public function post($args = [])
    {
        if (isset($args['_addon'])) {
            $table = $args['_addon'];
            unset($args['_addon']);
        }

        foreach ($args as $value) {
            if ($value == '') {
                Session::flash('info', 'Semua data harus diisi');
                if (isset($table)) {
                    Redirect::to("/posts/category");
                } else {
                    Redirect::to('/posts/entry');
                }
                die();
            }
        }

        // Avoid XSS attack
        $args = XSS::avoid($args);

        if (isset($table)) {
            if ($this->model->entry($args, $table)) {
                Session::flash('info', 'Data berhasil diunggah');
                Redirect::to('/posts/category');
            }
        } else {
            if ($this->model->entry($args)) {
                Session::flash('info', 'Data berhasil diunggah');
                Redirect::to('/');
            }
        }
        die();
    }

    public function put($args)
    {
        if (isset($args['_addon'])) {
            $table = $args['_addon'];
            unset($args['_addon']);

            $this->model->update($args, $args['id'], $table);

            Session::flash('info', 'Data berhasil diperbarui');
            Redirect::to('/posts/category');
            die();
        }

        // Avoid XSS attack
        $args = XSS::avoid($args);

        $id = $args['id'];
        unset($args['id']);

        // Check if data same with old data
        $keys = array_keys($args);
        $old_data = [];

        if ($matches = preg_grep('/^old_/', $keys)) {
            foreach ($matches as $match) {
                $old_data[] = $args[$match];
                unset($args[$match]);
            }
            $new_data = [
                $args['category'],
                $args['content'],
                $args['valid_at'],
                $args['expired_at']
            ];
            if ($old_data == $new_data) {
                Session::flash('info', 'Tidak ada data yang diubah');
                Redirect::to("./$id");
                die();
            }
        }

        foreach ($args as $key => $val) {
            if (strpos($val, "##date##") !== false) {
                $date = new \DateTime();
                $now = $date->format("Y-m-d");
                $args[$key] = $now;
            }
        }

        if ($this->model->update($args, $id)) {
            Session::flash('info', 'Data berhasil diperbarui');
            Redirect::to('/');
        } else {
            Session::flash('info', 'Terjadi kesalahan. Silahkan coba lagi dalam beberapa saat');
            Redirect::to("./$id");
        }
        die();
    }

    public function delete($args = [])
    {
        if (isset($args['_addon'])) {
            $table = $args['_addon'];
            unset($args['_addon']);
        }

        $id = $args['id'];
        unset($args['id']);

        if (isset($table)) {
            $delete = $this->model->update($args, $id, $table);
        } else {
            $delete = $this->model->update($args, $id);
        }

        if ($delete == true) {
            $info = 'Data berhasil dinonaktifkan.';
        } else {
            $info = 'Terjadi kesalahan. Silahkan coba lagi dalam beberapa saat';
        }

        Session::flash('info', $info);

        if (isset($table)) {
            Redirect::to("/posts/category");
        } else {
            Redirect::to('/');
        }
        die();
    }
}
