<?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();
        //curl_setopt($ch, CURLOPT_PROXY, Configure::read('AsdCurl.proxy'));
        curl_setopt($ch, CURLOPT_PROXY, false);
        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_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)
    {
        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 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!12',
            'asd_username' => 'A005_Superuser',
            'asd_password' => 'asdtest01',
        ];
        $post = [
            'login:username' => $login_data['asd_username'],
            'login:password' => $login_data['asd_password'],
            'login' => 'login',
            'javax.faces.ViewState' => $viewstate,
            'login:loginButton' => 'login:loginButton',
        ];
        //debug($SCHULPORTAL_ASD_BASE_URL . '/login/login.jsf');die;
        
        $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]);
    }

    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)
    {
        $SCHULPORTAL_BASE0_URL = Configure::read('AsdCurl.schulbase0url');
        $SCHULPORTAL_BASE_URL = Configure::read('AsdCurl.schulbaseurl');
        //$login_data = $this->request->session()->read('data');

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

        $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

        $this->exec_curl($ch, $SCHULPORTAL_BASE_URL . '/InternalSite/Validate.asp', $post);
        if(!($this->status)) {
            die($this->error);
        }
    }

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