<?php
/**
 * Plugin Name: Uplink7 Visitor Counter
 * Description: Hochleistungs-Besucherzähler mit AJAX-Tracking, Dashboard-Statistiken und Shortcode [u7_visitors].
 * Version: 1.0
 * Author: uplink7
 * Text Domain: uplink7-visitor-counter
 */

if (!defined('ABSPATH')) exit;

// --- 1. FREEMIUS SDK INITIALISIERUNG ---

if ( ! function_exists( 'uvc_fs' ) ) {
    /**
     * Helferfunktion für den Zugriff auf das Freemius SDK.
     */
    function uvc_fs() {
        global $uvc_fs;

        if ( ! isset( $uvc_fs ) ) {
            $sdk_path = dirname( __FILE__ ) . '/lib/freemius/start.php';
            if ( file_exists( $sdk_path ) ) {
                require_once $sdk_path;
            } else {
                return false;
            }

            $uvc_fs = fs_dynamic_init( array(
                'id'                  => '27763',
                'slug'                => 'uplink7-visitor-counter',
                'type'                => 'plugin',
                'public_key'          => 'pk_7dc823d24edc6e5957d621ec1b46d',
                'is_premium'          => false,
                'premium_suffix'      => 'Premium',
                'has_premium_version' => true,
                'has_addons'          => false,
                'has_paid_plans'      => true,
                'is_org_compliant'    => true,
                'menu'                => array(
                    'slug'    => 'u7-visitor-counter',
                    'support' => false,
                ),
            ) );
        }

        return $uvc_fs;
    }

    uvc_fs();
    do_action( 'uvc_fs_loaded' );
}

// --- 2. INITIALISIERUNG BEI AKTIVIERUNG ---

register_activation_hook(__FILE__, 'u7_vc_activate');

function u7_vc_activate() {
    if (!get_option('u7_vc_settings')) {
        update_option('u7_vc_settings', ['online', 'today', 'yesterday', 'month', 'total', 'avg']);
    }
    
    if (!get_option('u7_vc_start_date')) {
        update_option('u7_vc_start_date', time());
    }

    if (!get_option('u7_vc_title')) {
        update_option('u7_vc_title', 'Besucher Statistik');
    }

    if (!get_option('u7_vc_labels')) {
        update_option('u7_vc_labels', [
            'online' => 'Live Online',
            'today' => 'Heute',
            'yesterday' => 'Gestern',
            'month' => 'Monat',
            'total' => 'Gesamt',
            'avg' => 'Ø / Tag'
        ]);
    }

    if (!get_option('u7_vc_styles')) {
        $default_styles = [
            'card_bg' => '#111111',
            'card_border' => '#333333',
            'online' => ['color' => '#57b26e', 'size' => '16', 'weight' => '700'],
            'today' => ['color' => '#ffffff', 'size' => '16', 'weight' => '700'],
            'yesterday' => ['color' => '#ffffff', 'size' => '16', 'weight' => '700'],
            'month' => ['color' => '#ffffff', 'size' => '16', 'weight' => '700'],
            'total' => ['color' => '#ffffff', 'size' => '16', 'weight' => '700'],
            'avg' => ['color' => '#57b26e', 'size' => '16', 'weight' => '700'],
        ];
        update_option('u7_vc_styles', $default_styles);
    }

    if (get_option('u7_count_total') === false) update_option('u7_count_total', 0);
    if (get_option('u7_vc_exclude_bots') === false) update_option('u7_vc_exclude_bots', '1');
    if (get_option('u7_vc_exclude_admins') === false) update_option('u7_vc_exclude_admins', '0');
}

// --- 3. TRACKING LOGIK & AJAX ---

add_action('wp_ajax_u7_track_visit', 'u7_vc_handle_tracking');
add_action('wp_ajax_nopriv_u7_track_visit', 'u7_vc_handle_tracking');

add_action('wp_ajax_u7_get_stats', 'u7_vc_get_stats_ajax');
add_action('wp_ajax_nopriv_u7_get_stats', 'u7_vc_get_stats_ajax');

function u7_vc_handle_tracking() {
    // Admin Ausschluss
    if (get_option('u7_vc_exclude_admins', '0') === '1' && current_user_can('manage_options')) {
        if (defined('DOING_AJAX')) wp_send_json_success(['status' => 'admin_ignored']);
        return;
    }

    // Bot Ausschluss
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    if (get_option('u7_vc_exclude_bots', '1') === '1' && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $ua)) {
        if (defined('DOING_AJAX')) wp_send_json_success(['status' => 'bot_ignored']);
        return;
    }

    $raw_ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    
    // IP Maskierung für Datenschutz
    if (filter_var($raw_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $ip_parts = explode('.', $raw_ip);
        $ip = $ip_parts[0].'.'.$ip_parts[1].'.'.$ip_parts[2].'.0';
    } else {
        $ip = preg_replace('/:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+$/i', ':0000:0000:0000:0000', $raw_ip);
    }

    $today = current_time('Y-m-d');
    $this_month = current_time('Y-m');
    $ip_hash = md5($ip);

    // Online Status (Transient)
    $online_visitors = get_transient('u7_vc_online') ?: [];
    $online_visitors[$ip_hash] = time();
    foreach ($online_visitors as $hash => $last_action) {
        if ($last_action < (time() - 300)) unset($online_visitors[$hash]);
    }
    set_transient('u7_vc_online', $online_visitors, 300);

    // Unique Visit pro Tag
    $session_key = 'u7_v_lock_' . md5($ip . $today);
    if (!get_transient($session_key)) {
        // Gesamt-Counter
        update_option('u7_count_total', (int)get_option('u7_count_total', 0) + 1);

        // Tages-Statistik
        $daily = get_option('u7_count_daily', []);
        $daily[$today] = ($daily[$today] ?? 0) + 1;
        if (count($daily) > 31) { // Halte max 31 Tage für den Durchschnitt
            ksort($daily);
            array_shift($daily);
        }
        update_option('u7_count_daily', $daily);

        // Monats-Statistik
        $month_stats = get_option('u7_count_monthly', ['month' => '', 'count' => 0]);
        if ($month_stats['month'] !== $this_month) {
            $month_stats = ['month' => $this_month, 'count' => 1];
        } else { $month_stats['count']++; }
        update_option('u7_count_monthly', $month_stats);

        set_transient($session_key, true, DAY_IN_SECONDS);
    }
    
    if (defined('DOING_AJAX') && DOING_AJAX) {
        wp_send_json_success(['status' => 'tracked']);
    }
}

function u7_vc_get_stats_ajax() {
    $stats = u7_vc_get_data();
    $stats['today_fmt'] = number_format($stats['today']);
    $stats['yesterday_fmt'] = number_format($stats['yesterday']);
    $stats['month_fmt'] = number_format($stats['month']);
    $stats['total_fmt'] = number_format($stats['total']);
    $stats['avg_fmt'] = number_format($stats['avg'], 1);
    wp_send_json_success($stats);
}

// --- 4. SCRIPTS & STYLES ---

add_action('wp_enqueue_scripts', 'u7_vc_enqueue_frontend_scripts');
function u7_vc_enqueue_frontend_scripts() {
    wp_register_script('u7-vc-tracker', false, [], null, true);
    wp_enqueue_script('u7-vc-tracker');

    $ajaxurl = admin_url('admin-ajax.php');
    $js_code = "
    (function() {
        var ajaxurl = '{$ajaxurl}';
        fetch(ajaxurl + '?action=u7_track_visit');
        setInterval(function() {
            fetch(ajaxurl + '?action=u7_get_stats').then(r => r.json()).then(d => {
                if(d.success) {
                    var s = d.data;
                    if(document.querySelector('.u7-vc-val-online')) document.querySelector('.u7-vc-val-online').innerText = s.online;
                    if(document.querySelector('.u7-vc-val-today')) document.querySelector('.u7-vc-val-today').innerText = s.today_fmt;
                    if(document.querySelector('.u7-vc-val-yesterday')) document.querySelector('.u7-vc-val-yesterday').innerText = s.yesterday_fmt;
                    if(document.querySelector('.u7-vc-val-month')) document.querySelector('.u7-vc-val-month').innerText = s.month_fmt;
                    if(document.querySelector('.u7-vc-val-total')) document.querySelector('.u7-vc-val-total').innerText = s.total_fmt;
                    if(document.querySelector('.u7-vc-val-avg')) document.querySelector('.u7-vc-val-avg').innerText = s.avg_fmt;
                }
            });
        }, 10000);
    })();
    ";
    wp_add_inline_script('u7-vc-tracker', $js_code);

    $styles = get_option('u7_vc_styles', []);
    $card_bg = esc_attr($styles['card_bg'] ?? '#111');
    $card_border = esc_attr($styles['card_border'] ?? '#333');
    $online_color = esc_attr($styles['online']['color'] ?? '#57b26e');
    $today_color = esc_attr($styles['today']['color'] ?? '#fff');
    $yesterday_color = esc_attr($styles['yesterday']['color'] ?? '#fff');
    $month_color = esc_attr($styles['month']['color'] ?? '#fff');
    $total_color = esc_attr($styles['total']['color'] ?? '#fff');
    $avg_color = esc_attr($styles['avg']['color'] ?? '#57b26e');

    $css_code = "
    .u7-vc-card { background: {$card_bg}; color: #fff; border-radius: 12px; border: 1px solid {$card_border}; padding: 15px; min-width: 250px; line-height: 1.6; display: inline-block; }
    .u7-vc-title-label { text-transform: uppercase; color: #57b26e; letter-spacing: 1px; font-weight: bold; display: block; margin-bottom: 5px; }
    .u7-vc-list { display: flex; flex-direction: column; }
    .u7-vc-row { display: flex; justify-content: space-between; align-items: center; }
    .u7-vc-label-text { font-weight: 500; }
    .u7-vc-val-online { color: {$online_color}; font-weight: bold; }
    .u7-vc-val-today { color: {$today_color}; }
    .u7-vc-val-yesterday { color: {$yesterday_color}; }
    .u7-vc-val-month { color: {$month_color}; }
    .u7-vc-val-total { color: {$total_color}; }
    .u7-vc-val-avg { color: {$avg_color}; }
    ";

    wp_register_style('u7-vc-frontend-style', false);
    wp_enqueue_style('u7-vc-frontend-style');
    wp_add_inline_style('u7-vc-frontend-style', $css_code);
}

// --- 5. ADMIN INTERFACE ---

add_action('admin_menu', 'u7_vc_add_menu');

function u7_vc_add_menu() {
    add_menu_page('U7 Counter', 'U7 Counter', 'manage_options', 'u7-visitor-counter', 'u7_vc_admin_page', 'dashicons-chart-area', 85);
}

function u7_vc_perform_reset() {
    update_option('u7_count_total', 0);
    update_option('u7_count_daily', []);
    update_option('u7_count_monthly', ['month' => current_time('Y-m'), 'count' => 0]);
    update_option('u7_vc_start_date', time());
}

function u7_vc_admin_page() {
    if (isset($_POST['u7_vc_save'])) {
        check_admin_referer('u7_vc_action', 'u7_vc_nonce');
        update_option('u7_vc_settings', $_POST['fields'] ?? []);
        update_option('u7_vc_styles', $_POST['styles'] ?? []);
        update_option('u7_vc_labels', $_POST['labels'] ?? []);
        update_option('u7_vc_title', sanitize_text_field($_POST['u7_widget_title']));
        update_option('u7_vc_exclude_bots', isset($_POST['u7_vc_exclude_bots']) ? '1' : '0');
        update_option('u7_vc_exclude_admins', isset($_POST['u7_vc_exclude_admins']) ? '1' : '0');
        echo '<div class="updated"><p>Einstellungen gespeichert!</p></div>';
    }

    if (isset($_POST['u7_vc_reset_stats'])) {
        check_admin_referer('u7_vc_action', 'u7_vc_nonce');
        u7_vc_perform_reset();
        echo '<div class="updated"><p>Statistiken zurückgesetzt!</p></div>';
    }

    $current_fields = get_option('u7_vc_settings', ['online', 'today', 'yesterday', 'month', 'total', 'avg']);
    $styles = get_option('u7_vc_styles', []);
    $labels = get_option('u7_vc_labels', []);
    $widget_title = get_option('u7_vc_title', 'Besucher Statistik');
    $stats = u7_vc_get_data();

    ?>
    <div class="wrap">
        <h1>Uplink7 Visitor Counter</h1>
        <?php
		$uvc_fs = uvc_fs();
		if ( $uvc_fs && ! $uvc_fs->is_premium() ) : ?>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 30px; margin-top:0; width: 100%;">
                <div style="background: linear-gradient(135deg, #6e8efb 0%, #a777e3 100%); color: white; padding: 25px; border-radius: 12px; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);">
                    <h3 style="margin-top:0; color:white;">Start Free Trial</h3>
                    <p>Test all professional features for 3 days for free. No obligation.</p>
                    <a href="<?php echo esc_url( $uvc_fs->get_trial_url() ); ?>" class="button button-large" style="background: white; color: #6e8efb; border: none; font-weight: bold;">Try for free</a>
                </div>
                <div style="background: #fff; border: 2px solid #fbbf24; padding: 25px; border-radius: 12px; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.05);">
                    <h3 style="margin-top:0;">Upgrade to Professional</h3>
                    <p>Unlock Statistics, more features and Priority Support.</p>
                    <a href="<?php echo esc_url( $uvc_fs->get_upgrade_url() ); ?>" class="button button-large button-primary" style="background: #fbbf24; color: #000; border: none; font-weight: bold;">Upgrade Now</a>
                </div>
            </div>
		<?php endif; ?>
        <div style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); margin-bottom: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="margin:0;">Aktuelle Zahlen</h2>
                <form method="post" onsubmit="return confirm('Wirklich alle Daten löschen?');">
                    <?php wp_nonce_field('u7_vc_action', 'u7_vc_nonce'); ?>
                    <input type="submit" name="u7_vc_reset_stats" class="button button-link-delete" value="Statistiken löschen" style="color:#d63638;">
                </form>
            </div>
            <div style="display: flex; gap: 40px; flex-wrap: wrap;">
                <div><strong style="font-size: 24px; color: #57b26e;"><?php echo esc_html((int)$stats['online']); ?></strong><br>Online</div>
                <div><strong style="font-size: 24px;"><?php echo esc_html(number_format($stats['today'])); ?></strong><br>Heute</div>
                <div><strong style="font-size: 24px;"><?php echo esc_html(number_format($stats['yesterday'])); ?></strong><br>Gestern</div>
                <div><strong style="font-size: 24px;"><?php echo esc_html(number_format($stats['month'])); ?></strong><br>Monat</div>
                <div><strong style="font-size: 24px;"><?php echo esc_html(number_format($stats['total'])); ?></strong><br>Gesamt</div>
                <div><strong style="font-size: 24px; color: #57b26e;"><?php echo esc_html(number_format($stats['avg'], 1)); ?></strong><br>Ø / Tag</div>
            </div>
        </div>

        <form method="post">
            <?php wp_nonce_field('u7_vc_action', 'u7_vc_nonce'); ?>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div class="card" style="max-width: 100%;">
                    <h3>Allgemeine Einstellungen</h3>
                    <p>Titel: <input type="text" name="u7_widget_title" value="<?php echo esc_attr($widget_title); ?>" class="large-text"></p>
                    <label><input type="checkbox" name="u7_vc_exclude_bots" value="1" <?php checked(get_option('u7_vc_exclude_bots', '1'), '1'); ?>> Bots ignorieren</label><br>
                    <label><input type="checkbox" name="u7_vc_exclude_admins" value="1" <?php checked(get_option('u7_vc_exclude_admins', '0'), '1'); ?>> Admins ausschließen</label>
                    <hr>
                    <h3>Beschriftungen (Labels)</h3>
                    <?php foreach(['online', 'today', 'yesterday', 'month', 'total', 'avg'] as $k): ?>
                        <p><?php echo esc_html(ucfirst($k)); ?>:<br> <input type="text" name="labels[<?php echo esc_attr($k); ?>]" value="<?php echo esc_attr($labels[$k] ?? ''); ?>" class="regular-text"></p>
                    <?php endforeach; ?>
                </div>
                <div class="card" style="max-width: 100%;">
                    <h3>Design & Sichtbarkeit</h3>
                    <?php foreach(['online', 'today', 'yesterday', 'month', 'total', 'avg'] as $f): ?>
                        <label><input type="checkbox" name="fields[]" value="<?php echo esc_attr($f); ?>" <?php checked(in_array($f, $current_fields)); ?>> <?php echo esc_html(ucfirst($f)); ?></label><br>
                    <?php endforeach; ?>
                    <hr>
                    <h3>Farben & Größen</h3>
                    <?php foreach(['online', 'today', 'yesterday', 'month', 'total', 'avg'] as $key): ?>
                        <div style="margin-bottom: 5px;">
                            <strong><?php echo esc_html(ucfirst($key)); ?>:</strong> 
                            <input type="color" name="styles[<?php echo esc_attr($key); ?>][color]" value="<?php echo esc_attr($styles[$key]['color'] ?? '#ffffff'); ?>"> 
                            <input type="number" name="styles[<?php echo esc_attr($key); ?>][size]" value="<?php echo esc_attr($styles[$key]['size'] ?? '16'); ?>" style="width: 50px;">px
                        </div>
                    <?php endforeach; ?>
                    <hr>
                    Hintergrund: <input type="color" name="styles[card_bg]" value="<?php echo esc_attr($styles['card_bg'] ?? '#111'); ?>"> 
                    Rahmen: <input type="color" name="styles[card_border]" value="<?php echo esc_attr($styles['card_border'] ?? '#333'); ?>">
                </div>
            </div>
            <p class="submit"><input type="submit" name="u7_vc_save" class="button button-primary" value="Einstellungen speichern"></p>
        </form>
    </div>
    <?php
}

// --- 6. DATEN HELPER ---

function u7_vc_get_data() {
    $online = count(get_transient('u7_vc_online') ?: []);
    $total = (int)get_option('u7_count_total', 0);
    $monthly = get_option('u7_count_monthly', ['count' => 0])['count'];
    $daily = get_option('u7_count_daily', []);
    
    $today_date = current_time('Y-m-d');
    $today = $daily[$today_date] ?? 0;

    $yesterday_date = date('Y-m-d', current_time('timestamp') - DAY_IN_SECONDS);
    $yesterday = $daily[$yesterday_date] ?? 0;
    
    $start_date = (int)get_option('u7_vc_start_date', time());
    $days_diff = ceil((time() - $start_date) / DAY_IN_SECONDS);
    if ($days_diff < 1) $days_diff = 1;
    
    return [
        'online' => $online, 
        'today' => $today, 
        'yesterday' => $yesterday, 
        'month' => $monthly, 
        'total' => $total, 
        'avg' => $total / $days_diff
    ];
}

// --- 7. SHORTCODE ---

add_shortcode('u7_visitors', 'u7_vc_shortcode_output');

function u7_vc_shortcode_output() {
    $stats = u7_vc_get_data();
    $visible = get_option('u7_vc_settings', ['online', 'today', 'yesterday', 'month', 'total', 'avg']);
    $labels = get_option('u7_vc_labels', []);
    $title = get_option('u7_vc_title', 'Besucher Statistik');
    
    ob_start();
    ?>
    <div class="u7-vc-card">
        <span class="u7-vc-title-label"><?php echo esc_html($title); ?></span>
        <div class="u7-vc-list">
            <?php 
            $keys = [
                'online' => 'Live Online',
                'today' => 'Heute',
                'yesterday' => 'Gestern',
                'month' => 'Monat',
                'total' => 'Gesamt',
                'avg' => 'Ø / Tag'
            ];
            foreach ($keys as $key => $default_label): 
                if (in_array($key, $visible)): ?>
                    <div class="u7-vc-row">
                        <span class="u7-vc-label-text"><?php echo esc_html($labels[$key] ?? $default_label); ?></span>
                        <span class="u7-vc-val-<?php echo $key; ?>">
                            <?php echo ($key === 'avg') ? number_format($stats[$key], 1) : number_format($stats[$key]); ?>
                        </span>
                    </div>
                <?php endif; 
            endforeach; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

// --- 8. WIDGET ---

add_action('widgets_init', function() { register_widget('U7_VC_Widget'); });
class U7_VC_Widget extends WP_Widget {
    public function __construct() { 
        parent::__construct('u7_vc_widget', 'U7 Visitor Counter', ['description' => 'Zeigt Besucherstatistiken an']); 
    }
    public function widget($args, $instance) { 
        echo $args['before_widget'] . do_shortcode('[u7_visitors]') . $args['after_widget']; 
    }
}