<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    use Coduo\PHPHumanizer\DateTimeHumanizer;

    class Main extends MY_Controller
    {

        public function __construct()
        {
            parent::__construct('home', 'profile');
            $this->load->model('YoutubePlayerModel', '', TRUE);
            $this->load->model('SocialMediaModel', '', TRUE);
            $this->load->model('UserModel', '', TRUE);
            $this->load->model('NotificationModel', '', TRUE);
            $this->load->model('PostsModel', '', TRUE);
        }

        public function index()
        {
            // TODO: Add twitch, instagram and 500px as further services

            $video = $this->YoutubePlayerModel->newestVids(1)[0];

            $currentlyActiveUsers = $this->UserModel->getActiveUsers(5);
            $newestUsers = $this->UserModel->getNewestUsers(5);
            $newestPosts = $this->PostsModel->getNewestPosts(3, 128);

            $this->load->view('header', ['active' => 'home', 'title' => lang('home_sitetitle'), 'additionalStyles' => ['lib/social-media-font.css', 'sortlist.css', 'home.css']]);
            $this->load->view('home', ['video' => $video, 'currentlyActiveUsers' => $currentlyActiveUsers, 'newestUsers' => $newestUsers, 'newestPosts' => $newestPosts]);
            $this->load->view('footer', ['additionalScripts' => ['lib/isotope.pkgd.min.js', 'home.js']]);
        }

        public function getPosts()
        {
            $amount = (int)$this->input->get('amount');
            $offset = $this->input->get('offset') * $amount;
            $category = $this->input->get('category');
            if ($category == "*") {
                $items = $this->SocialMediaModel->getPosts($amount, $offset);
            } else {
                $items = $this->SocialMediaModel->getPostsOfCategory($amount, $offset, explode(".", $category)[1]);
            }
            $font_sizes = [27, 27, 24, 24, 24, 20, 16, 16, 14, 14, 12, 11, 10];
            foreach ($items as $item) {
                $post_date = $item['post_date'];
                $item['post_date'] = DateTimeHumanizer::difference(new \DateTime(), new \DateTime("@$post_date"), $_SESSION['site_lang']);
                $item['font_sizes'] = $font_sizes;
                $this->load->view('post_list_entry', $item);
            }
        }

        public function addFeedback()
        {
            $url = $this->input->post('url');
            $message = $this->input->post('message');
            $anonymous = filter_var($this->input->post('anonymous'), FILTER_VALIDATE_BOOLEAN);
            var_dump($anonymous);
            $email = NULL;
            $userID = NULL;

            if (!$anonymous && !empty($_SESSION['user'])) {
                $userID = $_SESSION['user']['ID'];
            }

            $this->GeneralModel->addFeedback($url, $message, $anonymous, $userID, $email);
        }

        public function contactTeam()
        {
            $message = $this->input->post('message');
            $email = $this->input->post('email');
            $notice = ['type' => false, 'message' => ''];

            if (isset($message) && $message != "") {
                if ($email != "" || isset($_SESSION['user'])) {
                    if (isset($_SESSION['user']))
                        $email = $this->UserModel->getUser($_SESSION['user']['username'])[0]['email'];
                    if (preg_match("/[A-Za-z._]+@[A-Za-z._]+\.[A-Za-z._]+/", $email)) {
                        // TODO: Send contact mail

                        $userID = isset($_SESSION['user']) ? $_SESSION['user']['ID'] : null;

                        $this->GeneralModel->addContactMessage($email, $userID, $message);

                        $this->EmailModel->sendMail('contact@kingofdog.eu', "Neue Nachricht von $email", 'contact_message', ['email' => $email, 'message' => $message]);

                        $notice['type'] = true;
                        $notice['message'] = "Deine Nachricht wurde versendet!";
                    } else {
                        $notice['message'] = "Die eingebene E-Mail-Adresse ist ungültig!";
                    }
                } else {
                    $notice['message'] = "Bitte gib eine E-Mail-Adresse ein oder melde dich an.";
                }
            } else {
                $notice['message'] = "Bitte gib eine zu versendende Nachricht ein.";
            }

            echo json_encode($notice);
            header('Content-Type: application/json');
        }

        public function stillAlive()
        {
            if (isset($_SESSION['user']) && !empty($_SESSION['user'])) {
                $this->UserModel->updateOnline(intval($_SESSION['user']['ID']));
            }
            redirect(base_url());
        }

        public function getNotifications()
        {
            header('Content-Type: application/json');
            if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
                echo json_encode(['status' => 'error', 'message' => 'Du musst eingeloggt sein, um Benachrichtigungen zu empfangen.']);
                exit;
            }

            $count = (int) $this->input->post('count');
            $offset = (int) $this->input->post('offset');

            $returnData = ['status' => 'success', 'notifications' => []];

            $notifications = $this->NotificationModel->getUserNotifications($_SESSION['user']['ID'], $count, $count * $offset);
            $returnData['notifications'] = $notifications;

            echo json_encode($returnData);
        }

        public function notificationsRead() {
            header('Content-Type: application/json');
            if(!isset($_SESSION['user']) || empty($_SESSION['user'])) {
                echo json_encode(['success' => false, 'message' => 'Du musst eingeloggt sein, um Benachrichtigungen zu empfangen.']);
                exit;
            }

            $this->NotificationModel->markUserNotificationsAsRead($_SESSION['user']['ID']);

            echo json_encode(['success' => true]);
        }
    }