<?php

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

    /**
     * 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,
                `assign_datetime` TIMESTAMP NULL DEFAULT NULL,
                `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 `assign_datetime`;",
        ];

		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_Date or null on failure
     */
    public function getTrainingDate($trainingdateid) {
        global $wpdb;
        $table_name = $wpdb->prefix . self::$dbprefix;

        $row = $wpdb->get_row($wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d LIMIT 1", $trainingdateid), OBJECT);
        
        if($row != null) {
            return new Trainingssystem_Plugin_Database_Training_Date($row->id, $row->training_id, $row->training_mode, $row->ecoaching_enable, $row->lektion_settings, $row->user_id, $row->assign_datetime, $row->redirect, $row->created_by, $row->created_at);
        }
        return null;
    }

    /**
     * Returns all DateTrainings
     * 
     * @param String orderBy (currently assigndate_asc and assigndate_desc supported)
     * 
     * @return Array of Trainingssystem_Plugin_Database_Training_Date Objects or empty array
     */
    public function getAllTrainingDate($orderby = null) {
        global $wpdb;

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

        $sql = "SELECT * FROM $table_name ";
        if($orderby == "assigndate_asc") {
            $sql .= "ORDER BY assign_datetime ASC";
        } elseif($orderby == "assigndate_desc") {
            $sql .= "ORDER BY assign_datetime DESC";
        }

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

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

    /**
     * Returns all DateTrainings that are due to be inserted
     * 
     * 
     * @return Array of Trainingssystem_Plugin_Database_Training_Date Objects or empty array
     */
    public function getTrainingDateDue() {
        global $wpdb;

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

        $data = $wpdb->get_results("SELECT * FROM $table_name WHERE assign_datetime <= NOW()", OBJECT);
        $result = [];

        foreach ($data as $row){
            $result[] = new Trainingssystem_Plugin_Database_Training_Date($row->id, $row->training_id, $row->training_mode, $row->ecoaching_enable, $row->lektion_settings, $row->user_id, $row->assign_datetime,  $row->redirect, $row->created_by, $row->created_at);
        }

        return $result;
    }

    /**
     * Returns all DateTrainings for a given user
     * 
     * @param Int userId
     * 
     * @return Array of Trainingssystem_Plugin_Database_Training_Date Objects or empty array
     */
    public function getTrainingDateByUser($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_Date($row->id, $row->training_id, $row->training_mode, $row->ecoaching_enable, $row->lektion_settings, $row->user_id, $row->assign_datetime,  $row->redirect, $row->created_by, $row->created_at);
        }

        return $result;
    }

    /**
     * Returns all DateTrainings for multiple users
     * Structure:
     * User-ID as Array Key
     * |--> Trainingssystem_Plugin_Database_Training_Date Objects for the given user
     * 
     * @param Array userIds
     * 
     * @return 2D-Array of Trainingssystem_Plugin_Database_Training_Date Objects or empty array
     */
    public function getTrainingDateByUsers($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_Date($row->id, $row->training_id, $row->training_mode, $row->ecoaching_enable, $row->lektion_settings, $row->user_id, $row->assign_datetime,  $row->redirect, $row->created_by, $row->created_at);
        }

        return $result;
    }

    /**
     * Inserts a new date training
     * 
     * @return boolean success
     */
    public function insertTrainingDate($trainingId, $trainingMode, $ecoachingEnable, $lektionSettings, $userId, $assignDatetime, $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,
                                    "assign_datetime" => $assignDatetime,
                                    "redirect" => $redirect,
                                    "created_by" => $createdBy,
                                    "created_at" => $createdAt
                                ),
                                array("%d", "%d", "%d", "%s", "%d", "%s", "%d", "%d", "%s")
                            );
        return $sql !== false;
    }

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

        $trainingids = [];

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

        if($this->deleteAllTrainingDatesForUser($userid)) {
            
            foreach($datetrainings as $date_t) {
                if(!$this->insertTrainingDate($date_t['trainingId'], $date_t['trainingMode'], $date_t['ecoachingEnable'], ($date_t['trainingMode'] == 2) ? is_array($date_t['lektionSettings']) ? json_encode($date_t['lektionSettings']) : $date_t['lektionSettings'] : 0, $userid, $date_t['assignDatetime'], $date_t['redirect'], get_current_user_id())) {
                    return false;
                }
            }
            return true;

        } else {
            return false;
        }
    }

    public function updateDatetimeForTrainingDate($trainingdateid, $newdate) {
        global $wpdb;

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

        $sql = $wpdb->update(
            $table_name,
            array(
                "assign_datetime" => $newdate,
            ),
            array(
                "id" => $trainingdateid,
            ),
            "%s",
            "%d",
        );

        return $sql !== false;
    }
    
    /**
     * Deletes a date training by its id
     * 
     * @return boolean success
     */
    public function deleteTrainingDate($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 Date for multiple users
     * 
     * @param Int Training-ID
     * @param Array User-IDs
     * 
     * @return boolean success
     */
    public function deleteTrainingDateForUsers($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 Dates for a single user
     * 
     * @param Array Training-IDs
     * @param Int User-ID
     * 
     * @return boolean success
     */
    public function deleteTrainingDatesForUser($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 Dates for a single user
     * 
     * @param Int User-ID
     * 
     * @return boolean success
     */
    public function deleteAllTrainingDatesForUser($userid) {
        global $wpdb;

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

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

    }

    /**
     * Deletes multiple Training Dates by their id
     * 
     * @param Array ids
     * 
     * @return boolean success
     */
    public function deleteTrainingsDate($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}')");

    }
}
