<?php
namespace App\Controller;

use App\Controller\AppController;
use Spatie\ArrayToXml\ArrayToXml;

class StudiesController extends AppController
{
    public $html;
    public $error;
    public $status;

    public function getElementsByClass(&$parentNode, $tagName, $className) {
        $nodes=array();
    
        $childNodeList = $parentNode->getElementsByTagName($tagName);
        for ($i = 0; $i < $childNodeList->length; $i++) {
            $temp = $childNodeList->item($i);
            if (stripos($temp->getAttribute('class'), $className) !== false) {
                $nodes[]=$temp;
            }
        }   
        return $nodes;
    }

    public function array2xml($array,  $xml = false){
        if($xml === false){
            $xml = new \SimpleXMLElement('<xjxobj/>');
        }
        foreach($array as $key => $value){
            if(is_array($value)){
                $this->array2xml($value, $xml->addChild($key));
            }else{
                $xml->addChild($key, $value);
            }
        }
        return $xml->asXML();
    }

    public function init_curl_params()
    {
        $ch = curl_init();
        if($_SERVER['SERVER_NAME'] != 'asd-control.wtrinkl.de') {
            curl_setopt($ch, CURLOPT_PROXY, '10.1.248.1:82');
        }
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0');
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        return ($ch);
    }

    public 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);
    }

    public function exec_curl($ch, $url, $post)
    {
        if ($post == false) {
            curl_setopt($ch, CURLOPT_POST, 0);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array());
        } else {
            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'));
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        $this->html = curl_exec($ch);
        //debug(curl_errno($ch));
        //debug(curl_getinfo($ch, CURLINFO_HTTP_CODE));
        if (curl_errno($ch)) {
            $this->status = false;
            $this->error = 'Couldn\'t send request: ' . curl_error($ch);
        } else {
            $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($resultStatus != 200) {
                $this->status = false;
                $this->error = 'Request failed: HTTP status code: ' . $resultStatus;
            }
        }
    }

    public function ajaxCount() {

        $request = $this->request->query;
        //debug($request);die;

        $ch = $this->init_curl_params();
        $xjxobj = [
            'e' => [
                (int)  0 => ['k' =>  '0', 'v' => 'iframe'],
                (int)  1 => ['k' =>  '1', 'v' => '1'],
                (int)  2 => ['k' =>  '2', 'v' => 'tx_szhrksearch_pi1[bundesland][]'],
                (int)  3 => ['k' =>  '3', 'v' => '2'],
                (int)  4 => ['k' =>  '4', 'v' => 'tx_szhrksearch_pi1[search]'],
                (int)  5 => ['k' =>  '5', 'v' => '1'],
                (int)  6 => ['k' =>  '6', 'v' => 'tx_szhrksearch_pi1[fach]'],
                (int)  7 => ['k' =>  '7', 'v' => $request['fachrichtung']],
                (int)  8 => ['k' =>  '8', 'v' => 'tx_szhrksearch_pi1[studtyp]'],
                (int)  9 => ['k' =>  '9', 'v' => '3'],
                (int) 10 => ['k' => '10', 'v' => []],
                (int) 11 => ['k' => '11', 'v' => '3'],
                (int) 12 => ['k' => '12', 'v' => 'tx_szhrksearch_pi1[zubesch][]'],
                (int) 13 => ['k' => '13', 'v' => 'O'],
                (int) 14 => ['k' => '14', 'v' => 'tx_szhrksearch_pi1[ort]'],
                (int) 15 => ['k' => '15', 'v' => 'Regensburg'],
                (int) 16 => ['k' => '16', 'v' => 'tx_szhrksearch_pi1[plzdist]'],
                (int) 17 => ['k' => '17', 'v' => '25']
            ]
        ];
        $test = ArrayToXml::convert($xjxobj,'xjxobj');
        $test = trim(str_replace('<?xml version="1.0"?>','',$test));
        $url = 'https://www.hochschulkompass.de/en/degree-programmes/study-in-germany-search/advanced-degree-programme-search.html?type=9993';

        $post = [
            'xajax' => 'getCount',
            'xajaxr' => exec('date +%s%3N'),
            'xajaxargs[]' => $test
        ];

        debug($post);

        $this->exec_curl($ch, $url, $post);

        //debug($this->html);

        $xml_count = simplexml_load_string($this->html);
        $json_count = json_encode($xml_count);
        $array_count = json_decode($json_count,TRUE);

        $count = $array_count['cmd']['xjxobj']['e']['v'];
        $this->set('count',$count);
        $this->viewBuilder()->layout('ajax');
    }

    public function getparams()
    {
        $ch = $this->init_curl_params();
        $post ='';
        $url = 'https://www.hochschulkompass.de/en/bavaria/degree-programmes/study-in-germany-search/advanced-degree-programme-search.html';
        $this->exec_curl($ch, $url, $post);
        //debug($this->html);
        $htmlParser = new \DOMDocument(); //to parse html using DOMDocument
        libxml_use_internal_errors(true); // your HTML gives parser warnings, keep them internal
        $htmlParser->loadHTML($this->html); //Loaded the html string we took from simple xml
        $htmlParser->preserveWhiteSpace = false;

        $selects = ['zusemester','sprache'];
        $singles = array();
        foreach ($selects as $select) {
            $languages = array();
            $items = $htmlParser->getElementById($select);
            //debug($items->getAttribute('name'));
        
            $rows = $items->getElementsByTagName('option');
            foreach ($rows as $row) {             
                //debug($row->nodeValue);
                //debug($row->getAttribute('value'));
                $singles[$select][$row->nodeValue] = $row->getAttribute('value');
            }  
        }  
        //debug($singles);

        $label_arr = array();
        $labels = $htmlParser->getElementsByTagName('label');
        foreach ($labels as $label) {
            $label_arr[$label->getAttribute('for')] =$label->nodeValue;       
        }
        //debug($label_arr);
        //die;
        
        $multi_arr = array();

        $xpath = new \DOMXpath($htmlParser);
        $articles = $xpath->query('//div[@class="hrk-select select td-0"]');
        //debug($articles);
        foreach($articles as $article) {
            $sginputs = $article->getElementsByTagName('input');
            foreach($sginputs as $sginput) {
                $multi_arr['sachgr'][$label_arr[$sginput->getAttribute('id')]] = $sginput->getAttribute('id');
                //debug($sginput->getAttribute('id'));
                //debug($label_arr[$sginput->getAttribute('id')]);
            }
            
        }
        

        $multis = ['besform', 'zubesch', 'abschluss' ];
        
        $inputs = $htmlParser->getElementsByTagName('input');
        
        foreach ($multis as $multi) {
        
            //debug($inputs);
            foreach ($inputs as $input) {
                $id = $input->getAttribute('id');
                //debug($id);
                if (!empty($id)) {
                    //debug(strpos($id,$multi));
                    if (strpos($id,$multi) === 0) {
                        $input_id = $input->getAttribute('id');
                        //debug($input_id);
                        //debug($label_arr[$input_id]);
                        $multi_arr[$multi][$label_arr[$input_id]] = $input->getAttribute('value');
                        //debug($input->getAttribute('value'));
                    }
                }
            }
        }

        $this->set('singles', $singles);
        $this->set('multi_arr', $multi_arr);
        $this->viewBuilder()->layout('studies');
        
    }

    public function index()
    {  
        
        $get = [
            'iframe'=>'1',
            'tx_szhrksearch_pi1[bundesland][]'=>'2',
            'tx_szhrksearch_pi1[search]'=>'1',
            'genios'=>'',
            'tx_szhrksearch_pi1[fach]'=>'Physics',
            'tx_szhrksearch_pi1[studtyp]'=>'3',
            'tx_szhrksearch_pi1[zusemester]'=>'',
            'tx_szhrksearch_pi1[lehramt]'=>'',
            'tx_szhrksearch_pi1[sprache]'=>'',
            'tx_szhrksearch_pi1[name]'=>'',
            'tx_szhrksearch_pi1[plz]'=>'',
            'tx_szhrksearch_pi1[ort]'=>'Deggendorf',
            'tx_szhrksearch_pi1[traegerschaft]'=>'',
            'tx_szhrksearch_pi1[plzdist]'=>'25',
            'tx_szhrksearch_pi1[results_at_a_time]'=>'25'
        ];
        $url = 'https://www.hochschulkompass.de/en/degree-programmes/study-in-germany-search/advanced-degree-programme-search.html?';
        //debug(http_build_query($get));
        $url .= http_build_query($get);
        //debug($url);
        //debug($get);
        $this->exec_curl($ch, $url, $post);
        //debug($this->html);die;
        $htmlParser = new \DOMDocument(); //to parse html using DOMDocument
        libxml_use_internal_errors(true); // your HTML gives parser warnings, keep them internal
        $htmlParser->loadHTML($this->html); //Loaded the html string we took from simple xml
        $htmlParser->preserveWhiteSpace = false;

        $list = array();
        $results = $this->getElementsByClass($htmlParser, 'section', 'result-box');

        foreach($results as $result) {
            $properties = (object) array();
            $course = $result->getElementsByTagName('h2')->item(0)->nodeValue;
            $properties->Course = $course;
            $items = $result->getElementsByTagName('li');
            
                foreach($items as $item) {
                    $title =  $this->getElementsByClass($item, 'span', 'title')[0]->nodeValue;
                    $status = $this->getElementsByClass($item, 'span', 'status')[0]->nodeValue;
                    $properties->$title = $status;
                }
            array_push($list,$properties);
        }

        $this->set('list', $list);
        $this->viewBuilder()->layout('studies');
    }
}

