<?php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Filesystem\File;
use Cake\I18n\Time;
use Cake\Utility\Xml;

//define('SCHULPORTAL_BASE0_URL', "https://portal.schulen.bayern.de");
//define('SCHULPORTAL_BASE_URL', SCHULPORTAL_BASE0_URL . "/uniquesig2d1dfad4a11c25e42c462e53b4721e48/uniquesig0");

class MonitoringsController extends AppController
{

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Tools');
    }

    private function query_to_var($string)
    {
        $arr = array();
        $pairs = explode('&', $string);
        //debug($pairs);
        foreach ($pairs as $pair) {
            $parts = explode('=', $pair);
            $arr[urldecode($parts[0])] = urldecode($parts[1]);
        }
        return $arr;
    }

    private function get_string_between($string, $start, $end)
    {
        $string = " " . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) {
            return "";
        }

        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        $sub = substr($string, $ini, $len);
        $elem = explode(' ', $sub)[0];
        return str_replace('"', '', $elem);
    }

    private function login_school($ch)
    {

        //$login_data = $this->request->session()->read('data');

        $login_data = [
            'portal_username' => 'asd.trinkl',
            'portal_password' => 'HiegTzs!182',
        ];
        curl_setopt($ch, CURLOPT_URL, SCHULPORTAL_BASE_URL);
        $text = curl_exec($ch);
        

        $post = [
            'user_name' => $login_data['portal_username'],
            'password' => $login_data['portal_password'],
            'repository' => 'schulen.bayern.de',
            'site_name' => 'schulportal',
            'secure' => '1',
            'resource_id' => '2',
            'login_type' => '2',
        ];
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

        // Anmeldeformular fuer das Schulportal abschicken - Step 2

        curl_setopt($ch, CURLOPT_URL, SCHULPORTAL_BASE_URL . '/InternalSite/Validate.asp');
        $text = curl_exec($ch);
    }

    public function screen()
    {
        $this->set('path', $this->Tools->screen());
    }

    public function trans()
    {
        if ($this->request->is('post')) {
            //debug($this->request);
            $string = $this->request['data']['string'];
            $arr = $this->query_to_var($string);
            $this->set('arr', $arr);
        }
    }

    public function showxml()
    {
        if ($this->request->is('post')) {
            //debug($this->request);
            $string = $this->request['data']['string'];
            echo($string);
            //$arr = $p = xml_parser_create();
            //xml_parse_into_struct($p, $string, $vals, $index);
            //xml_parser_free($p);
            $vals = Xml::toArray(Xml::build($string));
            //debug($vals);
            //debug($index);
            $this->set('arr', $vals);
        }
    }

    public function login()
    {
        if ($this->request->is('post')) {
            $post = $this->request['data'];
            $this->request->session()->write('data', $this->request['data']);
            debug($post);
            return $this->redirect(['action' => 'examine']);
        }
    }

    public function viva()
    {
        $schools = $this->Monitorings->find('all', array('conditions' => array('action' => 'lehrkap')));
        $schools->select(['school'])
            ->distinct(['school']);

        foreach ($schools as $school) {
            $snr = $school->school;
            $vdata = $this->Monitorings->find('all', array('conditions' => array('action' => 'lehrkap', 'school' => $snr, 'comment' => 'vor Viva')));
            $vdata->select(['data']);
            //debug($vdata->first()->data);
            $ndata = $this->Monitorings->find('all', array('conditions' => array('action' => 'lehrkap', 'school' => $snr, 'comment' => 'nach Viva')));
            //debug($ndata->first()->data);
            $ndata->select(['data']);
            $data[$snr]['vor'] = $vdata->first()->data;
            $data[$snr]['nach'] = $ndata->first()->data;
            //debug($data);
        }
        $this->set('data', $data);
    }

    public function examine()
    {
        //$login_data = $this->request->session()->read('data');

        if ($this->request->is('post')) {

            //debug($this->request->data['school_nr']);die;

            $login_data = [
                'asd_username' => 'A005_TrinklW',
                'asd_password' => 'HiegTzs!12',
            ];
            $school_nr = $this->request->data['school_nr'];
            //$school_nr = '0181';

            $ch = $this->Tools->init_curl_params();
            $this->login_school($ch);

            $text = $this->Tools->asd_curl($ch, '', array(), '/asddv/dv_xy_00.jsf');

            $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');

            $post = [
                'login:username' => $login_data['asd_username'],
                'login:password' => $login_data['asd_password'],
                'login' => 'login',
                'javax.faces.ViewState' => $viewstate,
                'login:loginButton' => 'login:loginButton',
            ];
            $text = $this->Tools->asd_curl($ch, $post, array('Content-Type: application/x-www-form-urlencoded'), '/login/login.jsf');

            $text = $this->Tools->asd_curl($ch, '', array(), '/asdus/us_01_01.jsf');

            $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
            $conversationId = $this->get_string_between($text, 'name="conversationId" value="', '" />');

            $post_basic = [
                'mainForm' => 'mainForm',
                'referenzBaumAnzeigen' => 'false',
                'mainForm:hasChanged' => 'false',
                'mainForm:hasNotReleased' => 'false',
                'mainForm:hasPopUpChanged' => 'false',
                'mainForm:hasAdresseChanged' => 'false',
                'mainForm:confirmedOverride' => 'false',
                'mainForm:zuordnungNotification' => 'false',
                'skipvalidation' => 'false',
                'mainForm:istAnzeigeMaske' => 'false',
            ];

            $post = [
                'changeNotification' => 'false',
                'conversationId' => $conversationId,
                'mainForm:dienststelle_schluessel' => $school_nr,
                'mainForm:dienststelle_nameoffiziell' => '',
                'mainForm:dienststelle_dst_wl_dsttyp_id_uebe' => 'EMPTY:0',
                'mainForm:dienststelle_plzstrasse' => '',
                'mainForm:dienststelle_ort' => '',
                'mainForm:dienststelle_sat_kurz_bezeichnung' => 'EMPTY:0',
                'mainForm:dienststelle_bdg_kurz_bezeichnung' => 'EMPTY:0',
                'mainForm:dienststelle_wl_kurz_bezeichnung' => 'EMPTY:0',
                'mainForm:dienststelle_dst_wl_regierung_id_u' => 'EMPTY:0',
                'mainForm:dienststelle_dst_wl_schulamt_id' => 'EMPTY:0',
                'mainForm:dienststelle_referent' => '',
                'mainForm:dienststelle_dst_wl_mb_bezirk_id_u' => 'EMPTY:0',
                'mainForm:dienststelle_status' => 'EMPTY:0',
                'mainForm:dienststelle_sortierung' => 'com.hp.asd.domain.tech.PersProperty:7',
                'mainForm:action_suchen' => 'Suchen',
                'javax.faces.ViewState' => $viewstate,
            ];

            $text = $this->Tools->asd_curl($ch, array_merge($post_basic, $post), array('Content-Type: application/x-www-form-urlencoded'), '/asdus/us_01_01.jsf?cid=' . $conversationId);

            $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
            $conversationId = $this->get_string_between($text, 'name="conversationId" value="', '" />');

            $post = [
                'changeNotification' => 'false',
                'conversationId' => $conversationId,
                'mainForm:resultTable:0:email' => '0001@schulen.bayern.de',
                'mainForm:resultTable:0:j_idt112' => 'on',
                'javax.faces.ViewState' => $viewstate,
                'mainForm:resultTable:0:dienststelle_nameoffiziell' => 'mainForm:resultTable:0:dienststelle_nameoffiziell',
            ];

            $text = $this->Tools->asd_curl($ch, array_merge($post_basic, $post), array('Content-Type: application/x-www-form-urlencoded'), '/asdus/us_01_02.jsf?cid=' . $conversationId);

            //debug($text);die;
            //$output = $this->Tools->asd_basic($text);
            //$this->set('output', $output);

            $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
            $conversationId = $this->get_string_between($text, 'name="conversationId" value="', '" />');
            $mask = $this->get_string_between($text, '/uniquesig0/asd/asdus/', '.jsf?cid=');
            //debug($mask);
            //debug($text);die;
            $post = [
                'conversationId' => $conversationId,
                'changeNotification' => 'true',
                'mainForm:schulnummer' => $school_nr,
                'mainForm:schule' => 'Leibniz-Gymnasium+Altdorf',
                'mainForm:schulstellePlzStrasse' => 'Gymnasium',
                'mainForm:lehrkapazitaet' => 'Lehrkapazit%C3%A4t',
                'mainForm:erhebungsinformationskommentar' => '',
                'mainForm:statusaenderungen_kommentar' => '',
                'javax.faces.ViewState' => $viewstate,
            ];

            if ($mask == 'us_01_10') {
                $schooltype = 'gms';
                $schuleSelect = $this->get_string_between($text, 'name="mainForm:schuleSelect" class="w100p" size="1" onchange="submit()">	<option value="', '" selected="selected">');
                //debug($schuleSelect);
                //debug($text);die;

                $post = [
                    'conversationId' => $conversationId,
                    'changeNotification' => 'true',
                    'mainForm:schuleSelect' => $schuleSelect,
                    'mainForm:lehrkapazitaet' => 'Lehrkapazität',
                    'mainForm:erhebungsinformationskommentar' => '',
                    'mainForm:statusaenderungen_kommentar' => '',
                    'javax.faces.ViewState' => $viewstate,
                ];
            } else {
                $schooltype = 'gymreal';
            }
            $text = $this->Tools->asd_curl($ch, array_merge($post_basic, $post), array('Content-Type: application/x-www-form-urlencoded'), '/asdus/' . $mask . '.jsf?cid=' . $conversationId);
            //debug('/asdus/' . $mask . '.jsf?cid=' . $conversationId);
            //echo $text;die;
            $data = $this->Tools->asd_lk($text, $schooltype);

            $this->set('t_heads', $data['t_heads']);
            $this->set('teachers', $data['teachers']);

            $data['action'] = 'lehrkap';
            $data['school'] = $school_nr;
            $data['data'] = json_encode($data['teachers']);
            $now = Time::parse();
            $now->timezone = "Europe/Berlin";
            $data['date'] = $now;
            $data['comment'] = 'nach Viva';
            $monitoring = $this->Monitorings->newEntity();
            $monitoring = $this->Monitorings->patchEntity($monitoring, $data);
            $result = $this->Monitorings->save($monitoring);

            /* $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
            $conversationId = $this->get_string_between($text, 'name="conversationId" value="', '" />');

            $post = [
            'conversationId' => $conversationId,
            'changeNotification' => 'true',
            'mainForm:schulnummer' => $school_nr,
            'mainForm:schule' => 'Oskar-von-Miller-Gymnasium München',
            'mainForm:schulstellePlzStrasse' => 'Gymnasium',
            'mainForm:lehrkapazitaetFach' => 'Lehrkap./Fach',
            'mainForm:selectedUnterrichtsfach' => 'alle',
            'mainForm:resultTable:wi' => '',
            'mainForm:resultTable:cols' => '',
            'mainForm:resultTable:si' => '|||',
            'javax.faces.ViewState' => $viewstate
            ];
            $text = $this->Tools->asd_curl($ch, array_merge($post_basic, $post), array('Content-Type: application/x-www-form-urlencoded'), '/asdus/us_01_50.jsf?cid=' . $conversationId);

            $data = $this->Tools->asd_lf($text);

            $this->set('t_headslf', array_merge(array('Name'), $data['t_headslf']));
            $this->set('lehrfach', $data['lehrfach']); */

            //debug($output);
            $this->set('text', $text);
            $this->render(null, 'asd');
        }
    }

    public function asdus()
    {
        $save = false;
        if (!empty($this->request['pass'])) {
            $command = $this->request['pass']['0'];
            if ($command == 'save') {
                $save = true;
            }
        }
        //$login_data = $this->request->session()->read('data');
        $login_data = [
            'asd_username' => 'A005_TrinklW',
            'asd_password' => 'HiegTzs!12',
        ];

        $ch = $this->Tools->init_curl_params();
        $this->login_school($ch);
        // ASD aufrufen - Step 3

        $text = $this->Tools->asd_curl($ch, '', array(), '/asddv/dv_xy_00.jsf');

        //debug($text);die;

        $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
        $post = [
            'login:username' => $login_data['asd_username'],
            'login:password' => $login_data['asd_password'],
            'login' => 'login',
            'javax.faces.ViewState' => $viewstate,
            'login:loginButton' => 'login:loginButton',
        ];
        $text = $this->Tools->asd_curl($ch, $post, array('Content-Type: application/x-www-form-urlencoded'), '/login/login.jsf');
        //debug($text);die;

        $schularten = array(
            'Gymnasium' => '747',
            'Grundsch.sow.Mittelschule' => '742',
            'Realschule' => '745',
            'Abendrealschule' => '752',
            'Realschule z. sp. F.' => '746',
            'Schulartunabhängige Orientierungsstufe' => '749',
            'Integrierte Gesamtschule' => '750',
        );
        $output = array();
        foreach ($schularten as $sakey => $savalue) {

            $text = $this->Tools->asd_curl($ch, '', array(), '/asdus/us_03_01.jsf');

            $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
            $conversationId = $this->get_string_between($text, 'name="conversationId" value="', '" />');

            $post = [
                'mainForm' => 'mainForm',
                'referenzBaumAnzeigen' => 'false',
                'conversationId' => $conversationId,
                'changeNotification' => 'false',
                'mainForm:hasChanged' => 'false',
                'mainForm:hasNotReleased' => 'false',
                'mainForm:hasPopUpChanged' => 'false',
                'mainForm:hasAdresseChanged' => 'false',
                'mainForm:confirmedOverride' => 'false',
                'mainForm:zuordnungNotification' => 'false',
                'skipvalidation' => 'false',
                'mainForm:istAnzeigMaske' => 'false',
                'mainForm:dienststellenName' => '',
                'mainForm:schulart' => '',
                'mainForm:teilnehmendeGesamt' => '',
                'mainForm:nichtAbgegebenKeinLv' => '',
                'mainForm:nichtAbgegebenLv' => '',
                'mainForm:vollstaendigMitPlFehler' => '',
                'mainForm:vollstaendigOhnePlFehler' => '',
                'mainForm:abgegeben=&' => '',
                'mainForm:abgelehnt' => '',
                'mainForm:freigegeben' => '',
                'mainForm:us_03_01_popup_selectSchulart' => 'com.hp.asd.wl.domain.standard.SchulartRechtlich:' . $savalue,
                'mainForm:popup_ok' => 'Ok',
                'javax.faces.ViewState' => $viewstate,
            ];

            $text = $this->Tools->asd_curl($ch, $post, array('Content-Type: application/x-www-form-urlencoded'), '/asdus/us_03_01.jsf?cid=' . $conversationId);

            $htmlParser = new \DOMDocument(); //to parse html using DOMDocument
            libxml_use_internal_errors(true); // your HTML gives parser warnings, keep them internal
            $htmlParser->loadHTML($text); //Loaded the html string we took from simple xml
            $htmlParser->preserveWhiteSpace = false;
            $fields = array(
                'Teilnehmende Schulen insgesamt' => 'mainForm:teilnehmendeGesamt',
                'Schulen nicht übermittelt (kein Lieferversuch)' => 'mainForm:nichtAbgegebenKeinLv',
                'Schulen nicht übermittelt (Lieferversuch)' => 'mainForm:nichtAbgegebenLv',
                'Schulen übermittelt (PL-Fehler)' => 'mainForm:vollstaendigMitPlFehler',
                'Schulen übermittelt (keine PL-Fehler)' => 'mainForm:vollstaendigOhnePlFehler',
                'Schulen abgegeben' => 'mainForm:abgegeben',
                'Schulen von Schulaufsicht abgelehnt' => 'mainForm:abgelehnt',
                'Schulen von Schulaufsicht freigegeben' => 'mainForm:freigegeben');

            foreach ($fields as $key => $field) {
                $output[$sakey][$key] = $htmlParser->getElementById($field)->getAttribute('value');
            }
        }

        // staatliche Gymnasien
        $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
        $conversationId = $this->get_string_between($text, 'name="conversationId" value="', '" />');
        $post = [
            'sideMenu' => 'sideMenu',
            'javax.faces.ViewState' => $viewstate,
            'sideMenu:j_idt51:0:j_idt57:1:j_idt59' => 'sideMenu:j_idt51:0:j_idt57:1:j_idt59',
        ];
        $text = $this->Tools->asd_curl($ch, $post, array('Content-Type: application/x-www-form-urlencoded'), '/asdus/us_03_01.jsf?cid=' . $conversationId);
        $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
        $conversationId = $this->get_string_between($text, 'name="conversationId" value="', '" />');
        $post = [
            'mainForm' => 'mainForm',
            'referenzBaumAnzeigen' => 'false',
            'conversationId' => $conversationId,
            'changeNotification' => 'false',
            'mainForm:hasChanged' => 'false',
            'mainForm:hasNotReleased' => 'false',
            'mainForm:hasPopUpChanged' => 'false',
            'mainForm:hasAdresseChanged' => 'false',
            'mainForm:confirmedOverride' => 'false',
            'mainForm:zuordnungNotification' => 'false',
            'skipvalidation' => 'false',
            'mainForm:istAnzeigeMaske' => 'false',
            'mainForm:dienststelle_schluessel' => '',
            'mainForm:dienststelle_nameoffiziell' => '',
            'mainForm:dienststelle_dst_wl_dsttyp_id_uebe' => 'com.hp.asd.wl.domain.standard.Dienststellentyp:1671',
            'mainForm:dienststelle_plzstrasse' => '',
            'mainForm:dienststelle_ort' => '',
            'mainForm:dienststelle_sat_kurz_bezeichnung' => 'com.hp.asd.wl.domain.standard.SchulartRechtlich:747',
            'mainForm:dienststelle_bdg_kurz_bezeichnung' => 'EMPTY:0',
            'mainForm:dienststelle_wl_kurz_bezeichnung' => 'EMPTY:0',
            'mainForm:dienststelle_dst_wl_regierung_id_u' => 'EMPTY:0',
            'mainForm:dienststelle_dst_wl_schulamt_id' => 'EMPTY:0',
            'mainForm:dienststelle_referent' => '',
            'mainForm:dienststelle_dst_wl_mb_bezirk_id_u' => 'EMPTY:0',
            'mainForm:dienststelle_status' => 'EMPTY:0',
            'mainForm:dienststelle_sortierung' => 'com.hp.asd.domain.tech.PersProperty:7',
            'mainForm:action_suchen' => 'Suchen',
            'javax.faces.ViewState' => $viewstate,
        ];
        $text = $this->Tools->asd_curl($ch, $post, array('Content-Type: application/x-www-form-urlencoded'), '/asdus/us_01_01.jsf?cid=' . $conversationId);
        $viewstate = $this->get_string_between($text, 'id="javax.faces.ViewState" value="', '" autocomplete');
        $conversationId = $this->get_string_between($text, 'name="conversationId" value="', '" />');
        $post = [
            'mainForm' => 'mainForm',
            'referenzBaumAnzeigen' => 'false',
            'conversationId' => $conversationId,
            'changeNotification' => 'false',
            'mainForm:hasChanged' => 'false',
            'mainForm:hasNotReleased' => 'false',
            'mainForm:hasPopUpChanged' => 'false',
            'mainForm:hasAdresseChanged' => 'false',
            'mainForm:confirmedOverride' => 'false',
            'mainForm:zuordnungNotification' => 'false',
            'skipvalidation' => 'true',
            'mainForm:istAnzeigeMaske' => 'false',
            'mainForm:resultTable:0:email' => '0252@schulen.bayern.de',
            'mainForm:resultTable:0:j_idt112' => 'on',
            'mainForm:resultTable:1:email' => '0282@schulen.bayern.de',
            'mainForm:resultTable:1:j_idt112' => 'on',
            'mainForm:resultTable:2:email' => '0180@schulen.bayern.de',
            'mainForm:resultTable:2:j_idt112' => 'on',
            'mainForm:resultTable:3:email' => '0072@schulen.bayern.de',
            'mainForm:resultTable:3:j_idt112' => 'on',
            'mainForm:resultTable:4:email' => '0151@schulen.bayern.de',
            'mainForm:resultTable:4:j_idt112' => 'on',
            'javax.faces.ViewState' => $viewstate,
            'mainForm:j_idt183' => 'mainForm:j_idt183',
        ];
        $text = $this->Tools->asd_curl($ch, $post, array('Content-Type: application/x-www-form-urlencoded'), '/asdus/us_01_02.jsf?cid=' . $conversationId);
        $htmlParser = new \DOMDocument(); //to parse html using DOMDocument
        libxml_use_internal_errors(true); // your HTML gives parser warnings, keep them internal
        $htmlParser->loadHTML($text); //Loaded the html string we took from simple xml
        $htmlParser->preserveWhiteSpace = false;

        $table = $htmlParser->getElementById('mainForm:resultTable');
        //debug($table);

        $rows = $table->getElementsByTagName('tr');
        $i = 0;
        foreach ($rows as $row) {
            //debug('Hallo');
            if ($i > 0) {
                $cols = $row->getElementsByTagName('td');
                $status[$i] = $cols->item(5)->nodeValue;
            }
            $i++;
        }
        $result = array_count_values($status);

        $output2['Staatliche Gymnasien']['Teilmende Schulen insgesamt'] = sizeof($status);
        if (!isset($result['n. überm. (kein Liefervers.)'])) {
            $output2['Staatliche Gymnasien']['Schulen nicht übermittelt (kein Lieferversuch)'] = 0;
        } else {
            $output2['Staatliche Gymnasien']['Schulen nicht übermittelt (kein Lieferversuch)'] = $result['n. überm. (kein Liefervers.)'];
        }
        if (!isset($result['n. überm. (Lieferversuch)'])) {
            $output2['Staatliche Gymnasien']['Schulen nicht übermittelt (Lieferversuch)'] = 0;
        } else {
            $output2['Staatliche Gymnasien']['Schulen nicht übermittelt (Lieferversuch)'] = $result['n. überm. (Lieferversuch)'];
        }
        if (!isset($result['übermittelt (PL-Fehler)'])) {
            $output2['Staatliche Gymnasien']['Schulen übermittelt (PL-Fehler)'] = 0;
        } else {
            $output2['Staatliche Gymnasien']['Schulen übermittelt (PL-Fehler)'] = $result['übermittelt (PL-Fehler)'];
        }
        if (!isset($result['übermittelt (keine PL-Fehler)'])) {
            $output2['Staatliche Gymnasien']['Schulen übermittelt (keine PL-Fehler)'] = 0;
        } else {
            $output2['Staatliche Gymnasien']['Schulen übermittelt (keine PL-Fehler)'] = $result['übermittelt (keine PL-Fehler)'];
        }
        if (!isset($result['abgegeben'])) {
            $output2['Staatliche Gymnasien']['Schulen abgegeben'] = 0;
        } else {
            $output2['Staatliche Gymnasien']['Schulen abgegeben'] = $result['abgegeben'];
        }
        if (!isset($result['Schulaufs. abgelehnt'])) {
            $output2['Staatliche Gymnasien']['Schulen von Schulaufsicht abgelehnt'] = 0;
        } else {
            $output2['Staatliche Gymnasien']['Schulen von Schulaufsicht abgelehnt'] = $result['Schulaufs. abgelehnt'];
        }
        if (!isset($result['Schulaufs. freigegeben'])) {
            $output2['Staatliche Gymnasien']['Schulen von Schulaufsicht freigegeben'] = 0;
        } else {
            $output2['Staatliche Gymnasien']['Schulen von Schulaufsicht freigegeben'] = $result['Schulaufs. freigegeben'];
        }

        $output = array_merge($output2, $output);
        //debug($output);die;

        if ($save) {
            $data['action'] = 'asdus';
            $data['school'] = '';
            $data['data'] = json_encode($output);
            $now = Time::parse();
            $now->timezone = "Europe/Berlin";
            $data['date'] = $now;
            $data['comment'] = '';
            $monitoring = $this->Monitorings->newEntity();
            $monitoring = $this->Monitorings->patchEntity($monitoring, $data);
            $result = $this->Monitorings->save($monitoring);
        }

        $all = $this->Monitorings->find('all', array('conditions' => array('action' => 'asdus'), 'order' => array('id' => 'DESC')));
        $old = $all->first();
        $now = Time::parse();
        $now->timezone = "Europe/Berlin";
        $this->set('now', $now);
        $this->set('old', $old);
        $this->set('output', $output);
        $this->set('text', $text);
        $viewOutput = $this->render();
        $path = WWW_ROOT . 'files/html/asdus.html';
        $file = new File($path, true);
        $file->write($viewOutput);
        $file->close();
    }

    public function mstr()
    {

        $SCHULPORTAL_MSTR_BASE_URL = SCHULPORTAL_BASE0_URL . '/uniquesig9adaec6129c81dbeb2f42638bc9f27ac0c442a10891f0c915c9d7f0c371a00b3/uniquesig1/asd';
        $reportID = '3F1FE53C4583613BABF14EA6242BACBE';

        $ch = $this->Tools->init_curl_params();
        $this->login_school($ch);

        // MSTR aufrufen - Step 3

        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array());

        curl_setopt($ch, CURLOPT_URL, $SCHULPORTAL_MSTR_BASE_URL . '/servlet/mstrWeb');
        $text = curl_exec($ch);

        $post = [
            'Uid' => 'A005_TrinklW',
            'Pwd' => 'HiegTzs!12',
        ];

        $mstr_login_vars = array('ConnMode', '3054', 'evt', 'src', 'target', 'key', 'Port', 'Project', 'Server', 'login', 'smartBanner', 'lb');

        foreach ($mstr_login_vars as $var) {
            $value = $this->get_string_between($text, 'name="' . $var . '" value=', 'type="hidden"');
            $pvar[$var] = $value;
        }
        $post = array_merge($post, $pvar);
        //debug($post);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

        // Bei MSTR uber Formular anmelden - Step 4

        curl_setopt($ch, CURLOPT_URL, $SCHULPORTAL_MSTR_BASE_URL . '/servlet/mstrWeb');
        $text = curl_exec($ch);

        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array());

        // MSTR Bericht ausführen - Step 5

        $htmlParser = new \DOMDocument(); //to parse html using DOMDocument
        libxml_use_internal_errors(true); // your HTML gives parser warnings, keep them internal
        $htmlParser->loadHTML($text); //Loaded the html string we took from simple xml
        $htmlParser->preserveWhiteSpace = false;

        $links = $htmlParser->getElementsByTagName('a');
        foreach ($links as $link) {
            if ($link->nodeValue == 'Amtliche Schulstatistik') {
                $params = explode('&', $link->getAttribute('href'));
                foreach ($params as $param) {
                    $parts = explode('=', $param);
                    $lp[$parts[0]] = $parts[1];
                }
            }
        }

        curl_setopt($ch, CURLOPT_URL, $SCHULPORTAL_MSTR_BASE_URL . '/servlet/mstrWeb?evt=3010&src=' . $lp['src'] . '&ServerAlias=' . $lp['ServerAlias'] . '&Port=' . $lp['Port'] . '&Project=' . $lp['Project'] . '&Server=' . $lp['Server'] . '&loginReq=true');
        $text = curl_exec($ch);
        //$this->Tools->screen($SCHULPORTAL_MSTR_BASE_URL . '/servlet/mstrWeb?evt=3010&src=' . $lp['src'] . '&ServerAlias=' . $lp['ServerAlias'] . '&Port=' . $lp['Port'] . '&Project=' . $lp['Project'] . '&Server=' . $lp['Server'] . '&loginReq=true');
        //$this->Tools->screen('https://portal.schulen.bayern.de/uniquesig2d1dfad4a11c25e42c462e53b4721e48/uniquesig0/SecureSchulportalPortalHomePage/');
        //die;
        curl_setopt($ch, CURLOPT_URL, $SCHULPORTAL_MSTR_BASE_URL . '/servlet/mstrWeb?evt=3067&src=mstrWeb.3067&reportViewMode=1&reportID=' . $reportID);

        $text = curl_exec($ch);

        $post = array();
        $pvar = array();
        $mstr_result_vars = array('evt', 'src', 'reportViewMode', 'reportID', 'fastExport', 'rsfb', 'rb', 'directExport');
        foreach ($mstr_result_vars as $var) {
            $value = $this->get_string_between($text, 'name="' . $var . '" value=', 'type="hidden"');
            $pvar[$var] = $value;
        }
        $post = array_merge($post, $pvar);
        $action = $this->get_string_between($text, 'FORM ACTION="mstrWeb', 'ID="printForm"');

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

        // MSTR fertigen Bericht anzeigen - Step 6

        curl_setopt($ch, CURLOPT_URL, $SCHULPORTAL_MSTR_BASE_URL . '/servlet/mstrWeb' . $action);
        sleep(20);
        $text = curl_exec($ch);

        $post = array();
        $pvar = array();
        $mstr_down_vars = array('evt', 'src', 'SaveReportProperties', 'rb');
        foreach ($mstr_down_vars as $var) {
            $value = $this->get_string_between($text, 'name="' . $var . '" value=', 'type="hidden"');
            $pvar[$var] = $value;
        }
        $post = array_merge($post, $pvar);
        $action = $this->get_string_between($text, 'FORM ACTION="', 'ID="printForm"');

        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_URL, $SCHULPORTAL_MSTR_BASE_URL . '/servlet/' . $action);

        $text = curl_exec($ch);

        // Von MSTR abmelden - Step 8

        $post = [
            'evt' => '3008',
            'src' => 'mstrWeb.3008',
            'xts' => exec('date +%s%3N'),
        ];

        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_URL, $SCHULPORTAL_MSTR_BASE_URL . '/servlet/mstrWeb');
        $logout = curl_exec($ch);

        // Vom Schulportal abmelden - Step 9

        curl_close($ch);

        $text = iconv($in_charset = 'UTF-16LE', $out_charset = 'UTF-8', $text);

        //Ergebnis in Datenbank speichern

        $data['action'] = 'mstr';
        $data['school'] = '';
        $data['data'] = json_encode($text);
        $now = Time::parse();
        $now->timezone = "Europe/Berlin";
        $data['date'] = $now;
        if (strpos($text, 'MMIHG') !== false) {
            $data['comment'] = 'Success';
        } else {
            $data['comment'] = 'Fail';
        }
        $monitoring = $this->Monitorings->newEntity();
        $monitoring = $this->Monitorings->patchEntity($monitoring, $data);
        $result = $this->Monitorings->save($monitoring);

        $this->set('text', $text);
        $this->viewBuilder()->layout('ajax');
    }

    public function showFails()
    {
        $data = $this->Monitorings->find('all', array('conditions' => array('comment' => 'Fail', 'action' => 'mstr')));
        $this->set('data', $data);
    }

}
