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

class Positions extends DatabaseModel {
    public $tableName = 'positions';
    public $databaseMatrix = [
        [ 'name', 'varchar', '128' ],
        [ 'position', 'varchar', '128' ],
        [ 'start', 'varchar', '16' ],
        [ 'end', 'varchar', '16' ],
        [ 'details', 'text', '' ],
        [ 'details_nobs', 'text', '' ],
        [ 'image', 'varchar', '256' ],
    ];
    public $plugin;

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

    public function create( $name, $position, $start, $end, $details, $detailsNobs = '' ) {
        if ( !$this->plugin->checkEnabled() ) {
            Debug::info( 'Resume is disabled in the config.' );
            return false;
        }
        if ( empty( $detailsNobs ) ) {
            $detailsNobs = $details;
        }
        $fields = [
            'name' => $name,
            'position' => $position,
            'start' => $start,
            'end' => $end,
            'details' => $details,
            'details_nobs' => $detailsNobs,
        ];
        if ( !self::$db->insert( $this->tableName, $fields ) ) {
            Debug::info( 'Position::create - failed to insert to db' );
            return false;
        }
        return self::$db->lastId();
    }
    
    public function filter( $postArray, $params = [] ) {
        foreach ( $postArray as $instance ) {
            if ( !is_object( $instance ) ) {
                $instance = $postArray;
                $end = true;
            }
            $instance->prettyStart = $instance->start;
            $instance->prettyEnd = $instance->end;
            $out[] = $instance;
            if ( !empty( $end ) ) {
                $out = $out[0];
                break;
            }
        }
        return $out;
    }
    
    public function update( $id, $fields ) {
        if ( !Check::id( $id ) ) {
            Debug::info( 'Positions:update: illegal ID.' );
            return false;
        }
        if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
            // new CustomException( 'positionUpdate' );
            Debug::error( "Positions:update: $id not updated: $fields" );
            return false;
        }
        return true;
    }
}
