<?php

/**
 * Functions for Trainings Dep Database Table
 *
 * @package    Trainingssystem_Plugin
 * @subpackage Trainingssystem_Plugin/includes
 *
 * @author     Max Sternitzke <max.sternitzke@th-luebeck.de>
 */
class Trainingssystem_Plugin_Database_Training_Dep_Daoimple implements Trainingssystem_Plugin_Database_Training_Dep_Dao
{
    public static $dbprefix = TRAININGSSYSTEM_PLUGIN_DB_TRAINING_DEP;

    /**
     * Initialize the collections used to maintain the actions and filters.
     *
     * @since    1.0.0
     */
    public function __construct()
    {
        $this->iniDB();
    }

    public function iniDB()
    {

        global $wpdb;
        $table_name = $wpdb->prefix . self::$dbprefix;
        $charset_collate = $wpdb->get_charset_collate();
        $tableversionsstr =[
			"CREATE TABLE IF NOT EXISTS $table_name(
                `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
                `training_id` BIGINT(20) NOT NULL,
                `training_mode` INT(4) NOT NULL,
                `ecoaching_enable` TINYINT(1) NOT NULL DEFAULT 0,
                `lektion_id` BIGINT(20) NOT NULL DEFAULT 0,
                `user_id` BIGINT(20) NOT NULL,
                `time_add` INT(4) NOT NULL,
                `time_multiplier` VARCHAR(16) NOT NULL,
                `dependent_trainings` TEXT(2048) NOT NULL,
                `dependent_condition` ENUM('or', 'and') NOT NULL DEFAULT 'or',
                `created_by` BIGINT(20) NOT NULL,
                `created_at` TIMESTAMP NOT NULL DEFAULT NOW(),
                PRIMARY KEY (`id`)
        )$charset_collate;",
        "ALTER TABLE $table_name CHANGE `lektion_id` `lektion_settings` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL;",
        "ALTER TABLE $table_name ADD `redirect` BOOLEAN NOT NULL DEFAULT FALSE AFTER `dependent_condition`;",
        ];

		Trainingssystem_Plugin_Database_Coach_impl::updateDBTable(self::$dbprefix,$table_name, $tableversionsstr);
    }

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

	}

    /**
     * Returns a single dataset
     * 
     * @param int ID
     * 
     * @return Trainingssystem_Plugin_Database_Training_Dep or null on failure
     */
    public function getTrainingDep($trainingdepid) {
        global $wpdb;
        $table_name = $wpdb->prefix . self::$dbprefix;

        $row = $wpdb->get_row($wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d LIMIT 1", $trainingdepid), OBJECT);
        
        if($row != null) {
            return new Trainingssystem_Plugin_Database_Training_Dep($row->id, $row->training_id, $row->training_mode, $row->ecoaching_enable, $row->lektion_settings, $row->user_id, $row->time_add, $row->time_multiplier, $row->dependent_trainings, $row->dependent_condition, $row->redirect, $row->created_by, $row->created_at);
        }
        return null;
    }   
    
    /**
    * Returns all DepTrainings
    * 
    * @param String orderBy (currently id_asc and id_desc supported)
    * 
    * @return Array of Trainingssystem_Plugin_Database_Training_Dep Objects or empty array
    */
   public function getAllTrainingDep($orderby = null) {
       global $wpdb;

       $table_name = $wpdb->prefix . self::$dbprefix;

       $sql = "SELECT * FROM $table_name ";
       if($orderby == "id_asc") {
           $sql .= "ORDER BY id ASC";
       } elseif($orderby == "id_desc") {
           $sql .= "ORDER BY id DESC";
       }

       $data = $wpdb->get_results($sql, OBJECT);
       $result = [];

       foreach ($data as $row){
           $result[] = new Trainingssystem_Plugin_Database_Training_Dep($row->id, $row->training_id, $row->training_mode, $row->ecoaching_enable, $row->lektion_settings, $row->user_id, $row->time_add, $row->time_multiplier, $row->dependent_trainings, $row->dependent_condition, $row->redirect, $row->created_by, $row->created_at);
       }
       
       return $result;
   }


    /**
     * Returns all DepTrainings for a given user
     * 
     * @param Int userId
     * 
     * @return Array of Trainingssystem_Plugin_Database_Training_Dep Objects or empty array
     */
    public function getTrainingDepByUser($userId) {
        global $wpdb;

        $table_name = $wpdb->prefix . self::$dbprefix;

        $data = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d", $userId ), OBJECT);
        $result = [];

        foreach ($data as $row){
            $result[] = new Trainingssystem_Plugin_Database_Training_Dep($row->id, $row->training_id, $row->training_mode, $row->ecoaching_enable, $row->lektion_settings, $row->user_id, $row->time_add, $row->time_multiplier, $row->dependent_trainings, $row->dependent_condition, $row->redirect, $row->created_by, $row->created_at);
        }

        return $result;
    }

    /**
     * Returns all DepTrainings for multiple users
     * Structure:
     * User-ID as Array Key
     * |--> Trainingssystem_Plugin_Database_Training_Dep Objects for the given user
     * 
     * @param Array userIds
     * 
     * @return 2D-Array of Trainingssystem_Plugin_Database_Training_Dep Objects or empty array
     */
    public function getTrainingDepByUsers($userIds) {

        if(empty($userIds)) {
            return array();
        }

        global $wpdb;

        $table_name = $wpdb->prefix . self::$dbprefix;

        $data = $wpdb->get_results("SELECT * FROM $table_name WHERE user_id IN (" . implode(', ', $userIds) . ")");
        $result = [];

        foreach ($data as $row){
            if(!isset($ret[$row->user_id])) {
                $ret[$row->user_id] = array();
            }
            $result[$row->user_id][] = new Trainingssystem_Plugin_Database_Training_Dep($row->id, $row->training_id, $row->training_mode, $row->ecoaching_enable, $row->lektion_settings, $row->user_id, $row->time_add, $row->time_multiplier, $row->dependent_trainings, $row->dependent_condition, $row->redirect, $row->created_by, $row->created_at);
        }

        return $result;
    }

    /**
     * Inserts a new dep training
     * 
     * @return boolean success
     */
    public function insertTrainingDep($trainingId, $trainingMode, $ecoachingEnable, $lektionSettings, $userId, $timeAdd, $timeMultiplier, $dependentTrainings, $dependentCondition, $redirect, $createdBy, $createdAt = null) {
        global $wpdb;

        $table_name_data = $wpdb->prefix . self::$dbprefix;

        if($createdAt == null) {
            $createdAt = current_time('mysql');
        }
        $sql = $wpdb->insert($table_name_data,
                                array(
                                    "training_id" => $trainingId,
                                    "training_mode" => $trainingMode,
                                    "ecoaching_enable" => $ecoachingEnable,
                                    "lektion_settings" => $lektionSettings,
                                    "user_id" => $userId,
                                    "time_add" => $timeAdd,
                                    "time_multiplier" => $timeMultiplier,
                                    "dependent_trainings" => $dependentTrainings,
                                    "dependent_condition"  => $dependentCondition,
                                    "redirect" => $redirect,
                                    "created_by" => $createdBy,
                                    "created_at" => $createdAt
                                ),
                                array("%d", "%d", "%d", "%s", "%d", "%d", "%s", "%s", "%s", "%d", "%d", "%s")
                            );
        return $sql !== false;
    }

    /**
     * Updates all of a users dep trainings by removing all and then adding the (maybe) edited ones
     * 
     * @param Int User-ID
     * @param Array Dep Trainings
     * 
     * @return boolean success
     */
    public function updateTrainingsDepByUserId($userid, $deptrainings) {

        $trainingids = [];

        foreach($deptrainings as $t) {
            $trainingids[] = $t['trainingId'];
        }

        if($this->deleteAllTrainingDepsForUser($userid)) {
            
            foreach($deptrainings as $date_d) {

                if(!$this->insertTrainingDep($date_d['trainingId'], $date_d['trainingMode'], $date_d['ecoachingEnable'], ($date_d['trainingMode'] == 2) ? is_array($date_d['lektionSettings']) ? json_encode($date_d['lektionSettings']) : $date_d['lektionSettings'] : 0, $userid, $date_d['timeAdd'], $date_d['timeMultiplier'], $date_d['dependentTrainings'], $date_d['dependentCondition'], $date_d['redirect'], get_current_user_id())) {
                    return false;
                }
            }
            return true;

        } else {
            return false;
        }
    }
    
    /**
     * Deletes a training dep by its id
     * 
     * @return boolean success
     */
    public function deleteTrainingDep($id) {
        global $wpdb;

        $table_name = $wpdb->prefix . self::$dbprefix;

        $sql = $wpdb->delete($table_name,
            array(
                'id' => $id
            ),
            array(
                '%d'
            )
        );

        return $sql !== false;
    }

    /**
     * Deletes a single Training Dep for multiple users
     * 
     * @param Int Training-ID
     * @param Array User-IDs
     * 
     * @return boolean success
     */
    public function deleteTrainingDepForUsers($trainingid, $users) {
        global $wpdb;

        $table_name = $wpdb->prefix . self::$dbprefix;

        $users_imploded = implode("','", $users);

        return false !== $wpdb->query("DELETE FROM {$table_name} WHERE training_id = {$trainingid} AND user_id IN ('{$users_imploded}')");

    }

    /**
     * Deletes multiple Training Deps for a single user
     * 
     * @param Array Training-IDs
     * @param Int User-ID
     * 
     * @return boolean success
     */
    public function deleteTrainingDepsForUser($trainingids, $userid) {
        global $wpdb;

        $table_name = $wpdb->prefix . self::$dbprefix;

        $trainings_imploded = implode("','", $trainingids);

        return false !== $wpdb->query("DELETE FROM {$table_name} WHERE user_id = {$userid} AND training_id IN ('{$trainings_imploded}')");

    }

    /**
     * Deletes all Training Deps for a user
     * 
     * @param Int User-ID
     * 
     * @return boolean success
     */
    public function deleteAllTrainingDepsForUser($userid) {
        global $wpdb;

        $table_name = $wpdb->prefix . self::$dbprefix;

        return false !== $wpdb->query("DELETE FROM {$table_name} WHERE user_id = {$userid}");

    }

    /**
     * Deletes multiple Training Deps by their ids
     * 
     * @param Array ids
     * 
     * @return boolean success
     */
    public function deleteTrainingsDep($ids) {
        global $wpdb;

        $table_name = $wpdb->prefix . self::$dbprefix;

        $ids_imploded = implode("','", $ids);

        return false !== $wpdb->query("DELETE FROM {$table_name} WHERE id IN ('{$ids_imploded}')");

    }
}
