<?php

namespace Trainingssystem\Module\App\RestHandler;

use stdClass;
use Trainingssystem\Module\App\Query\GetAllTrainingsForUserIdQuery;

class TrainingDataRestHandler
{
    private GetAllTrainingsForUserIdQuery $getAllTrainingsForUserIdQuery;

    public function __construct(GetAllTrainingsForUserIdQuery $getAllTrainingsForUserIdQuery)
    {
        $this->getAllTrainingsForUserIdQuery = $getAllTrainingsForUserIdQuery;
    }

    /**
     * @param \WP_REST_Request $request
     * @return \WP_Error|\WP_HTTP_Response|\WP_REST_Response
     */
    public function handle(\WP_REST_Request $request)
    {
        $user = wp_get_current_user();
        $trainingsForUser = $this->getAllTrainingsForUserIdQuery->execute($user->ID);
        return rest_ensure_response($trainingsForUser);
    }

    public function getAppSleepQestions(\WP_REST_Request $request)
    {
        $bodyData = json_decode($request->get_body());
        $lessons = $bodyData->lessons;
        $trainingId = $bodyData->trainingId;
        $user = wp_get_current_user();
        $regex = "/\[[\wöäüßÖÄÜ0-9-_?! :.,;\/{}()=\"'…\n\r]+\]?/";
        $type = 'tsforms';
        $code = "";
        $resultSites = [];

        foreach ($lessons as $lesson) {
            $resultSite = new stdClass();
            
            $seitenids = $this::getSeitenIdsByLektion($trainingId, $lesson->id); //todo
            $seitenPost = get_posts(
                array(
                    "post_type" => "seiten",
                    "numberposts" => -1,
                    "orderby" => "ID",
                    "order" => "ASC",
                    "include" => $seitenids,
                )
            );

            foreach ($seitenPost as $seitenpost) {
                $formfieldSorted = [];
                $code .= $seitenpost->post_content;
                $founds = $this::getLektionForms($regex, $code, $type);
                $founds = explode(';', ($founds));
                $code = "";
                $tempFormfieldArr = [];
                $formdata = [];
                $ids = array_column($this->getAllTrainingsForUserIdQuery->getFormField(implode(",", $founds)), 'ID');
                $formdata = $this->getAllTrainingsForUserIdQuery->getFormData(implode(",", $ids));
                $tempFormfields = $this->getAllTrainingsForUserIdQuery->getFormField(implode(",", $founds));
                $formfieldSorted=array_fill(0,count($tempFormfields),"null");
                foreach ($tempFormfields as $tempFormfield1) {
                        if(in_array($tempFormfield1->form_ID, $founds)) {
                        $key = array_search($tempFormfield1->form_ID, $founds);
                        $formfieldSorted[$key] = $tempFormfield1;
                        }
                       $key = "";
                }


                foreach ($formfieldSorted as $key => $tempFormfield) {
            $tempForm = new stdClass();

                    $tempForm->formfield = $tempFormfield;

                    foreach ($formdata as $fd) {
                        if ($tempFormfield->ID == $fd->field_ID) {
                            $temp = [];
                            array_push($temp, $fd);
                            $tempForm->formdata = $temp;
                            break;
                        } else {
                            $tempForm->formdata = null;
                        }
                    }
                    $tempFormfieldArr[$key] = $tempForm;

                }
                $seitenpost->forms = $tempFormfieldArr;
                $tempFormfieldArr = "";
                $tempForm = "";
                $tempFormfields = "";
                $tempFormfield = "";
                $founds = "";
                $formdata = "";

                unset($seitenpost->{"post_content"});
                unset($seitenpost->{"comment_count"});
                unset($seitenpost->{"comment_status"});
                unset($seitenpost->{"filter"});
                unset($seitenpost->{"guid"});
                unset($seitenpost->{"menu_order"});
                unset($seitenpost->{"ping_status"});
                unset($seitenpost->{"pinged"});
                unset($seitenpost->{"post_author"});
                unset($seitenpost->{"post_content_filtered"});
                unset($seitenpost->{"post_date"});
                unset($seitenpost->{"post_date_gmt"});
                unset($seitenpost->{"post_excerpt"});
                unset($seitenpost->{"post_mime_type"});
                unset($seitenpost->{"post_modified"});
                unset($seitenpost->{"post_modified_gmt"});
                unset($seitenpost->{"post_name"});
                unset($seitenpost->{"post_parent"});
                unset($seitenpost->{"post_password"});
                unset($seitenpost->{"post_status"});
                unset($seitenpost->{"post_title"});
                unset($seitenpost->{"post_type"});
                unset($seitenpost->{"to_ping"});
            }

            $resultSite->name = $lesson->name;
            $resultSite->sites = $seitenPost;
            array_push($resultSites, $resultSite);
        }

        return rest_ensure_response($resultSites);
    }

    public function getAppSleepQestionsMulti(\WP_REST_Request $request)
    {
        $bodyData = json_decode($request->get_body());
        $lessons = $bodyData->lessons;
        $trainingId = $bodyData->trainingId;
        $user = wp_get_current_user();
        $regex = "/\[[\wöäüßÖÄÜ0-9-_?! :.,;\/{}()=\"'…\n\r]+\]?/";
        $type = 'tsforms';
        $code = "";
        $resultSites = [];

        foreach ($lessons as $lesson) {
            $resultSite = new stdClass();
            
            $seitenids = $this::getSeitenIdsByLektion($trainingId, $lesson->id); //todo
            $seitenPost = get_posts(
                array(
                    "post_type" => "seiten",
                    "numberposts" => -1,
                    "orderby" => "ID",
                    "order" => "ASC",
                    "include" => $seitenids,
                )
            );

            foreach ($seitenPost as $seitenpost) {
                $formfieldSorted = [];
                $code .= $seitenpost->post_content;
                $founds = $this::getLektionForms($regex, $code, $type);
                $founds = explode(';', ($founds));
                $code = "";
                $tempFormfieldArr = [];
                $formdata = [];
                $ids = array_column($this->getAllTrainingsForUserIdQuery->getFormField(implode(",", $founds)), 'ID');
                $formdata = $this->getAllTrainingsForUserIdQuery->getFormData(implode(",", $ids));
                $tempFormfields = $this->getAllTrainingsForUserIdQuery->getFormField(implode(",", $founds));
                $formfieldSorted=array_fill(0,count($tempFormfields),"null");
                foreach ($tempFormfields as $tempFormfield1) {
                        if(in_array($tempFormfield1->form_ID, $founds)) {
                        $key = array_search($tempFormfield1->form_ID, $founds);
                        $formfieldSorted[$key] = $tempFormfield1;
                        }
                       $key = "";
                }


                foreach ($formfieldSorted as $key => $tempFormfield) {
                    $tempForm = new stdClass();
                    $temp = [];
                    $tempForm->formfield = $tempFormfield;

                    foreach ($formdata as $fd) {
                        if ($tempFormfield->ID == $fd->field_ID) {
                            
                            array_push($temp, $fd);
                            $tempForm->formdata = $temp;
                            //break;
                        } else {
                            //$tempForm->formdata = [];
                        }
                    }
                    $tempFormfieldArr[$key] = $tempForm;

                }
                $seitenpost->forms = $tempFormfieldArr;
                $tempFormfieldArr = "";
                $tempForm = "";
                $tempFormfields = "";
                $tempFormfield = "";
                $founds = "";
                $formdata = "";

                unset($seitenpost->{"post_content"});
                unset($seitenpost->{"comment_count"});
                unset($seitenpost->{"comment_status"});
                unset($seitenpost->{"filter"});
                unset($seitenpost->{"guid"});
                unset($seitenpost->{"menu_order"});
                unset($seitenpost->{"ping_status"});
                unset($seitenpost->{"pinged"});
                unset($seitenpost->{"post_author"});
                unset($seitenpost->{"post_content_filtered"});
                unset($seitenpost->{"post_date"});
                unset($seitenpost->{"post_date_gmt"});
                unset($seitenpost->{"post_excerpt"});
                unset($seitenpost->{"post_mime_type"});
                unset($seitenpost->{"post_modified"});
                unset($seitenpost->{"post_modified_gmt"});
                unset($seitenpost->{"post_name"});
                unset($seitenpost->{"post_parent"});
                unset($seitenpost->{"post_password"});
                unset($seitenpost->{"post_status"});
                unset($seitenpost->{"post_title"});
                unset($seitenpost->{"post_type"});
                unset($seitenpost->{"to_ping"});
            }

            $resultSite->name = $lesson->name;
            $resultSite->sites = $seitenPost;
            array_push($resultSites, $resultSite);
        }

        return rest_ensure_response($resultSites);
    }

    /**
     * Return the page IDs of a lektion
     * 
     * @param Integer Training-ID
     * @param Integer Lektion-ID
     * 
     * @return Array Integers
     */
    public static function getSeitenIdsByLektion($trainingid, $lektionid)
    {
        global $wpdb;
        $tablename = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_TRAINING_SEITEN;
        $sql = $wpdb->prepare("SELECT seiten_id FROM $tablename where training_id = %d AND lektion_id = %d ORDER BY seiten_index", $trainingid, $lektionid);
        $result = $wpdb->get_results($sql);
        $ret = [];
        foreach ($result as $r) {
            $ret[] = $r->seiten_id;
        }
        $str = implode(",", $ret);
        return $str;
    }

    //Filters Shortcodes and returns forms ids 
    public static function getLektionForms($regex, $code, $type)
    {
        preg_match_all($regex, $code, $matches);
        $all_shortcodes_list = array();
        $s_index = 0;

        foreach ($matches[0] as $match) {
            if (substr($match[0], 0, 1) === '[') { // no closing tags here
                $all_shortcodes_list[$s_index]['original_shortcode'] = $match;
                if (strpos($match, " ") !== false) {
                    $all_shortcodes_list[$s_index]['shortcode_name'] = substr($match, 1, strpos($match, " "));
                    $all_shortcodes_list[$s_index] = array_merge($all_shortcodes_list[$s_index], array_slice(shortcode_parse_atts(substr($match, 1, strlen($match) - 2)), 1));
                } else {
                    $all_shortcodes_list[$s_index]['shortcode_name'] = substr($match, 1, strlen($match) - 2);
                }
                $s_index++;
            }
        }
        $found_ids = array();
        foreach ($all_shortcodes_list as $shortcode) {
            switch (trim($shortcode['shortcode_name'])) {
                case "ts_forms":
                    if (isset($shortcode['id']) && $type == "tsforms" && !isset($found_ids[$shortcode['id']])) {
                        $found_ids[$shortcode['id']] = $shortcode['id'];
                    }
                    break;
            }
        }
        return implode(';', array_values($found_ids));
    }
}