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

use TheTempusProject\Hermes\Functions\Redirect;
use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Bedrock\Functions\Input;
use TheTempusProject\Bedrock\Functions\Session;
use TheTempusProject\Houdini\Classes\Issues;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Classes\Controller;
use TheTempusProject\Classes\Forms;
use TheTempusProject\Models\Review;
use TheTempusProject\TheTempusProject as App;
use TheTempusProject\Houdini\Classes\Components;
use TheTempusProject\Houdini\Classes\Template;
use TheTempusProject\Models\ReviewCategory;
use TheTempusProject\Houdini\Classes\Forms as HoudiniForms;

class Reviews extends Controller {
    protected static $reviews;
    protected static $categories;

    public function __construct() {
        self::$title = 'Reviews - {SITENAME}';
        self::$pageDescription = 'This page allows you to add a new product review or update your existing reviews.';

        if ( ! App::$isLoggedIn ) {
            Session::flash( 'notice', 'You must be logged in to review products.' );
            return Redirect::home();
        }

        parent::__construct();
        self::$reviews = new Review;
        self::$categories = new ReviewCategory;
        Components::append( 'TEMPLATE_JS_INCLUDES', Template::parse('<script language="JavaScript" crossorigin="anonymous" type="text/javascript" src="{ROOT_URL}app/plugins/reviews/js/reviews.js"></script>' ) );
        Components::append( 'TEMPLATE_CSS_INCLUDES', Template::parse('<link rel="stylesheet" href="{ROOT_URL}app/plugins/reviews/css/reviews.css">') );
    }

    public function index() {
        Views::view( 'reviews.list', self::$reviews->byUser() );
    }

    public function review( $slug = null ) {
        $category = self::$categories->findBySlug( $slug );
        if ( ! $category ) {
            $categories = self::$categories->simpleUnreviewed();
            if ( empty( $categories ) ) {
                Session::flash( 'notice', 'There are no additional products to review at this time.' );
                Redirect::to( 'reviews/index' );
            }
            $selectedCategory = '0';
            $reviewCategorySelect = HoudiniForms::getSelectHtml(
                'review_category_id',
                $categories,
                $selectedCategory,
            );
            Components::set( 'reviewCategorySelect', $reviewCategorySelect );
        } else {
            $selectedCategory = $category->ID;
            Components::set(
                'reviewCategorySelect',
                '<input type="hidden" name="review_category_id" id="review_category_id" value="' . $selectedCategory . '">'
            );
        }
        if ( ! Input::exists('submit') ) {
            return Views::view( 'reviews.create' );
        }
        if ( ! Forms::check( 'createReview' ) ) {
            Issues::add( 'error', [ 'There was an error with your review.' => Check::userErrors() ] );
            return Views::view( 'reviews.create' );
        }
        $result = self::$reviews->create( Input::post('title'), Input::post('rating'), Input::post('review'), Input::post('review_category_id') );
        if ( ! empty( $result ) ) {
            Session::flash( 'success', 'Your review has been received.' );
            Redirect::to( 'reviews/index' );
        } else {
            Issues::add( 'error', 'There was an unresolved error while submitting your review.' );
            return Views::view( 'reviews.create' );
        }
    }

    public function view( $id = null ) {
        $review = $this->confirmOwner( $id );
        Views::view( 'reviews.view', $review );
    }

    public function edit( $id = null ) {
        $review = $this->confirmOwner( $id );

        if ( ! Input::exists( 'submit' ) ) {
            return Views::view( 'reviews.edit', $review );
        }

        if ( ! Forms::check( 'reviewEditPublic' ) ) {
            Issues::add( 'error', [ 'There was an error with your request.' => Check::userErrors() ] );
            return Views::view( 'reviews.edit', $review );
        }
        
        $result = self::$reviews->update(
            $id,
            Input::post('title'),
            Input::post('rating'),
            Input::post('review')
        );

        if ( $result ) {
            Session::flash( 'success', 'Your review has been updated.' );
            return Redirect::to( 'reviews/index' );
        }

        Issues::add( 'error', [ 'There was an error with your request.' => Check::userErrors() ] );
        Views::view( 'reviews.edit', $review );
    }

    public function delete( $id = null ) {
        $this->confirmOwner( $id );
        if ( self::$reviews->delete( $id ) ) {
            Session::flash( 'success', 'Review deleted' );
        } else {
            Session::flash( 'error', 'There was an error with your request.' );
        }
        return Redirect::to( 'reviews/index' );
    }

    private function confirmOwner( $id ) {
        if ( ! App::$isLoggedIn ) {
            Session::flash( 'error', 'You must be logged in to review products.' );
            return Redirect::home();
        }
        if ( !Check::id( $id ) ) {
            Session::flash( 'error', 'Unknown Review' );
            return Redirect::to( 'reviews/index' );
        }
        $review = self::$reviews->findById( $id );
        if ( empty( $review ) ) {
            Session::flash( 'error', 'Unknown Review' );
            return Redirect::to( 'reviews/index' );
        }
        if ( App::$activeUser->ID != $review->createdBy ) {
            Session::flash( 'error', 'Unknown Review' );
            return Redirect::to( 'reviews/index' );
        }
        return $review;
    }
}