<?php

namespace Trainingssystem\Module\App\Query;

use stdClass;
class SaveSleepEntryQuery
{

    public function execute($entries)
    {
        $insertedEntryArr = [];

        $user = wp_get_current_user();
    foreach($entries as $entry){

        $time = current_time('mysql');

        $id = $this::insertFormDataForUser($entry->field_id, $user->ID, $entry->data, 0, $time );

       $resultData = new stdClass();
       $resultData->userId = $user->ID;
       $resultData->id = $id;
       $resultData->time = $time;
       $resultData->data = $entry->data;

        array_push($insertedEntryArr, $resultData);

    }
    return json_encode($insertedEntryArr);
    }

    public function updateEntry($entry)
    {
    foreach($entry as $entryData){
        if($entryData != null){
           $this::updateFormDataForUser($entryData->id, $entryData->data);
        }
    }
    return json_encode($entry);
    }

    public function updateFormDataForUser($id, $data) {
        global $wpdb;
        $table_name_data = $wpdb->prefix . 'md_trainingsmgr_ts_forms_data';
        $wpdb->update( $table_name_data, array( 'data' => $data ), array('ID' => $id) );
        return 1;
    }

    public function deleteEntry($entry)
    {
    foreach($entry as $data){
    $this::deleteFormDataForUser($data->id);
    }
    return json_encode($entry);
    }

    public function deleteFormDataForUser($id) {
        global $wpdb;
        $table_name_data = $wpdb->prefix . 'md_trainingsmgr_ts_forms_data';

        $wpdb->delete( $table_name_data, array('ID' => $id) );

        return $sql !== false;
    }

    /**
     * Inserts a new formdata dataset
     * 
     * @param int field ID
     * @param int user ID
     * @param String data
     * @param int formgroup
     * 
     * @return boolean success
     */
    public function insertFormDataForUser($fieldid, $userid, $data, $formgroup, $time = null) {
        global $wpdb;
        $table_name_data = $wpdb->prefix . 'md_trainingsmgr_ts_forms_data';

       
        $sql = $wpdb->insert($table_name_data,
                                array(
                                    "field_ID" => $fieldid,
                                    "user_ID" => $userid,
                                    "data" => $data,
                                    "form_group" => $formgroup,
                                    "save_date" => $time,
                                ),
                                array("%d", "%d", "%s", "%d", "%s")
                            );

        return $wpdb->insert_id;
    }

}