<?php

/* * *
 * created by Ringo Lewandrowski
 * Dipl-Ing Multimedia (FH)
 * www.neograph.de
 */

class hbAgbService {

    var $title, $setItUpKey, $description, $sort_order;
    private $agbConfig = array();
    private $agbTexts = array();
    private $accessToken;

    function hbAgbService() {
        $this->code = 'hbAgbService';
        $this->title = HB_AGB_SERVICE_SET_IT_UP_TITLE;
        $this->description = HB_AGB_SERVICE_SET_IT_UP_DESCRIPTION;
        $this->sort_order = HB_AGB_SERVICE_SET_IT_UP_SORT_ORDER;
        $this->enabled = true;
        $this->setItUpKey = "hbAgbServiceKey";
        $this->agbConfig = $this->configLawTexts();
        $this->checkForToken();
    }

    function check() {
        if (!isset($this->_check)) {
            $check_query = go_db_query("select set_it_up_value from " . DB_TBL_SET_IT_UP . " where set_it_up_key = '" . $this->setItUpKey . "'");
            $this->_check = go_db_num_rows($check_query);
        }
        return $this->_check;
    }

    function install() {
        go_db_query("insert into " . DB_TBL_SET_IT_UP . " (set_it_up_title, set_it_up_key, set_it_up_description, set_it_up_group_id, sort_order, date_added) values ('HB_AGB_ACCESS_TOKEN_TITLE', '" . $this->setItUpKey . "', 'HB_AGB_ACCESS_TOKEN_TITLE_DESCRIPTION', '6', 'HB_AGB_SERVICE_SET_IT_UP_SORT_ORDER', now())");
    }

    function remove() {
        go_db_query("delete from " . DB_TBL_SET_IT_UP . " WHERE set_it_up_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
        return array($this->setItUpKey);
    }

    private function checkForToken() {
        $sql = "SELECT set_it_up_value FROM " . DB_TBL_SET_IT_UP . " WHERE set_it_up_key = '" . $this->setItUpKey . "'";
        $check = go_db_query($sql);
        if (go_db_num_rows($check) > 0) {
            $result = go_db_fetch_array($check);
            if ($result['set_it_up_value'] != "") {
                $this->accessToken = trim($result['set_it_up_value']);
                if (!isset($_POST['hbFormPost'])) {
                    $this->renderForm();
                } else {
                    $this->agbTexts = $this->loadLawTexts($this->accessToken);
                    $this->saveInDatabase();
                }
            } else {
                echo 'Sie haben noch keinen Access-Token eingegeben.<br/>Bitte klicken Sie auf bearbeiten und tragen Sie Ihren H&auml;ndlerbund Access-Token ein.<br/><br/>';
            }
        }
    }

    private function configLawTexts() {
        $lawTextConfig = array(
            'impressum' => array(
                'did' => '1293C20B491',
                'beschreibung' => 'Impressum',
                'mysqlTable' => 'pages',
                'mysqlField' => 'pages_html_text',
                'filter' => array(
                    'pages_id' => '6',
                    'pages_title' => 'IMPRESSUM',
                    'language_id' => '5',
                    'sort_order' => '1',
                    'status' => '1'
                )
            ),
            'datenschutz' => array(
                'did' => '12766C5E204',
                'beschreibung' => 'Datenschutzerkl&auml;rung',
                'mysqlTable' => 'info_privacy',
                'mysqlField' => 'Text',
                'filter' => null
            ),
            'rueckgaberecht' => array(
                'did' => '12766C4A6BE',
                'beschreibung' => 'R&uuml;ckgaberecht',
                'mysqlTable' => 'info_give_back',
                'mysqlField' => 'Text',
                'filter' => null
            ),
            'widerrufsrecht' => array(
                'did' => '12766C53647',
                'beschreibung' => 'Widerrufsrecht',
                'mysqlTable' => 'info_give_back',
                'mysqlField' => 'Text',
                'filter' => null
            ),
            'agb' => array(
                'did' => '12766C46A8A',
                'beschreibung' => 'AGB',
                'mysqlTable' => 'info_conditions',
                'mysqlField' => 'Text',
                'filter' => null
            ),
            'versand' => array(
                'did' => '12766C58F26',
                'beschreibung' => 'Versandbedingungen',
                'mysqlTable' => 'info_shipping',
                'mysqlField' => 'Text'
            ),
            'batteriehinweise' => array(
                'did' => '134CBB4D101',
                'beschreibung' => 'Batteriehinweise',
                'mysqlTable' => 'pages',
                'mysqlField' => 'pages_html_text',
                'filter' => array(
                    'pages_title' => 'BATTERIEHINWEISE',
                    'language_id' => '5',
                    'sort_order' => '1',
                    'status' => '1'
                )
            )
        );
        return $lawTextConfig;
    }

    private function loadLawTexts($accessToken) {
        $url = "https://www.hb-intern.de/www/hbm/api/live_rechtstexte.htm?APIkey=1IqJF0ap6GdDNF7HKzhFyciibdml8t4v&did=";
        $tempTexts = array();
        foreach ($this->agbConfig as $lawText) {
            $curlUrl = $url . $lawText['did'] . '&AccessToken=' . $accessToken;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_POST, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_USERAGENT, "INPUT DATA SCRIPT");
            curl_setopt($curl, CURLOPT_URL, $curlUrl);
            $result = curl_exec($curl);
            $result = str_replace("�?�", "&euro;", $result);
            $result = strip_tags($result, "<p><a><br /><br>\n<strong><b>");
            $result = utf8_decode($result);
            curl_close($curl);
            if (!preg_match("/DOCUMENT_NOT_AVAILABLE/i", $result) && !preg_match("/SHOP_NOT_FOUND/i", $result)) {
                $tempTexts[] = array($lawText['beschreibung'] => $result);
            } else {
                $tempTexts[] = array($lawText['beschreibung'] => 'error');
            }
        }
        return $tempTexts;
    }

    private function saveInDatabase() {
        $currentIndex = 0;
        foreach ($this->agbConfig as $structure) {
            foreach ($this->agbTexts[$currentIndex] as $description => $text) {
                if ($text == 'error') {
                    if ($description == 'Batteriehinweise') {
                        $sql = "UPDATE " . $structure['mysqlTable'] . " SET status='0' WHERE pages_title='" . $structure['filter']['pages_title'] . "'";
                        $result = go_db_query($sql);
                        if (!$result) {
                            die('DB-ERROR');
                        }
                    }
                    continue;
                }
                if ($description == $structure['beschreibung']) {
                    $text = go_db_real_escape_string($text);
                    if ($structure['filter'] == null) {
                        $sql = "SELECT " . $structure['mysqlField'] . " FROM " . $structure['mysqlTable'];
                        if (go_db_num_rows(go_db_query($sql)) > 0) {
                            $sql = "UPDATE " . $structure['mysqlTable'] . " SET " . $structure['mysqlField'] . "='" . $text . "'";
                            $result = go_db_query($sql);
                            if (!$result) {
                                echo 'Datenbankfehler';
                                die();
                            }
                            $this->renderInfo($structure['beschreibung'] . ' wurde erfolgreich gespeichert');
                            break;
                        } else {
                            $sql = "INSERT INTO " . $structure['mysqlTable'] . "(id, Text, language_id) VALUES ('1','" . $text . "','5')";
                            $result = go_db_query($sql);
                            if (!$result) {
                                echo 'Datenbankfehler';
                                die();
                            }
                            break;
                            $this->renderInfo($structure['beschreibung'] . ' wurde erfolgreich gespeichert');
                        }
                    } else {
                        $filter = "WHERE ";
                        if (trim($text) == "error") {
                            if ($description == 'Batteriehinweise') {
                                $sql = "UPDATE " . $structure['mysqlTable'] . " SET status='0' WHERE pages_title='" . $structure['filter']['pages_title'] . "'";
                                $result = go_db_query($sql);
                                if (!$result) {
                                    die('DB-ERROR');
                                }
                            }
                            continue;
                        }
                        foreach ($structure['filter'] as $key => $value) {
                            $filter .= $key . "='" . $value . "' AND ";
                        }
                        $filter = substr($filter, 0, -4);
                        $sql = "SELECT " . $structure['mysqlField'] . " FROM " . $structure['mysqlTable'] . " " . $filter;
                        if (go_db_num_rows(go_db_query($sql)) > 0) {
                            $sql = "UPDATE " . $structure['mysqlTable'] . " SET " . $structure['mysqlField'] . "='" . $text . "' " . $filter;
                            $result = go_db_query($sql);
                            if (!$result) {
                                echo 'Datenbankfehler';
                                die();
                            }
                            $this->renderInfo($structure['beschreibung'] . ' wurde erfolgreich gespeichert');
                            break;
                        } else {
                            $values = $structure['filter'];
                            $status = 1;
                            $sql = "INSERT INTO " . $structure['mysqlTable'] . "(pages_title, pages_html_text, language_id, sort_order, status) VALUES ('" . $values['pages_title'] . "','" . $text . "', '" . $values['language_id'] . "','" . $values['sort_order'] . "','" . $status . "')";
                            $result = go_db_query($sql);
                            if (!$result) {
                                echo 'Datenbankfehler';
                                die();
                            }
                            $this->renderInfo($structure['beschreibung'] . ' wurde erfolgreich gespeichert');
                            break;
                        }
                    }
                    break;
                }
            }
            $currentIndex++;
        }
    }

    private function renderInfo($text) {
        echo $text . '<br/><br/>';
    }

    private function renderForm() {
        echo '<form action="" method="post">'
        . '<input type="submit" name="hbFormPost" value="Rechtstexte aktualisieren" />'
        . '<br/><br/>'
        . '</form>';
    }

}

?>