<?php
/**
 * app/models/group.php
 *
 * This class is used for the manipulation of the groups database table.
 *
 * @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\Permissions;
use TheTempusProject\Bedrock\Classes\Config;
use TheTempusProject\Bedrock\Functions\Input;
use TheTempusProject\Classes\DatabaseModel;

class Group extends DatabaseModel {
    protected static $user;
    protected static $permissions;
    public $tableName = 'groups';
    public $configName = 'group';
    public $modelVersion = '1.0';
    public static $protectedGroups = [
        'Super', 'Admin', 'Moderator'
    ];
    public $configMatrix = [
        'defaultGroup' => [
            'type' => 'customSelect',
            'pretty' => 'The Default Group for new registrations.',
            'default' => 4,
        ],
    ];
    public $databaseMatrix = [
        [ 'name', 'varchar', '32' ],
        [ 'permissions', 'text', '' ],
    ];
    public $permissionMatrix = [
        'adminAccess' => [
            'pretty' => 'Access Administrator Areas',
            'default' => false,
        ],
    ];
    public $resourceMatrix = [
        [
            'name' => 'Super',
            'permissions' => '{"adminAccess":true}',
        ],
        [
            'name' => 'Admin',
            'permissions' => '{"adminAccess":true}',
        ],
        [
            'name' => 'User',
            'permissions' => '{"adminAccess":false}',
        ],
        [
            'name' => 'Guest',
            'permissions' => '{"adminAccess":false}',
        ],
    ];

    /**
     * The model constructor.
     */
    public function __construct() {
        parent::__construct();
        self::$group = $this;
        self::$permissions = new Permissions;
    }

    public function isEmpty( $id ) {
        if ( !Check::ID( $id ) ) {
            return false;
        }
        $userData = self::$db->get( 'users', [ 'userGroup', '=', $id ] );
        if ( !$userData->count() ) {
            return true;
        }
        return false;
    }

    /**
     * Function to delete the specified group.
     *
     * @param  int|array $ID the log ID or array of ID's to be deleted
     * @return bool
     */
    public function delete( $data ) {
        if ( empty( self::$log ) ) {
            self::$log = new Log;
        }
        if ( !is_array( $data ) ) {
            $data = [ $data ];
        }
        foreach ( $data as $instance ) {
            if ( !Check::id( $instance ) ) {
                $error = true;
            }
            if ( $this->countMembers( $instance ) !== 0 ) {
                Debug::info( 'Group is not empty.' );
                return false;
            }
            if ( $instance == Config::getValue( 'group/defaultGroup' ) ) {
                Debug::info( 'Cannot delete the default group.' );
                return false;
            }
            if ( $instance == '1' ) {
                Debug::info( 'Cannot delete the super group.' );
                return false;
            }
            self::$db->delete( $this->tableName, [ 'ID', '=', $instance ] );
            self::$log->admin( "Deleted group: $instance" );
            Debug::info( "Group deleted: $instance" );
            if ( !empty( $end ) ) {
                break;
            }
        }
        if ( !empty( $error ) ) {
            Debug::info( 'One or more invalid ID\'s.' );
            return false;
        }
        return true;
    }
    
    public function hasPermission( $permission ) {

    }

    // update($data, Input::post('name'), ) {
    public function getPermissionsDelta( $id, $permissions ) {
    }

    public function create( $name, $permissions ) {
        if ( empty( self::$log ) ) {
            self::$log = new Log;
        }
        if ( !Check::dataTitle( $name ) ) {
            Debug::info( 'modelGroup: illegal group name.' );
            return false;
        }
        $fields = [
            'name' => $name,
            'permissions' => json_encode( $permissions ),
        ];
        if ( self::$db->insert( $this->tableName, $fields ) ) {
            self::$log->admin( "Created Group: $name" );
            return true;
        }
        return false;
    }

    public function update( $id, $name, $permissions ) {
        if ( empty( self::$log ) ) {
            self::$log = new Log;
        }
        if ( !Check::id( $id ) ) {
            return false;
        }
        if ( !Check::dataTitle( $name ) ) {
            Debug::info( 'modelGroup: illegal group name.' );
            return false;
        }
        $fields = [
            'name' => $name,
            'permissions' => json_encode( $permissions ),
        ];
        if ( self::$db->update( $this->tableName, $id, $fields ) ) {
            self::$log->admin( "Updated Group: $id" );
            return true;
        }
        return false;
    }

    public function getDefaultPermissions() {
        return self::$permissions->getDefaultPermissionsArray();
    }

    public function filter( $data, $params = [] ) {
        $defaults = $this->getDefaultPermissions();
        foreach ( $data as $instance ) {
            if ( !is_object( $instance ) ) {
                $instance = $data;
                $end = true;
            }
            $toArray = (array) $instance;
            $instance->perms = json_decode( $instance->permissions, true );
            $instance->userCount = $this->countMembers( $instance->ID );
            foreach ( $defaults as $name => $default ) {
                $string_name = $name . '_string';
                $text_name = $name . '_text';
                $pretty_name = $name . '_pretty';
                if ( isset( $instance->perms[ $name ] ) ) {
                    $default = $instance->perms[ $name ];
                }
                $instance->$name = $default;
                $instance->$pretty_name = self::$permissions->getPrettyName( $name );
                if ( $default === true ) {
                    $instance->$string_name = 'true';
                    $instance->$text_name = 'yes';
                } else {
                    $instance->$string_name = 'false';
                    $instance->$text_name = 'no';
                }
            }
            $out[] = $instance;
            if ( !empty( $end ) ) {
                $out = $out[0];
                break;
            }
        }
        return $out;
    }

    public function findByName( $name ) {
        if ( !Check::dataString( $name ) ) {
            Debug::warn( "$this->tableName findByName: illegal name: $name" );
            return false;
        }
        $groupData = self::$db->get( $this->tableName, [ 'name', '=', $name ] );
        if ( !$groupData->count() ) {
            Debug::warn( 'Could not find a group named: ' . $name );
            return false;
        }
        return $this->filter( $groupData->first() );
    }

    public function listGroupsSimple( $include_all = false, $include_none = false ) {
        $db = self::$db->get( $this->tableName, '*' );
        if ( !$db->count() ) {
            Debug::warn( 'Could not find any groups' );
            return false;
        }
        
        $groups = $db->results();
        $out = [];
        if ( $include_all ) {
            $out[ 'All Groups' ] = 0;
        }
        if ( $include_none ) {
            $out[ 'No Group' ] = 0;
        }
        foreach ( $groups as &$group ) {
            $out[ $group->name ] = $group->ID;
        }
        return $out;
    }

    public function listMembers( $id ) {
        if ( !Check::id( $id ) ) {
            return false;
        }
        $group = $this->findById( $id );
        if ( $group === false ) {
            return false;
        }
        $members = self::$db->get( 'users', [ 'userGroup', '=', $id ] );
        if ( !$members->count() ) {
            Debug::info( "list members: Could not find anyone in group: $id" );
            return false;
        }
        $out = $members->results();
        return $out;
    }

    /**
     * Retrieves a count of the members in a specific group.
     *
     * @param  integer $id - The group ID to count the members of
     * @return boolean|integer
     */
    public function countMembers( $id ) {
        if ( !Check::id( $id ) ) {
            return false;
        }
        $userData = self::$db->get( 'users', [ 'userGroup', '=', $id ] );
        if ( !$userData->count() ) {
            Debug::info( "count members: Could not find anyone in group: $id" );
            return 0;
        }
        return $userData->count();
    }
}
