<?php

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

define('WNC_ANALYTICS_DB_VERSION', '2');

function wnc_analytics_table_name() {
    global $wpdb;

    return $wpdb->prefix . 'wnc_clicks';
}

function wnc_create_analytics_table() {
    global $wpdb;

    $table = wnc_analytics_table_name();
    $charset = $wpdb->get_charset_collate();

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    dbDelta("CREATE TABLE {$table} (
        id bigint unsigned NOT NULL AUTO_INCREMENT,
        created_at datetime NOT NULL,
        page_url text NOT NULL,
        post_id bigint unsigned NOT NULL DEFAULT 0,
        event_type varchar(32) NOT NULL DEFAULT 'button_click',
        device varchar(16) NOT NULL DEFAULT 'unknown',
        button_mode varchar(16) NOT NULL DEFAULT 'url',
        user_agent text,
        PRIMARY KEY  (id),
        KEY created_at (created_at),
        KEY post_id (post_id),
        KEY event_type (event_type)
    ) {$charset};");

    $wpdb->query("UPDATE {$table} SET user_agent = NULL WHERE user_agent IS NOT NULL");

    update_option('wnc_analytics_db_version', WNC_ANALYTICS_DB_VERSION, false);
}

register_activation_hook(
    dirname(__DIR__) . '/where-next-connector.php',
    'wnc_create_analytics_table'
);

add_action('plugins_loaded', function () {
    if (get_option('wnc_analytics_db_version') !== WNC_ANALYTICS_DB_VERSION) {
        wnc_create_analytics_table();
    }
});

function wnc_analytics_enabled() {
    $options = wnc_get_options();

    return !empty($options['pro_enable_analytics'])
        && function_exists('wnc_is_pro_active')
        && wnc_is_pro_active();
}

add_action('wp_enqueue_scripts', function () {
    if (!wnc_analytics_enabled()) {
        return;
    }

    wp_enqueue_script(
        'wnc-analytics',
        WNC_URL . 'assets/analytics.js',
        [],
        WNC_VERSION,
        true
    );

    wp_localize_script('wnc-analytics', 'wncAnalytics', [
        'endpoint' => admin_url('admin-ajax.php'),
        'action' => 'wnc_track_click',
    ]);
});

function wnc_track_click() {
    if (!wnc_analytics_enabled()) {
        wp_send_json_error(['message' => 'Analytics disabled.'], 403);
    }

    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    $button_mode = isset($_POST['button_mode']) ? sanitize_key(wp_unslash($_POST['button_mode'])) : 'url';

    if (!$post_id || !get_post($post_id)) {
        wp_send_json_error(['message' => 'Invalid analytics event.'], 400);
    }

    if (function_exists('wnc_is_enabled_post_type') && !wnc_is_enabled_post_type(get_post_type($post_id))) {
        wp_send_json_error(['message' => 'Post type not enabled.'], 400);
    }

    if (!in_array($button_mode, ['url', 'full'], true)) {
        $button_mode = 'url';
    }

    global $wpdb;

    $inserted = $wpdb->insert(
        wnc_analytics_table_name(),
        [
            'created_at' => current_time('mysql'),
            'page_url' => get_permalink($post_id),
            'post_id' => $post_id,
            'event_type' => 'button_click',
            'device' => wp_is_mobile() ? 'mobile' : 'desktop',
            'button_mode' => $button_mode,
        ],
        ['%s', '%s', '%d', '%s', '%s', '%s']
    );

    if (!$inserted) {
        wp_send_json_error(['message' => 'Could not record event.'], 500);
    }

    wp_send_json_success();
}

add_action('wp_ajax_wnc_track_click', 'wnc_track_click');
add_action('wp_ajax_nopriv_wnc_track_click', 'wnc_track_click');

add_action('init', function () {
    if (wnc_analytics_enabled()) {
        if (!wp_next_scheduled('wnc_cleanup_analytics')) {
            wp_schedule_event(time() + HOUR_IN_SECONDS, 'daily', 'wnc_cleanup_analytics');
        }
    } else {
        wp_clear_scheduled_hook('wnc_cleanup_analytics');
    }
});

add_action('wnc_cleanup_analytics', function () {
    $options = wnc_get_options();
    $retention_days = absint($options['pro_analytics_retention_days'] ?? 365);

    if ($retention_days <= 0) {
        return;
    }

    $cutoff = current_datetime()
        ->modify('-' . $retention_days . ' days')
        ->format('Y-m-d H:i:s');

    global $wpdb;

    $wpdb->query(
        $wpdb->prepare(
            'DELETE FROM ' . wnc_analytics_table_name() . ' WHERE created_at < %s',
            $cutoff
        )
    );
});

register_deactivation_hook(dirname(__DIR__) . '/where-next-connector.php', function () {
    wp_clear_scheduled_hook('wnc_cleanup_analytics');
});
