<?php
/**
 * app/plugins/updates/models/update.php
 *
 * This class is used for the manipulation of the status_updates database table.
 *
 * @package TP Status-Updates
 * @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\Classes\Config;
use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Canary\Bin\Canary as Debug;
use TheTempusProject\Classes\DatabaseModel;
use TheTempusProject\Plugins\Updates as Plugin;
use TheTempusProject\TheTempusProject as App;

class Update extends DatabaseModel {
    public $tableName = 'status_updates';
    public $databaseMatrix = [
        [ 'status', 'varchar', '512' ],
        [ 'createdAt', 'int', '10' ],
        [ 'createdBy', 'int', '10' ],
        [ 'updatedAt', 'int', '10' ],
        [ 'updatedBy', 'int', '10' ],
        [ 'deletedAt', 'int', '10' ],
        [ 'deletedBy', 'int', '10' ],
    ];
    public $plugin;

    /**
     * The model constructor.
     */
    public function __construct() {
        parent::__construct();
        $this->plugin = new Plugin;
    }
    public function create( $status ) {
        if ( ! $this->plugin->checkEnabled() ) {
            Debug::info( 'Status-Updates are disabled in the config.' );
            return false;
        }
        $fields = [
            'status' => $status,
            'createdAt' => time(),
            'createdBy' => App::$activeUser->ID,
        ];
        if ( !self::$db->insert( $this->tableName, $fields ) ) {
            Debug::info( 'Status-Updates::create - failed to insert to db' );
            return false;
        }
        return self::$db->lastId();
    }
    public function update( $status ) {
        if ( !$this->plugin->checkEnabled() ) {
            Debug::info( 'Status-Updates are disabled in the config.' );
            return false;
        }
        $fields = [
            'status' => $status,
            'updatedAt' => time(),
            'updatedBy' => App::$activeUser->ID,
        ];
        if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
            Debug::info( 'Status-Updates::update - failed to update to db' );
            return false;
        }
        return true;
    }
    public function byUser( $userID, $limit = null ) {
        $whereClause = [ 'createdBy', '=', $userID ];
        if ( empty( $limit ) ) {
            $reviews = self::$db->get( $this->tableName, $whereClause );
        } else {
            $reviews = self::$db->get( $this->tableName, $whereClause, 'ID', 'DESC', [0, $limit] );
        }
        if ( !$reviews->count() ) {
            Debug::info( 'No Reviews found.' );
            return false;
        }
        return $this->filter( $reviews->results() );
    }
}
