<?php
if (!defined("ABSPATH")) {
    exit();
}

/*
Plugin Name: LeadLab by wiredminds
Description: Wiredminds LeadLab Tracking-Code integration for WordPress
Plugin URI: https://github.com/wiredminds-gmbh/wordpress
Version: 1.3
Author: wiredminds GmbH
Author URI: http://www.wiredminds.de
Requires PHP: 7.4
Requires at least: 4.8.1
*/

if (version_compare(phpversion(), "7.4", "<")) {
    wp_die(
        __(
            "This plugin requires a more recent version of PHP. Please contact your hosting provider to upgrade.",
            "wiredminds-leadlab"
        ),
        __("PHP Version Requirements", "wiredminds-leadlab"),
        ["response" => 503]
    );
}

/**
 * Add HTTP security headers for admin page
 */
function wp_wm_add_security_headers()
{
    if (
        is_admin() &&
        isset($_GET["page"]) &&
        strpos($_GET["page"], "leadlab.php") !== false
    ) {
        header("X-Frame-Options: DENY");
        header("X-Content-Type-Options: nosniff");
        header("X-XSS-Protection: 1; mode=block");
        header("Referrer-Policy: strict-origin-when-cross-origin");
        header(
            "Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"
        );
    }
}

/**
 * Add menu link
 */
function wp_wm_add_links()
{
    if (function_exists("add_options_page")) {
        add_options_page(
            "LeadLab by wiredminds",
            "LeadLab by wiredminds",
            "manage_options",
            __FILE__,
            "wp_wm_admin"
        );
    }
}

/**
 * Create admin page
 */
function wp_wm_admin()
{
    if (!current_user_can("manage_options")) {
        wp_die(
            __(
                "You do not have sufficient permissions to access this page.",
                "wiredminds-leadlab"
            )
        );
    }

    $error_message = "";
    $success_message = "";

    if (!empty($_POST["action"])) {
        if (
            !isset($_POST["_wpnonce"]) ||
            !wp_verify_nonce($_POST["_wpnonce"], "wp_wm_save_settings")
        ) {
            error_log(
                "LeadLab Plugin: CSRF attempt detected by user ID: " .
                    get_current_user_id()
            );

            echo '<div class="notice notice-error"><p>' .
                __(
                    "Sicherheitsüberprüfung fehlgeschlagen. Bitte laden Sie die Seite neu und versuchen Sie es erneut.",
                    "wiredminds-leadlab"
                ) .
                "</p></div>";
            return;
        }

        if ($_POST["action"] == "save") {
            $custnum = sanitize_text_field($_POST["wp_wm_custnum"]);

            // Additional validation: exactly 16 alphanumeric characters (hash format)
            if (preg_match('/^[a-zA-Z0-9]{16}$/', $custnum)) {
                update_option("wp_wm_custnum", $custnum);
                $success_message = __(
                    "Einstellungen erfolgreich gespeichert.",
                    "wiredminds-leadlab"
                );
            } else {
                $error_message = __(
                    "Ungültiges Kundennummer-Format. Es müssen genau 16 alphanumerische Zeichen sein (A-Z, a-z, 0-9).",
                    "wiredminds-leadlab"
                );
            }

            $consent_value =
                isset($_POST["wp_wm_consent"]) && $_POST["wp_wm_consent"] == "1"
                    ? 1
                    : 0;
            update_option("wp_wm_consent", $consent_value);
        }
    }

    $wp_wm_custnum = sanitize_text_field(get_option("wp_wm_custnum", ""));
    $wp_wm_consent = (int) get_option("wp_wm_consent", 0);
    ?>

    <div class="wrap">
        <h2><?php _e(
            "Wiredminds LeadLab Tracking-Code Konfiguration",
            "wiredminds-leadlab"
        ); ?></h2>

        <?php
        if (!empty($error_message)) {
            echo '<div class="notice notice-error"><p>' .
                esc_html($error_message) .
                "</p></div>";
        }
        if (!empty($success_message)) {
            echo '<div class="notice notice-success"><p>' .
                esc_html($success_message) .
                "</p></div>";
        }
        ?>

        <div class="postbox-container" style="width: 600px;">
            <div class="metabox-holder">
                <div class="meta-box-sortables">
                    <form action="" method="post">
                        <div class="postbox">
                            <h3 class="hndle"><span>Konfiguration</span></h3>
                            <div class="inside">
                                <p>
                                    <label
                                        style="width:210px;text-align:right; float:left; display:block; line-height: 30px;"
                                        for="wp_wm_custnum">Kundennummer:</label>&nbsp;
                                    <input name="wp_wm_custnum" id="wp_wm_custnum" type="text" value="<?php echo esc_attr(
                                        $wp_wm_custnum
                                    ); ?>" size="40" maxlength="16" pattern="[a-zA-Z0-9]{16}" title="Geben Sie genau 16 alphanumerische Zeichen ein (A-Z, a-z, 0-9)"/>
                                </p>


								<p>
								 <label
                                        style="width:210px;text-align:right; float:left; display:block; line-height: 30px;"
                                        for="wp_wm_consent">Tracking-Cookie Erweiterung:</label>&nbsp;
									<input name="wp_wm_consent" id="wp_wm_consent" type="checkbox" value=1 <?php echo $wp_wm_consent
             ? "checked"
             : ""; ?> size="40"/>
								</p>

                            </div>
                        </div>
                        <div style="text-align:right">
                            <input type="hidden" name="action" value="save"/>
                            <?php wp_nonce_field(
                                "wp_wm_save_settings",
                                "_wpnonce"
                            ); ?>
                            <input type="submit" class="button-primary" name="submit" value="<?php _e(
                                "Speichern",
                                "wiredminds-leadlab"
                            ); ?> &raquo;"/>
                        </div>
                    </form>
                    <hr/>
                </div>
            </div>
        </div>
    </div>
    <?php
}

/**
 * Output pixelcode
 */
function wp_wm_pixel()
{
    $wp_wm_custnum = sanitize_text_field(get_option("wp_wm_custnum"));
    $wp_wm_consent = (int) get_option("wp_wm_consent");

    if (!empty($wp_wm_custnum)) { ?>

        <!-- wiredminds leadlab tracking V7 START -->
 	<script type="text/javascript">
        (function(d,s){var l=d.createElement(s),e=d.getElementsByTagName(s)[0];
		l.async=true;l.type='text/javascript';
		l.src='https://c.leadlab.click/<?php echo esc_js($wp_wm_custnum); ?>.js';
		e.parentNode.insertBefore(l,e);})(document,'script');
	</script>


        <!-- wiredminds leadlab tracking V7 END -->
        <?php }
    if (!empty($wp_wm_consent)) { ?>

        <!-- wiredminds leadlab consent START -->
 	<script type="text/javascript">
    (function(d,s){var l=d.createElement(s),e=d.getElementsByTagName(s)[0];
    l.async=true;l.type='text/javascript';
    l.src='https://c.leadlab.click/consent.min.js';
    e.parentNode.insertBefore(l,e);})(document,'script');
</script>


        <!-- wiredminds leadlab consent V7 END -->
        <?php }
}

add_action("admin_menu", "wp_wm_add_links");
add_action("wp_footer", "wp_wm_pixel");
add_action("send_headers", "wp_wm_add_security_headers");
