<?php
/**
 * app/plugins/bookmarks/models/folders.php
 *
 * This class is used for the manipulation of the folders database table.
 *
 * @package TP Bookmarks
 * @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\Canary\Bin\Canary as Debug;
use TheTempusProject\Classes\DatabaseModel;
use TheTempusProject\TheTempusProject as App;
use TheTempusProject\Houdini\Classes\Filters;
use TheTempusProject\Canary\Classes\CustomException;

class Folders extends DatabaseModel {
    public $tableName = 'folders';
    public $databaseMatrix = [
        [ 'title', 'varchar', '256' ],
        [ 'color', 'varchar', '48' ],
        [ 'privacy', 'varchar', '48' ],
        [ 'description', 'text', '' ],
        [ 'folderID', 'int', '11' ],
        [ 'createdBy', 'int', '11' ],
        [ 'createdAt', 'int', '11' ],
        [ 'uuid', 'char', '36' ],
    ];

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

    public function findByUuid( $id ) {
        $whereClause = ['uuid', '=', $id];
        if ( empty( $limit ) ) {
            $folders = self::$db->get( $this->tableName, $whereClause );
        } else {
            $folders = self::$db->get( $this->tableName, $whereClause, 'ID', 'DESC', [0, $limit] );
        }
        if ( !$folders->count() ) {
            Debug::info( 'No Folders found.' );
            return false;
        }
        return $this->filter( $folders->first() );
    }

    public function create( $title, $folderID = 0, $description = '', $color = 'default', $privacy = 'private', $user = null ) {
        if ( empty( $user ) ) {
            $user = App::$activeUser->ID;
        }
        if ( ! Check::dataTitle( $title ) ) {
            Debug::info( 'Folders: illegal title.' );
            return false;
        }
        $fields = [
            'title' => $title,
            'description' => $description,
            'color' => $color,
            'privacy' => $privacy,
            'uuid' => generateUuidV4(),
            'createdBy' => $user,
            'createdAt' => time(),
        ];
        
        if ( !empty( $folderID ) ) {
            $fields['folderID'] = $folderID;
        }
        if ( ! self::$db->insert( $this->tableName, $fields ) ) {
            new CustomException( 'folderCreate' );
            Debug::error( "Folders: not created " . var_export($fields,true) );
            return false;
        }
        return self::$db->lastId();
    }

    public function update( $id, $title, $folderID = 0, $description = '', $color = 'default', $privacy = 'private' ) {
        if ( !Check::id( $id ) ) {
            Debug::info( 'Folders: illegal ID.' );
            return false;
        }
        if ( !Check::dataTitle( $title ) ) {
            Debug::info( 'Folders: illegal title.' );
            return false;
        }
        $fields = [
            'title' => $title,
            'description' => $description,
            'color' => $color,
            'privacy' => $privacy,
        ];
        if ( !empty( $folderID ) ) {
            $fields['folderID'] = $folderID;
        }
        if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
            new CustomException( 'folderUpdate' );
            Debug::error( "Folders: $id not updated: $fields" );
            return false;
        }
        return true;
    }

    public function byUser( $limit = null ) {
        $whereClause = ['createdBy', '=', App::$activeUser->ID];
        if ( empty( $limit ) ) {
            $folders = self::$db->get( $this->tableName, $whereClause );
        } else {
            $folders = self::$db->get( $this->tableName, $whereClause, 'ID', 'DESC', [0, $limit] );
        }
        if ( !$folders->count() ) {
            Debug::info( 'No Folders found.' );
            return false;
        }
        return $this->filter( $folders->results() );
    }

    public function bySpecificUser( $userID, $limit = null ) {
        $whereClause = ['createdBy', '=', $userID];
        if ( empty( $limit ) ) {
            $folders = self::$db->get( $this->tableName, $whereClause );
        } else {
            $folders = self::$db->get( $this->tableName, $whereClause, 'ID', 'DESC', [0, $limit] );
        }
        if ( !$folders->count() ) {
            Debug::info( 'No Folders found.' );
            return false;
        }
        return $this->filter( $folders->results() );
    }

    public function getName( $id ) {
        $folder = self::findById( $id );
        if (false == $folder) {
            return 'unknown';
        }
        return $folder->title;
    }

    public function getColor( $id ) {
        $folder = self::findById( $id );
        if (false == $folder) {
            return 'default';
        }
        return $folder->color;
    }

    public function simpleByUser() {
        $whereClause = ['createdBy', '=', App::$activeUser->ID];
        $folders = self::$db->get( $this->tableName, $whereClause );
        if ( !$folders->count() ) {
            Debug::warn( 'Could not find any folders' );
            return false;
        }
        
        $folders = $folders->results();
        $out = [];
        $out[ 'No Folder' ] = 0;
        foreach ( $folders as $folder ) {
            $out[ $folder->title ] = $folder->ID;
        }
        return $out;
    }

    public function simpleObjectByUser() {
        $whereClause = ['createdBy', '=', App::$activeUser->ID];
        $folders = self::$db->get( $this->tableName, $whereClause );
        if ( !$folders->count() ) {
            Debug::warn( 'Could not find any folders' );
            return false;
        }
        
        $folders = $folders->results();
        $out = [];
        foreach ( $folders as $folder ) {
            $obj = new \stdClass();
            $obj->title = $folder->title;
            $obj->ID = $folder->ID;
            $out[] = $obj;
        }
        return $out;
    }
    
    public function filter( $data, $params = [] ) {
        foreach ( $data as $instance ) {
            if ( !is_object( $instance ) ) {
                $instance = $data;
                $end = true;
            }
            // Real Work Starts Here
            $instance->prettyPrivacy = ucfirst( $instance->privacy );
            $instance->prettyTitle = ucfirst( $instance->title );

            if ( $instance->privacy == 'private' ) {
                $instance->privacyBadge = '<span class="mx-2 translate-center badge bg-success rounded-pill">Private</span>';
            } else {
                $instance->privacyBadge = '<span class="mx-2 translate-center badge rounded-pill bg-danger">Public</span>';
            }

            // Real Work Ends Here
            $out[] = $instance;
            if ( !empty( $end ) ) {
                $out = $out[0];
                break;
            }
        }
        return $out;
    }
}
