<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @package    SEOFlow
 * @subpackage SEOFlow/admin
 * @author Trinco Ingels <info@trincoingels.nl>
 */
class LinkNetwerk_Admin {

    private $plugin_name;
    private $version;
    private $dbTable;
    private $wpdb;
    private $uptimeRobotKeyword = "Uptime-Robot-Keyword";

    /**
     * Initialize the class and set its properties.
     *
     * @param      string    $plugin_name       The name of this plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct($plugin_name, $version) {
        global $wpdb;
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->wpdb = $wpdb;
        $this->dbTable = $wpdb->prefix . strtolower($this->plugin_name);
    }


    private function uploadImage($image, $imageName) {
        // Upload dir.
        $upload_dir = wp_upload_dir();
        $upload_path = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir['path']) . DIRECTORY_SEPARATOR;

        $imageInfo = explode(";base64,", $image);
        $imgExt = str_replace('data:', '', $imageInfo[0]);
        $image = str_replace(' ', '+', $imageInfo[1]);
        $filename = $imageName;

        $hashed_filename = md5($filename . microtime()) . '_' . $filename;

        $upload_file = file_put_contents($upload_path . $hashed_filename, base64_decode($image));


        $attachment = array(
            'post_mime_type' => $imgExt,
            'post_title' => sanitize_file_name(basename($hashed_filename)),
            'post_content' => '',
            'post_status' => 'inherit',
            'guid' => $upload_dir['url'] . '/' . basename($hashed_filename)
        );

        $attach_id = wp_insert_attachment($attachment, $upload_dir['path'] . '/' . $hashed_filename);

        include( ABSPATH . 'wp-admin/includes/image.php' );
        $attachment_meta = wp_generate_attachment_metadata($attach_id, $upload_dir['path'] . '/' . $hashed_filename);
        wp_update_attachment_metadata($attach_id, $attachment_meta);

        return $attach_id;
    }

    public function getVersion(){
        return ["version" => $this->version];
    }

    public function getLinks($atts) {
        global $post;
        if ($postId = filter_var($post->ID, FILTER_VALIDATE_INT)) {
            $order = $this->getSetting('linkOrder');

            $filterVisible = '';
            if(str_replace(".", "", $this->version) >= 124){
                $filterVisible = "and ((visibleTill is null OR visibleTill >= now()) and (visibleFrom is null or visibleFrom <= now()))";
            }

            if ($order == 'OldNew') {
                $sql = $this->wpdb->prepare("SELECT * FROM $this->dbTable where post_id = $postId $filterVisible  order by createdAt ASC");
            } else if ($order == 'Alphabet') {
                $sql = $this->wpdb->prepare("SELECT *, substring_index(SUBSTRING(link, LOCATE('>', link) +1, char_length(link)),'</a>', 1) `Title` FROM $this->dbTable where post_id = $postId $filterVisible   order by Title ASC");
            } else {
                $sql = $this->wpdb->prepare("SELECT * FROM $this->dbTable where post_id = $postId $filterVisible  order by createdAt DESC");
            }

            $results = $this->wpdb->get_results($sql, ARRAY_A);

            if ($results) {
                $return = '<p data="' . $this->uptimeRobotKeyword . '">';
                foreach ($results as $result) {
                    $return .= strip_tags($result['link'], "<a>") . '<br>';
                }
                $return .= "</p>";
                return $return;
            }
        }
    }

    public function addSetting($key, $value) {
        $db_table_name = $this->wpdb->prefix . strtolower($this->plugin_name) . '_instellingen';  // table name
        $setting = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM $db_table_name WHERE `key` = %s and `value` = %s", $key, $value));

        if ($setting && property_exists($setting, "id")) {
            $this->wpdb->update($db_table_name, array('key' => $key, 'value' => $value), array('id' => $setting->Id), array('%s', '%s'), array('%d')
            );
        } else {
            $this->wpdb->insert($db_table_name, array('key' => $key, 'value' => $value), array('%s', '%s')
            );
        }
    }

    public function getSetting($key) {
        $db_table_name = $this->wpdb->prefix . strtolower($this->plugin_name) . '_instellingen';  // table name
        $setting = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM $db_table_name WHERE `key` = %s", $key));

        return $setting->value;
    }

    public function getLink($id, $pageId, $websiteLinkId) {
        if ($id)
            return $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM $this->dbTable WHERE id = %d", $id));
        else
            return $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM $this->dbTable WHERE post_id = %d and website_link_id = %d", $pageId, $websiteLinkId));
    }

    public function saveLink($data) {
        $result = $this->wpdb->insert($this->dbTable, array('post_id' => $data['pageid'], 'link' => urldecode($data['link']), 'website_link_id' => $data['websiteLinkId'], 'visibleFrom' => isset($data['visibleFrom']) ? $data['visibleFrom'] : null, 'visibleTill' => isset($data['visibleTill']) ? $data['visibleTill'] : null), array('%d', '%s', '%d', '%s', '%s')
        );

        if ($result != 1)
            return new WP_Error(500, $this->wpdb->last_error);
        return $this->getLink(null, $data['pageid'], $data['websiteLinkId']);
    }

    public function updateLink($data) {
        $result = $this->wpdb->update($this->dbTable, array('link' => urldecode($data['link']), 'updatedAt' => current_time('mysql'), 'visibleFrom' => isset($data['visibleFrom']) ? $data['visibleFrom'] : null, 'visibleTill' => isset($data['visibleTill']) ? $data['visibleTill'] : null), array('post_id' => $data['pageid'], 'website_link_id' => $data['websiteLinkId']), array('%s', '%s', '%s', '%s'), array('%d', '%d')
        );

        if ($result != 1)
            return new WP_Error(500, $this->wpdb->last_error);
        return $this->getLink(null, $data['pageid'], $data['websiteLinkId']);
    }

    public function deleteLink($data) {
        $result = $this->wpdb->delete($this->dbTable, array('website_link_id' => $data['websiteLinkId']));

        if ($result != 1)
            return new WP_Error(500, $this->wpdb->last_error);
        return $this->getLink(null, $data['pageid'], $data['websiteLinkId']);
    }

    public function deleteAllLinks(){
        return $this->wpdb->query($this->wpdb->prepare("DELETE FROM $this->dbTable"));
    }

    public function saveBlog($data) {
        if ($data['featuredImage']) {
            $attach_id = $this->uploadImage($data['featuredImage'], $data['featuredImageName']);
        }

        $my_post = array(
            'post_title' => $data['title'],
            'post_name' => $data['slug'],
            'post_content' => $data['content'],
            'post_status' => 'publish',
            'post_author' => 1,
            'post_category' => explode(',', $data['categoryId']),
            'post_date' => $data['postDate']
        );

        $postId = wp_insert_post($my_post);
        if ($attach_id)
            set_post_thumbnail($postId, $attach_id);

        $seoDesc = $data['seoDescription'] ?? null;
        $seoTitle = $data['seoTitle'] ?? null;

        if (!empty($seoTitle) || !empty($seoDesc)) {
            if (in_array('wordpress-seo/wp-seo.php', apply_filters('active_plugins', get_option('active_plugins')))) { // YOAST
                update_post_meta($postId, '_yoast_wpseo_title', $seoTitle);
                update_post_meta($postId, '_yoast_wpseo_metadesc', $seoDesc);
            }
            if (in_array('seo-by-rank-math/rank-math.php', apply_filters('active_plugins', get_option('active_plugins')))) { // YOAST
                update_post_meta($postId, 'rank_math_title', $seoTitle);
                update_post_meta($postId, 'rank_math_description', $seoDesc);
            }
        }

        return array('pageId' => $postId, 'pageUrl' => get_permalink($postId));
    }

    public function updateBlog($data) {
        if ($data['featuredImage']) {
            $attach_id = $this->uploadImage($data['featuredImage'], $data['featuredImageName']);
        }

        $my_post = array(
            'ID' => $data['pageid'],
            'post_title' => $data['title'],
            'post_name' => $data['slug'],
            'post_content' => $data['content'],
            'post_status' => 'publish',
            'post_author' => 1,
            'post_category' => explode(',', $data['categoryId']),
            'post_date' => $data['postDate']
        );

        $postId = wp_update_post($my_post);
        if ($attach_id)
            set_post_thumbnail($postId, $attach_id);

        $seoDesc = $data['seoDescription'] ?? null;
        $seoTitle = $data['seoTitle'] ?? null;

        if (!empty($seoTitle) || !empty($seoDesc)) {
            if (in_array('wordpress-seo/wp-seo.php', apply_filters('active_plugins', get_option('active_plugins')))) { // YOAST
                update_post_meta($postId, '_yoast_wpseo_title', $seoTitle);
                update_post_meta($postId, '_yoast_wpseo_metadesc', $seoDesc);
            }
            if (in_array('seo-by-rank-math/rank-math.php', apply_filters('active_plugins', get_option('active_plugins')))) { // YOAST
                update_post_meta($postId, 'rank_math_title', $seoTitle);
                update_post_meta($postId, 'rank_math_description', $seoDesc);
            }
        }

        return array('pageId' => $postId, 'pageUrl' => get_permalink($postId));
    }

    public function deleteBlog($pageId) {
        wp_delete_post($pageId);
    }

    public function addCategory($category) {
        wp_insert_term($category, 'category');
    }

    public function exportOrder($order_id) {

        if (!get_option("lupsOnlineLinkNetwerkWebshopActive") && get_option("lupsOnlineLinkNetwerkWebshopActive") != 1) {
            return;
        }

        $order = new WC_Order($order_id);
        if ($order->get_status() == 'processing') {
            $lupsOnlineLinkNetwerkWebshopCategory = strtolower(get_option("lupsOnlineLinkNetwerkWebshopCategory")) ? : 'category';
            $lupsOnlineLinkNetwerkWebshopCategoryValue = strtolower(get_option("lupsOnlineLinkNetwerkWebshopCategoryValue")) ? : 'backlink';
            $lupsOnlineLinkNetwerkWebshopPartnerPageUrl = strtolower(get_option("lupsOnlineLinkNetwerkWebshopPartnerPageUrl")) ? : 'partnerpage url';


            $orderId = $order->get_id();

            $billingaddress = $order->get_address('billing');
            $shippingaddress = $order->get_address('shipping');

            $address = $billingaddress;
            if (!empty($shippingaddress["postcode"]) && !empty($shippingaddress["city"]) && !empty($shippingaddress["address_1"])) {
                $address = $shippingaddress;
            }

            $data = array();
            foreach ($order->get_items() as $item_id => $item) {
                $product = $item->get_product();

                $dataLine = array();
                $attributes = $product->get_attributes();
                foreach ($attributes as $attribute) {
                    $option = array_shift($attribute->get_options());
                    if (strtolower(wc_attribute_label($attribute->get_name())) == strtolower($lupsOnlineLinkNetwerkWebshopCategory)) {
                        $terms = wc_get_product_terms($product->id, $attribute->get_name(), array('fields' => 'names'));
                        $productContainsCategoryValue = false;
                        foreach ($terms as $term) {

                            if (!in_array(strtolower($term), explode(",", strtolower($lupsOnlineLinkNetwerkWebshopCategoryValue))))
                                continue;
                            $productContainsCategoryValue = true;
                        }
                        if (!$productContainsCategoryValue)
                            continue 2;
                    }
                    if (strtolower(wc_attribute_label($attribute->get_name())) == strtolower($lupsOnlineLinkNetwerkWebshopPartnerPageUrl)) {
                        $terms = wc_get_product_terms($product->id, $attribute->get_name(), array('fields' => 'names'));
                        $dataLine["PartnerPageUrl"] = array_shift(array_values($terms));
                    }
                }
                foreach (wc_get_order_item_meta($item_id, '_WCPA_order_meta_data') as $item_meta) {
                    if (strtolower($item_meta['label']) == 'anchor / keyword')
                        $dataLine["Title"] = $item_meta['value'];

                    if (strtolower($item_meta['label']) == 'url')
                        $dataLine["Url"] = $item_meta['value'];
                }

                array_push($data, $dataLine);
            }

            try {
                $api = new LinkNetwerk_Api();
                $api->apiCall(array('orderedLinks' => $data, 'customer' => array('firstname' => $address["first_name"], 'lastname' => $address["last_name"])), "POST");
            } catch (Exception $e) {
                if (get_option("lupsOnlineLinkNetwerkWebshopMailOnError")) {
                    $headers[] = 'Content-type: text/plain; charset=utf-8';
                    $headers[] = 'From:' . get_bloginfo('admin_email');

                    $reden = $e->getMessage();
                    if ($reden) {
                        $reden = json_decode($reden, true);
                        $reden = $reden["info"];
                    }
                    $html = "Hallo,\r\n";
                    $html .= sprintf("Order: %s is niet (geheel) verwerkt met de volgende reden: \r\n %s \r\n\n -- Dit is een automatische mail door de SEOFlow Linknetwerk plugin vanaf %s", $orderId, $reden, $_SERVER['SERVER_NAME']);
                    $to = get_option("lupsOnlineLinkNetwerkWebshopMailOnError");
                    if (!$to)
                        $to = sprintf("info@%s", $_SERVER['SERVER_NAME']);
                    wp_mail($to, sprintf("Het is niet gelukt om order %s automatisch door te zetten", $order_id), $html, $headers);
                }
            }
        }
    }

    /**
     * Add nav item to settings menu
     *
     */
    public function action_admin_menu() {
        add_options_page(esc_html__('SEO Flow', 'wp-crontrol'), esc_html__('SEO Flow', 'wp-crontrol'), 'manage_options', 'lupsOnlineLinkNetwerk_admin_options_page', [$this, 'admin_options_page']);
    }

    private function table_structure($table){
        $results = ($this->wpdb->get_results("DESCRIBE $table"));
        $output = "\r\nTable: $table \r\n";
        if($results){

            foreach($results[0] as $key => $value){ // Header only
                $output .= $key . "\t";
            }
            foreach($results as $result){
                $output .= "\r\n";
                foreach($result as $key => $value){
                    $output .= $value . "\t";
                }
            }
        }else{
            $output .= "\r\nTable not found / Result  empty";
        }
        return $output;
    }

    /**
     * Admin options page
     *
     */
    public function admin_options_page() {

        // check user capabilities
        if (!current_user_can('manage_options')) {
            return;
        }

        if ($_POST && isset($_POST["save_lupsOnlineLinkNetwerk_settings"])) {
            if (isset($_POST['lupsOnlineLinkNetwerkActive'])) {
                $lupsOnlineLinkNetwerkActive = wp_unslash(sanitize_text_field($_POST['lupsOnlineLinkNetwerkActive']));
            } else {
                $lupsOnlineLinkNetwerkActive = 0;
            }            
			
			if (isset($_POST['lupsOnlineLinkNetwerkAutoUpdate'])) {
                $lupsOnlineLinkNetwerkAutoUpdate = wp_unslash(sanitize_text_field($_POST['lupsOnlineLinkNetwerkAutoUpdate']));
            } else {
                $lupsOnlineLinkNetwerkAutoUpdate = 0;
            }

            $apiKey = sanitize_text_field($_POST['lupsOnlineLinkNetwerkApiKey']);
            if (!preg_match('/^[a-z0-9]+$/', $apiKey)) {
                LinkNetwerk_AdminNotice::displayError(__('Api Key Niet geldig'));
            } else {
                update_option('lupsOnlineLinkNetwerkActive', ($lupsOnlineLinkNetwerkActive === "on" ? 1 : 0));
                update_option('lupsOnlineLinkNetwerkAutoUpdate', ($lupsOnlineLinkNetwerkAutoUpdate === "on" ? 1 : 0));
                update_option('lupsOnlineLinkNetwerkApiKey', $apiKey);
                LinkNetwerk_AdminNotice::displaySuccess(__('Settings saved.'));
            }
            header("Refresh:0");
        } else if ($_POST && isset($_POST["save_lupsOnlineLinkNetwerk_webshop_settings"])) {
            if (isset($_POST['lupsOnlineLinkNetwerkWebshopActive'])) {
                $lupsOnlineLinkNetwerkWebshopActive = wp_unslash(sanitize_text_field($_POST['lupsOnlineLinkNetwerkWebshopActive']));
            } else {
                $lupsOnlineLinkNetwerkWebshopActive = 0;
            }

            $apiKey = sanitize_text_field($_POST['lupsOnlineLinkNetwerkWebshopLicenseKey']);
            $mailOnError = sanitize_text_field($_POST['lupsOnlineLinkNetwerkWebshopMailOnError']);
            $lupsOnlineLinkNetwerkWebshopPartnerPageUrl = sanitize_text_field($_POST['lupsOnlineLinkNetwerkWebshopPartnerPageUrl']);
            $lupsOnlineLinkNetwerkWebshopCategory = sanitize_text_field($_POST['lupsOnlineLinkNetwerkWebshopCategory']);
            if (!preg_match('/^[a-z0-9]+$/', $apiKey)) {
                LinkNetwerk_AdminNotice::displayError(__('License Key Niet geldig'));
            } else {
                update_option('lupsOnlineLinkNetwerkWebshopActive', ($lupsOnlineLinkNetwerkWebshopActive === "on" ? 1 : 0));
                update_option('lupsOnlineLinkNetwerkWebshopLicenseKey', $apiKey);
                update_option('lupsOnlineLinkNetwerkWebshopMailOnError', $mailOnError);
                update_option('lupsOnlineLinkNetwerkWebshopPartnerPageUrl', $lupsOnlineLinkNetwerkWebshopPartnerPageUrl);
                update_option('lupsOnlineLinkNetwerkWebshopCategory', $lupsOnlineLinkNetwerkWebshopCategory);
                LinkNetwerk_AdminNotice::displaySuccess(__('Settings saved.'));
            }
            header('Location: ' . $_SERVER['HTTP_REFERER']);
        }

        $lupsOnlineLinkNetwerkActive = get_option("lupsOnlineLinkNetwerkActive");
        $lupsOnlineLinkNetwerkAutoUpdate = get_option("lupsOnlineLinkNetwerkAutoUpdate");
		if(!$lupsOnlineLinkNetwerkAutoUpdate) $lupsOnlineLinkNetwerkAutoUpdate = in_array('lupsonline-link-netwerk/linknetwerk.php', array_values(get_option( 'auto_update_plugins' ) ?: [] ) );
        $lupsOnlineLinkNetwerkApiKey = get_option("lupsOnlineLinkNetwerkApiKey");
        $lupsOnlineLinkNetwerkWebshopActive = get_option("lupsOnlineLinkNetwerkWebshopActive");
        $lupsOnlineLinkNetwerkWebshopLicenseKey = get_option("lupsOnlineLinkNetwerkWebshopLicenseKey");
        $lupsOnlineLinkNetwerkWebshopMailOnError = get_option("lupsOnlineLinkNetwerkWebshopMailOnError");
        $lupsOnlineLinkNetwerkWebshopPartnerPageUrl = get_option("lupsOnlineLinkNetwerkWebshopPartnerPageUrl");
        $lupsOnlineLinkNetwerkWebshopCategory = get_option("lupsOnlineLinkNetwerkWebshopCategory");
        ?>
        <!-- Create a header in the default WordPress 'wrap' container -->
        <div class="wrap">

            <div id="icon-themes" class="icon32"></div>
            <h2><?php esc_html_e('SEO Flow', 'wp-crontrol'); ?></h2>
            <?php settings_errors(); ?>

            <?php
            if (isset($_GET['tab'])) {
                $active_tab = sanitize_text_field($_GET['tab']);
            } else {
                $active_tab = "settings";
            }
            ?>

            <h2 class="nav-tab-wrapper">
                <a href="?page=lupsOnlineLinkNetwerk_admin_options_page&tab=settings" class="nav-tab <?php echo $active_tab == 'settings' ? 'nav-tab-active' : ''; ?>">Links</a>
                <a href="?page=lupsOnlineLinkNetwerk_admin_options_page&tab=webshop" class="nav-tab <?php echo $active_tab == 'webshop' ? 'nav-tab-active' : ''; ?>">Webshop</a>
                <a href="?page=lupsOnlineLinkNetwerk_admin_options_page&tab=status" class="nav-tab <?php echo $active_tab == 'status' ? 'nav-tab-active' : ''; ?>">Status</a>
            </h2>

            <div class="tab-content">
                <?php
                switch ($active_tab) :
                    case 'settings':
                        ?>
                        <div class="wrap">
                            <div class="wrap narrow">
                                <form method="post" action="options-general.php?page=lupsOnlineLinkNetwerk_admin_options_page">
                                    <table class="form-table">
                                        <tbody>
                                        <tr>
                                            <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkVersion"><?php esc_html_e('Versie', 'wp-crontrol'); ?></label></th>
                                            <td>
                                                <label for="lupsOnlineLinkNetwerkVersion"><?php esc_html_e($this->version, 'wp-crontrol'); ?></label>
                                            </td>
                                        </tr>
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkAutoUpdate"><?php esc_html_e('Auto Update', 'wp-crontrol'); ?></label></th>
                                                <td>
                                                    <label for="lupsOnlineLinkNetwerkAutoUpdate"><input name="lupsOnlineLinkNetwerkAutoUpdate" type="checkbox" id="lupsOnlineLinkNetwerkAutoUpdate" <?php print($lupsOnlineLinkNetwerkAutoUpdate ? "checked" : ""); ?>>Actief</label>
                                                    <p class="description"><small><?php esc_html_e('We raden je aan automatische updates aan te zetten zodat essentiële beveiligingsfixes en nieuwe functies worden geïnstalleerd zodra deze beschikbaar zijn.', 'wp-crontrol'); ?></small></p>
                                                </td>
                                            </tr>										
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkActive"><?php esc_html_e('Actief', 'wp-crontrol'); ?></label></th>
                                                <td>
                                                    <label for="lupsOnlineLinkNetwerkActive"><input name="lupsOnlineLinkNetwerkActive" type="checkbox" id="lupsOnlineLinkNetwerkActive" <?php print($lupsOnlineLinkNetwerkActive ? "checked" : ""); ?>>Actief</label>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkWebshopUrl"><?php esc_html_e('Domein/Url', 'wp-crontrol'); ?></label></th>
                                                <td>

                                                    <input type="text" class="regular-text" value="<?php print(sanitize_text_field(get_site_url())); ?>" id="lupsOnlineLinkNetwerkWebshopUrl" name="lupsOnlineLinkNetwerkWebshopUrl" readonly/>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkApiKey"><?php esc_html_e('Api Key', 'wp-crontrol'); ?></label></th>
                                                <td>
                                                    <input type="text" class="regular-text" value="<?php print(sanitize_text_field($lupsOnlineLinkNetwerkApiKey)); ?>" id="lupsOnlineLinkNetwerkApiKey" name="lupsOnlineLinkNetwerkApiKey" />
                                                </td>
                                            </tr>
                                        </tbody></table>
                                    <p class="submit"><input id="lupsOnlineLinkNetwerk-submit" type="submit" class="button button-primary" value="<?php esc_attr_e('Opslaan', 'wp-crontrol'); ?>" name="save_lupsOnlineLinkNetwerk_settings"/></p>
                                    <?php wp_nonce_field('save_lupsOnlineLinkNetwerk_settings'); ?>
                                </form>
                            </div>
                        </div>
                        <?php
                        break;
                    case 'webshop':
                        ?>
                        <div class="wrap">
                            <div class="wrap narrow">
                                <form method="post" action="options-general.php?page=lupsOnlineLinkNetwerk_admin_options_page">
                                    <table class="form-table">
                                        <tbody>
                                        <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkWebshopActive"><?php esc_html_e('Actief', 'wp-crontrol'); ?></label></th>
                                                <td>
                                                    <label for="lupsOnlineLinkNetwerkWebshopActive"><input name="lupsOnlineLinkNetwerkWebshopActive" type="checkbox" id="lupsOnlineLinkNetwerkWebshopActive" <?php print($lupsOnlineLinkNetwerkWebshopActive ? "checked" : ""); ?>>Actief</label>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkWebshopUrl"><?php esc_html_e('Domein/Url', 'wp-crontrol'); ?></label></th>
                                                <td>

                                                    <input type="text" class="regular-text" value="<?php print(sanitize_text_field(get_site_url())); ?>" id="lupsOnlineLinkNetwerkWebshopUrl" name="lupsOnlineLinkNetwerkWebshopUrl" readonly/>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkWebshopLicenseKey"><?php esc_html_e('License Key', 'wp-crontrol'); ?></label></th>
                                                <td>
                                                    <input type="text" class="regular-text" value="<?php print(sanitize_text_field($lupsOnlineLinkNetwerkWebshopLicenseKey)); ?>" id="lupsOnlineLinkNetwerkWebshopLicenseKey" name="lupsOnlineLinkNetwerkWebshopLicenseKey" />
                                                </td>
                                            </tr>
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkWebshopPartnerPageUrl"><?php esc_html_e('Eigenschap Partner Page Url ', 'wp-crontrol'); ?></label></th>
                                                <td>
                                                    <input type="text" class="regular-text" value="<?php print(sanitize_text_field($lupsOnlineLinkNetwerkWebshopPartnerPageUrl)); ?>" id="lupsOnlineLinkNetwerkWebshopPartnerPageUrl" name="lupsOnlineLinkNetwerkWebshopPartnerPageUrl" />
                                                    <p class="description"><small><?php esc_html_e('Vul de naam van de eigenschap in die gebruikt wordt om de Partner Page Url te definiëren', 'wp-crontrol'); ?></small></p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkWebshopCategory"><?php esc_html_e('Eigenschap Categorie ', 'wp-crontrol'); ?></label></th>
                                                <td>
                                                    <input type="text" class="regular-text" value="<?php print(sanitize_text_field($lupsOnlineLinkNetwerkWebshopCategory)); ?>" id="lupsOnlineLinkNetwerkWebshopCategory" name="lupsOnlineLinkNetwerkWebshopCategory" />
                                                    <p class="description"><small><?php esc_html_e('Vul de naam van de eigenschap in voor de producten die verwerkt mogen worden.', 'wp-crontrol'); ?></small></p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th valign="top" scope="row"><label for="lupsOnlineLinkNetwerkWebshopMailOnError"><?php esc_html_e('Mailadres bij errors', 'wp-crontrol'); ?></label></th>
                                                <td>
                                                    <input type="text" class="regular-text" value="<?php print(sanitize_text_field($lupsOnlineLinkNetwerkWebshopMailOnError)); ?>" id="lupsOnlineLinkNetwerkWebshopMailOnError" name="lupsOnlineLinkNetwerkWebshopMailOnError" />
                                                </td>
                                            </tr>
                                        </tbody></table>
                                    <p class="submit"><input id="lupsOnlineLinkNetwerk-submit" type="submit" class="button button-primary" value="<?php esc_attr_e('Opslaan', 'wp-crontrol'); ?>" name="save_lupsOnlineLinkNetwerk_webshop_settings"/></p>
                                        <?php wp_nonce_field('save_lupsOnlineLinkNetwerk_webshop_settings'); ?>
                                </form>
                            </div>
                        </div>
                        <?php
                        break;
                    case 'status':
                        global $wp_version;

                        $report = "";
                        $report .= "\r\nSiteadres: " . get_site_url();
                        $report .= "\r\nWordpress version: $wp_version";
                        $report .= "\r\nPlugin version: "  . $this->version;
                        $report .= "\r\nPhp version: " . phpversion();
                        $report .= "\r\nAPI Key: " . $lupsOnlineLinkNetwerkApiKey;

                        $report .= "\n";
                        $report .= "\r\n#### TABLE STRUCTURES ####";
                        $report .= "\n";

                        $report .= self::table_structure($this->wpdb->prefix . "lupsonlinelinknetwerk");
                        $report .= "\n";
                        $report .= self::table_structure($this->wpdb->prefix . "lupsonlinelinknetwerk_instellingen");

                        ?>
                    <style>
                        #debug-report{
                            margin: 10px 0;
                            padding: 0;
                            position: relative;
                        }
                        #debug-report textarea {
                            font-family: monospace;
                            width: 100%;
                            margin: 0;
                            height: 300px;
                            padding: 20px;
                            border-radius: 0;
                            resize: none;
                            font-size: 12px;
                            line-height: 20px;
                            outline: 0;
                            background-color: #f0f0f1;
                        }
                        #debug-report .button-tooltip-container {
                            display: flex;
                            align-items: center;
                            margin-top: 16px;
                            min-height: 30px;

                        }
                        #debug-report .custom-tooltip {
                            display: none;
                            margin-left: 5%;
                            padding: 5px 12px;
                            background-color: #000000df;
                            border-radius: 4px;
                            color: #fff;
                        }
                    </style>

                        <div class="wrap">
                            <div class="wrap narrow">
                                <p>Kopieer en plak deze informatie alleen als je contact op neemt met ondersteuning</p>
                                <button class="button button-secondary d-block" id="show-debug-report">Ontvang systeemrapport</button>
                                <div id="debug-report" style="display: none;">
                                    <textarea readonly="readonly"><?php echo($report); ?></textarea>
                                    <div class="button-tooltip-container">
                                        <button id="copy-for-support" class="button-primary" href="#" data-tip="Gekopieerd!">Kopieer voor ondersteuning</button>
                                        <span class="custom-tooltip">copied!</span>
                                        </span>
                                    </p>
                                </div>
                            </div>
                        </div>
                        <script type="text/javascript">
                            jQuery(document).ready(function ($) {
                                $("#copy-for-support").click(function () {
                                    $("#debug-report > textarea").select();
                                    $("#debug-report .custom-tooltip").css({'display':"inline"});
                                    document.execCommand('copy');
                                    setTimeout( function() {
                                        $("#debug-report .custom-tooltip").css({'display':"none"});
                                    }, 1000);
                                });
                                $("#show-debug-report").click(function () {
                                    $("#debug-report").show();
                                });
                            });
                        </script>
                    <?php
                        break;
                endswitch;
                ?>
            </div>

        </div><!-- /.wrap -->

        <?php
    }

}
