<?php
/**
 * app/plugins/wip/models/projects.php
 *
 * This class is used for the manipulation of the projects database table.
 *
 * @package TP WIP
 * @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\Wip as Plugin;

class Projects extends DatabaseModel {
    public $tableName = 'projects';
    public $databaseMatrix = [
        [ 'title', 'varchar', '128' ],
        [ 'description', 'text', '' ],
        [ 'progress', 'int', '3' ],
        [ 'startDate', 'varchar', '32' ],
    ];
    public $plugin;

    /**
     * The model constructor.
     */
    public function __construct() {
        parent::__construct();
        $this->plugin = new Plugin;
    }

    public function create( $title, $description, $progress, $startDate ) {
        if ( !$this->plugin->checkEnabled() ) {
            Debug::info( 'Wip is disabled in the config.' );
            return false;
        }
        $fields = [
            'title' => $title,
            'description' => $description,
            'progress' => $progress,
            'startDate' => $startDate,
        ];
        if ( !self::$db->insert( $this->tableName, $fields ) ) {
            Debug::info( 'Projects::create - failed to insert to db' );
            return false;
        }
        return self::$db->lastId();
    }
    
    public function update( $id, $fields ) {
        if ( !Check::id( $id ) ) {
            Debug::info( 'Project:update: illegal ID.' );
            return false;
        }
        if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
            // new CustomException( 'projectUpdate' );
            Debug::error( "Project:update: $id not updated: $fields" );
            return false;
        }
        return true;
    }
    
    public function filter( $postArray, $params = [] ) {
        foreach ( $postArray as $instance ) {
            if ( !is_object( $instance ) ) {
                $instance = $postArray;
                $end = true;
            }
            $instance->prettyStart = $instance->startDate;
            $out[] = $instance;
            if ( !empty( $end ) ) {
                $out = $out[0];
                break;
            }
        }
        return $out;
    }
}
