<?php
namespace AsdCurl;

use Cake\Core\Configure; 



class AsdCurl
{
    public $status;
    public $error;
    public $html;
    public $message;

    public function __construct()
    {
        $this->status = false;
        $this->error = false;
        $this->html = '';
        $this->message = '';
    }

    public function init_curl_params()
    {
        $ch = curl_init('https://portal.schulen.bayern.de/');
        //curl_setopt($ch, CURLOPT_PROXY, Configure::read('AsdCurl.proxy'));
        //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
        curl_setopt($ch, CURLOPT_PROXY, "");
        curl_setopt($ch, CURLOPT_USERAGENT, Configure::read('AsdCurl.useragent'));
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIEJAR, Configure::read('AsdCurl.cookiejar'));
        curl_setopt($ch, CURLOPT_COOKIEFILE, Configure::read('AsdCurl.cookiefile'));
        curl_setopt($ch, CURLOPT_COOKIE, Configure::read('AsdCurl.cookie'));
        curl_setopt($ch, CURLOPT_SSLCERT, Configure::read('AsdCurl.cert'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        return ($ch);
    }

    public function get_string_between($string, $start, $end)
    {
        //debug($start);
        //debug($end);
        $string = " " . $string;
        $ini = strpos($string, $start);
        //debug($ini);
        //debug($string);die;
        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)
    {
        //debug($url);die;
        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);
        //echo 'Hallo';
        //echo $this->html;die;
        //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 login_asd($ch)
    {
        $SCHULPORTAL_ASD_BASE_URL = Configure::read('AsdCurl.asdbaseurl');
        $this->exec_curl($ch, $SCHULPORTAL_ASD_BASE_URL . '/asddv/dv_xy_00.jsf', false);
        if(!($this->status)) {
            die($this->error);
        }
        $viewstate = $this->get_string_between($this->html, 'id="javax.faces.ViewState" value="', '" autocomplete');

        $login_data = [
            'asd_username' => 'A005_TrinklW',
            'asd_password' => 'HiegTzs!183',
            //'asd_username' => 'A005_KnollmüllerP',
            //'asd_password' => 'Ooricha8e!',
        ];
        $post = [
            'login:username' => $login_data['asd_username'],
            'login:password' => $login_data['asd_password'],
            'login' => 'login',
            'javax.faces.ViewState' => $viewstate,
            'login:loginButton' => 'login:loginButton',
        ];
        $this->exec_curl($ch, $SCHULPORTAL_ASD_BASE_URL . '/login/login.jsf', $post);
        if(!($this->status)) {
            die($this->error);
        }
        $viewstate = $this->get_string_between($this->html, 'id="javax.faces.ViewState" value="', '" autocomplete');
        Configure::write('Session', ['viewstate' =>  $viewstate]);
        //echo $this->html;die;
    }

    public function login_mstr($ch) {
        $SCHULPORTAL_MSTR_BASE_URL = Configure::read('AsdCurl.mstrbaseurl');
        $url = '/asp';
        //debug($SCHULPORTAL_MSTR_BASE_URL . $url);die;
        $this->exec_curl($ch, $SCHULPORTAL_MSTR_BASE_URL . $url, false);

        //debug($this->html);die;

        $post = [
            'Uid' => 'A005_TrinklW',
            'Pwd' => 'HiegTzs!12',
        ];
        $pvar['ConnMode'] = $this->get_string_between($this->html, '<input name="ConnMode" id="ConnMode" type="hidden" class="mstrHiddenInput" value="', '"/>');
        $pvar['3054'] = $this->get_string_between($this->html, '<input name="3054" id="3054" type="submit" value="', '" class="mstrButton"/>');
        $mstr_login_vars = array('evt', 'src', 'target', 'key', 'Port', 'Project', 'Server', 'login', 'smartBanner', 'lb');
        foreach ($mstr_login_vars as $var) {
            $value = $this->get_string_between($this->html, 'name="' . $var . '" type="hidden" class="mstrHiddenInput" value="', '"/>');
            //$value = $this->get_string_between($this->html, 'name="' . $var . '" value=', 'type="hidden"');
            $pvar[$var] = $value;
        }
        
        $post = array_merge($post, $pvar);
        //debug($post);die;
        $this->exec_curl($ch, $SCHULPORTAL_MSTR_BASE_URL . '/asp/Main.aspx', $post);
        if(strpos($this->html,'Login failure')) {
            $this->status = false;
        }     
        //debug($this->html);die;
    }

    public function logout_mstr($ch) {
        $SCHULPORTAL_MSTR_BASE_URL = Configure::read('AsdCurl.mstrbaseurl');
        $url = '/asp/Main.aspx';
        $post = [
            'evt' => '3008',
            'src' => 'mstrWeb.3008',
            'xts' => exec('date +%s%3N'),
        ];
        $this->exec_curl($ch, $SCHULPORTAL_MSTR_BASE_URL . $url, $post);
        curl_close($ch);
    }

    public function login_school($ch)
    {
        //echo 'Hallo';die;
        $SCHULPORTAL_BASE0_URL = Configure::read('AsdCurl.schulbase0url');
        //$SCHULPORTAL_BASE0_URL = "https://portal.schulen.bayern.de/SecureSchulportalPortalHomePage";
        $SCHULPORTAL_BASE_URL = Configure::read('AsdCurl.schulbaseurl');
        //$SCHULPORTAL_BASE_URL = Configure::read('AsdCurl.schulbaseurl') . '/SecureSchulportalPortalHomePage';
        //$login_data = $this->request->session()->read('data');

        //echo  $SCHULPORTAL_BASE_URL; 

        $this->exec_curl($ch, $SCHULPORTAL_BASE_URL, false);
        if(!($this->status)) {
            die($this->error);
        }
        //echo $this->html; die;
        $login_data = [
            'portal_username' => 'asd.trinkl',
            'portal_password' => 'HiegTzs!184',
        ];

        $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',
        ];
        // Anmeldeformular fuer das Schulportal abschicken - Step 2

//https://portal.schulen.bayern.de/uniquesig2d1dfad4a11c25e42c462e53b4721e48/uniquesig0/SecureSchulportalPortalHomePage/
        //$this->exec_curl($ch, $SCHULPORTAL_BASE_URL . '/SecureSchulportalPortalHomePage', $post);
        $this->exec_curl($ch, $SCHULPORTAL_BASE_URL . '/InternalSite/Validate.asp', $post);
        if(!($this->status)) {
            die($this->error);
        }
        //debug($this->html);die;
    }

    public function exec_mstr($ch, $url, $post)
    {
        $SCHULPORTAL_MSTR_BASE_URL = Configure::read('AsdCurl.mstrbaseurl');
        $html = $this->exec_curl($ch, $SCHULPORTAL_MSTR_BASE_URL . $url, $post);
        return ($html);
    }
}
