<?php
/**
 * app/plugins/comments/controllers/admin/comments.php
 *
 * This is the comments admin controller.
 *
 * @package TP Comments
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Controllers\Admin;

use TheTempusProject\Houdini\Classes\Navigation;
use TheTempusProject\Houdini\Classes\Issues;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Houdini\Classes\Components;
use TheTempusProject\Bedrock\Functions\Input;
use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Classes\Forms;
use TheTempusProject\Classes\AdminController;
use TheTempusProject\Models\Comments as CommentsModel;

class Comments extends AdminController {
    protected static $comments;

    public function __construct() {
        parent::__construct();
        self::$title = 'Admin - Comments';
        self::$comments = new CommentsModel;
        $view = Navigation::activePageSelect( 'nav.admin', '/admin/comments' );
        Components::set( 'ADMINNAV', $view );
    }

    public function edit( $data = null ) {
        if ( !Input::exists( 'submit' ) ) {
            return Views::view( 'comments.admin.edit', self::$comments->findById( $data ) );
        }
        if ( !Forms::check( 'editComment' ) ) {
            Issues::add( 'error', [ 'There was an error with your request.' => Check::userErrors() ] );
            return Views::view( 'comments.admin.edit', self::$comments->findById( $data ) );
        }
        if ( self::$comments->update( $data, Input::post( 'comment' ) ) ) {
            Issues::add( 'success', 'Comment updated' );
        } else {
            return Views::view( 'comments.admin.edit', self::$comments->findById( $data ) );
        }
        $this->index();
    }

    public function viewComments( $contentIID = null ) {
        if ( empty( $contentIID ) ) {
            Issues::add( 'error', 'Content ID not found.' );
            return $this->index();
        }
        $contentData = self::$comments->findById( $data );
        if ( empty( $contentIID ) ) {
            return Views::view( 'comments.list', $commentData );
        }
        Issues::add( 'error', 'Comment not found.' );
        $this->index();
    }

    public function delete( $data = null ) {
        if ( $data == null ) {
            if ( !Input::exists( 'C_' ) ) {
                return $this->index();
            }
            $data = Input::post( 'C_' );
        }
        if ( !self::$comments->delete( $data ) ) {
            Issues::add( 'error', 'There was an error with your request.' );
        } else {
            Issues::add( 'success', 'Comment has been deleted' );
        }
        $this->index();
    }

    public function index() {
        Views::view( 'comments.admin.list', self::$comments->recent() );
    }
}
