<?php

/**
 * Register all actions and filters for the plugin
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Trainingssystem_Plugin
 * @subpackage Trainingssystem_Plugin/includes
 */

/**
 * Register all actions and filters for the plugin.
 *
 * Maintain a list of all hooks that are registered throughout
 * the plugin, and register them with the WordPress API. Call the
 * run function to execute the list of actions and filters.
 *
 * @package    Trainingssystem_Plugin
 * @subpackage Trainingssystem_Plugin/includes
 * @author     Markus Domin, Helge Nissen <->
 */
class Trainingssystem_Plugin_Database_Companygroup_Daoimple implements Trainingssystem_Plugin_Database_Companygroup_Dao{

    public static $dbprefix = TRAININGSSYSTEM_PLUGIN_DB_GRUPPE;

    public function __construct(){
        $this->iniDB();

    }

    public function iniDB(){




		//         $user_grouper_plugin_gruppe					
		// id	int(11)	NO	PRI		auto_increment
		// name	text	NO			
		// firmaid	int(11)	NO			
		// createrid	int(11)	NO			
		// createrdate	datetime	NO			


        global $wpdb;
        $table_name = $wpdb->prefix . self::$dbprefix;
        $charset_collate = $wpdb->get_charset_collate();
        $tableversionsstr =[
            "CREATE TABLE IF NOT EXISTS $table_name(
                     id INT NOT NULL AUTO_INCREMENT ,
                     name TEXT NOT NULL ,
                     firmaid INT NOT NULL ,
                     createrid INT NOT NULL ,
                     createrdate DATETIME NOT NULL,
                     PRIMARY KEY (id)
                     )$charset_collate;"
        ];
        Trainingssystem_Plugin_Database_Coach_impl::updateDBTable(self::$dbprefix,$table_name, $tableversionsstr);

    }
	
    /**
     * database updating beim plugin update
     *
     * @since    1.0.0
     */
	public function updating(){

	}

    // Gruppe erstellen
    public function insertCompanygroup($name, $company_id) {    
        global $wpdb;
        $table_name = $wpdb->prefix . self::$dbprefix;		
        
        $kAdminId = 0;
        $company = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($company_id);
        if($company->getKAdmin() != null) {
            $kAdminId = $company->getKAdmin()->getId();
        }

		$wpdb->insert($table_name,
            array('name' => $name, 
            'firmaid' => $company_id,
            'createrdate'=> current_time('mysql'),
            'createrid' => $kAdminId) 
			);
    }
	
	public function insertCompanygroupWithMembers($groupName, $companyId, $members) {
		global $wpdb;
        $table_name = $wpdb->prefix . self::$dbprefix;	
        
        $kAdminId = 0;
        $company = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($companyId);
        if($company->getKAdmin() != null) {
            $kAdminId = $company->getKAdmin()->getId();
        }

		$wpdb->insert($table_name,
            array('name' => $groupName, 
            'firmaid' => $companyId,
            'createrdate'=> current_time('mysql'),
            'createrid' => $kAdminId)
			);
		$groupId = $wpdb->insert_id;
		foreach ($members as $userId) {
			Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->addUserToGroup($userId, $groupId);
		}		
	}

	// Gruppe aktualisieren
	public function updateCompanygroup($group_id, $name) {
        global $wpdb;
        $table_name = $wpdb->prefix . self::$dbprefix;			
		$wpdb->update($table_name, array('name' => $name), array('id' => $group_id));
    }

	// Gruppe löschen
    public function deleteCompanygroup($id) {
        
		// Alle Mitglieder aus der Gruppe löschen
		Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->emptyGroup($id);
		
		// Gruppe selbst löschen
		global $wpdb;
        $table_name = $wpdb->prefix.$this::$dbprefix;
        $res = $wpdb->delete($table_name, array('id' => $id));
    }
	
	public function deleteAllGroups($companyId) {
		global $wpdb;
        $table = $wpdb->prefix.$this::$dbprefix;
        
		$query = $wpdb->prepare("SELECT id FROM $table WHERE firmaid = %s", $companyId);
		$groupIds = $wpdb->get_col($query);
		foreach ($groupIds as $id) $this->deleteCompanygroup($id);
	}
	
	public function getCompanygroupById($group_id, $includecompany = true, $includeallinfo = true){	
		global $wpdb;
        $table = $wpdb->prefix.$this::$dbprefix;
        
		$sql = $wpdb->prepare("SELECT * FROM $table where id = %d", $group_id);
        $row = $wpdb->get_row($sql);
        
        if($wpdb->num_rows != 0) {
            $company = $includecompany ? Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($row->firmaid) : null;
            $members = $includeallinfo ? $this->getMembers($group_id, $includecompany) : array();

            return new Trainingssystem_Plugin_Database_Companygroup($row->id, $row->name, $company, $members);
        }
        return null;
    }
    
    public function getCompanygroupByName($group_name, $company_id){		
		global $wpdb;
        $table = $wpdb->prefix.$this::$dbprefix;
        
		$sql = $wpdb->prepare("SELECT * FROM $table where name = %s and firmaid = %d", $group_name, $company_id);
        $row = $wpdb->get_row($sql);
        if($row == null) return null;
    
        $company = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($row->firmaid);
        if($company == null) return null;
		
		$members = $this->getMembers($row->id);
        
		return new Trainingssystem_Plugin_Database_Companygroup($row->id, $row->name, $company, $members);

	}
	
	
	public function getMembers($groupId){
		$userIDs = Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->getUserIdsByGroupId($groupId);
		return Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getNutzers($userIDs);			
	}

    function deleteUserInput($user_id){
        global $wpdb;
        $datatable=$wpdb->prefix.$this::$dbprefix;
        $wpdb->update( $datatable, array( 'createrid' => 0 ), array('createrid' => $user_id) );
    }

    public function getAllGroups() {
		global $wpdb;
        $table = $wpdb->prefix.$this::$dbprefix;
        
		$query = $wpdb->prepare("SELECT * FROM $table ORDER BY name");
		return $wpdb->get_results($query);
    }

    /**
     * Returns all Group-Objects for a specific company
     * 
     * @param Int Company-ID
     * 
     * @return Array CompanyGroup Objects
     */
    public function getAllGroupObjectsByCompanyId($company_id) {

        $groupids = $this->getAllGroupsByCompanyId($company_id);

        $ret = array();

        foreach ($groupids as $gid) {
            $ret[] = $this->getCompanygroupById($gid->id);
        }

        return $ret;
    } 

    public function getAllGroupsByCompanyId($companyId) {
        global $wpdb;
        $table = $wpdb->prefix.$this::$dbprefix;
        
		$query = $wpdb->prepare("SELECT * FROM $table WHERE firmaid = %s", $companyId);
		return $wpdb->get_results($query);
    }

}
