<?php
/**
 * app/plugins/notifications/controllers/notifications.php
 *
 * This is the home controller for the notifications plugin.
 *
 * @package TP Notifications
 * @version 5.0.1
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Controllers;

use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Houdini\Classes\Issues;
use TheTempusProject\Classes\Controller;
use TheTempusProject\Models\Notification as NotificationsModel;
use TheTempusProject\TheTempusProject as App;
use TheTempusProject\Hermes\Functions\Redirect;
use TheTempusProject\Bedrock\Functions\Session;

class Notifications extends Controller {
    protected static $notifications;

    public function __construct() {
        parent::__construct();
        self::$notifications = new NotificationsModel;
        self::$title = 'Notifications - {SITENAME}';
        self::$pageDescription = 'Your recent notifications';
        if ( ! App::$isLoggedIn ) {
            Session::flash( 'error', 'You do not have permission to access this page.' );
            return Redirect::home();
        }
    }

    public function index() {
        $notifications = self::$notifications->getByUser( 10 );
        Views::view( 'notifications.list', $notifications );
    }

    public function markRead( $id = null ) {
        $notification = self::$notifications->findById( $id );
        if ( $notification == false ) {
            Issues::add( 'error', 'Notification not found.' );
            return $this->index();
        }
        if ( $notification->userID != App::$activeUser->ID ) {
            Issues::add( 'error', 'You do not have permission to modify this notification.' );
            return $this->index();
        }
        $result = self::$notifications->markSeen( $id );
        if ( $result == true ) {
            Issues::add( 'success', 'Notification marked as read.' );
        } else {
            Issues::add( 'notice', 'There was an problem updating your notification.' );
        }
        return $this->index();
    }

    public function delete( $id = null ) {
        $notification = self::$notifications->findById( $id );
        if ( $notification == false ) {
            Issues::add( 'error', 'Notification not found.' );
            return $this->index();
        }
        if ( $notification->userID != App::$activeUser->ID ) {
            Issues::add( 'error', 'You do not have permission to modify this notification.' );
            return $this->index();
        }
        $result = self::$notifications->delete( $id );
        if ( $result == true ) {
            Issues::add( 'success', 'Notification deleted.' );
        } else {
            Issues::add( 'notice', 'There was an problem deleting your notification.' );
        }
        return $this->index();
    }
}
