<?php
/**
 * app/plugins/suggestions/models/suggestions.php
 *
 * This class is used for the manipulation of the suggestions database table.
 *
 * @package TP Suggest
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Models;

use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Bedrock\Classes\Config;
use TheTempusProject\Canary\Bin\Canary as Debug;
use TheTempusProject\Canary\Classes\CustomException;
use TheTempusProject\Classes\DatabaseModel;
use TheTempusProject\TheTempusProject as App;

class Suggestions extends DatabaseModel {
    public $tableName = 'suggestions';
    public $databaseMatrix = [
        [ 'title', 'varchar', '86' ],
        [ 'suggestion', 'text', '' ],
        [ 'suggestedOn', 'int', '10' ],
        [ 'approved', 'varchar', '5' ],
        [ 'approvedOn', 'int', '10' ],
        [ 'approvedBy', 'int', '11' ],
        [ 'author', 'int', '11' ],
    ];

    /**
     * The model constructor.
     */
    public function __construct() {
        parent::__construct();
    }

    // @TODO: Add a config for some of these things
    // public function enabled() {
    //     if ( true === parent::enabled() ) {
    //         return  Config::getValue( $this->configName . '/enabled' ) === true;
    //     }
    //     return false;
    // }
    public function filter( $data, $params = [] ) {
        foreach ( $data as $instance ) {
            if ( !is_object( $instance ) ) {
                $instance = $data;
                $end = true;
            }
            if ( !empty($instance->approvedBy)) {
                $instance->approvedByName = self::$user->getUsername( $instance->approvedBy );
            } else {
                $instance->approvedByName = '';
            }
            $instance->submittedBy = self::$user->getUsername( $instance->author );
            $out[] = $instance;
            if ( !empty( $end ) ) {
                $out = $out[0];
                break;
            }
        }
        return $out;
    }

    /**
     * Logs a Suggestion form.
     *
     * @param  int $ID           the user ID submitting the form
     * @param  string $url          the url
     * @param  string $o_url        the original url
     * @param  int $repeat       is repeatable?
     * @param  string $description_ description of the event.
     *
     * @return null
     */
    public function create( $title, $suggestion, $approved = 'false' ) {
        if ( !$this->enabled() ) {
            Debug::info( 'Suggestions are disabled in the config.' );
            return false;
        }
        $fields = [
            'author' => App::$activeUser->ID,
            'suggestedOn' => time(),
            'suggestion' => $suggestion,
            'approved' => $approved,
            'title' => $title,
        ];
        if ( !self::$db->insert( $this->tableName, $fields ) ) {
            new CustomException( $this->tableName );
            return false;
        }
        return self::$db->lastId();
    }

    public function update( $ID, $title, $suggestion, $approved = 'false' ) {
        if ( empty( self::$log ) ) {
            self::$log = new Log;
        }
        if ( !Check::id( $ID ) ) {
            Debug::info( 'Suggestion: illegal ID.' );
            return false;
        }
        $fields = [
            'suggestion' => $suggestion,
            'approved' => $approved,
            'title' => $title,
        ];
        if ( !self::$db->update( $this->tableName, $ID, $fields ) ) {
            new CustomException( $this->tableName );
            Debug::error( "Suggestion: $ID not updated: $fields" );

            return false;
        }
        self::$log->admin( "Updated Suggestion: $ID" );
        return true;
    }

    public function approve( $ID  ) {
        if ( empty( self::$log ) ) {
            self::$log = new Log;
        }
        if ( !Check::id( $ID ) ) {
            Debug::info( 'Suggestion: illegal ID.' );
            return false;
        }
        $fields = [
            'approved' => 'true',
            'approvedOn' => time(),
            'approvedBy' => App::$activeUser->ID,
        ];
        if ( !self::$db->update( $this->tableName, $ID, $fields ) ) {
            new CustomException( $this->tableName );
            Debug::error( "Suggestion: $ID not Rejected: $fields" );
            return false;
        }
        self::$log->admin( "Suggestion Rejected: $ID" );
        return true;
    }

    public function reject( $ID ) {
        if ( empty( self::$log ) ) {
            self::$log = new Log;
        }
        if ( !Check::id( $ID ) ) {
            Debug::info( 'Suggestion: illegal ID.' );
            return false;
        }
        $fields = [
            'approved' => 'false',
            'approvedOn' => null,
            'approvedBy' => null,
        ];
        if ( !self::$db->update( $this->tableName, $ID, $fields ) ) {
            new CustomException( $this->tableName );
            Debug::error( "Suggestion: $ID not Approved: $fields" );
            return false;
        }
        self::$log->admin( "Suggestion Approved: $ID" );
        return true;
    }

    public function recent( $approvedOnly = true, $limit = 0 ) {
        if ( true === $approvedOnly ) {
            $where = ['approved', '=', 'true'];
        } else {
            $where = ['ID', '>', '0'];
        }
        if ( empty( $limit ) ) {
            $data = self::$db->getPaginated( $this->tableName, $where, 'suggestedOn', 'DESC' );
        } else {
            $data = self::$db->get( $this->tableName, $where, 'suggestedOn', 'DESC', [0, $limit] );
        }
        if ( !$data->count() ) {
            Debug::info( 'No Suggestions found.' );
            return false;
        }
        return $this->filter( $data->results() );
    }
}
