<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Runs on plugin activation.
 * Creates all database tables using WP's dbDelta().
 */
class VLENS_Activator {

    public static function activate() {
        self::create_tables();
        self::set_default_options();
        flush_rewrite_rules();
    }

    /**
     * Create plugin tables.
     * Uses the same schema from the SQL file, adapted for wpdb prefix.
     */
    private static function create_tables() {
        global $wpdb;
        $charset = $wpdb->get_charset_collate();
        $p       = $wpdb->prefix . VLENS_TABLE_PREFIX;

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

        // A1. vs_visitors
        dbDelta( "CREATE TABLE {$p}visitors (
            id              BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            date            DATE            NOT NULL,
            ip              VARCHAR(64)     NOT NULL DEFAULT '',
            ip_raw          VARCHAR(45)     NOT NULL DEFAULT '',
            referred        TEXT,
            agent           VARCHAR(500)    NOT NULL DEFAULT '',
            platform        VARCHAR(100)    NOT NULL DEFAULT '',
            browser         VARCHAR(100)    NOT NULL DEFAULT '',
            browser_version VARCHAR(50)     NOT NULL DEFAULT '',
            device_type     VARCHAR(20)     NOT NULL DEFAULT 'unknown',
            country_code    CHAR(2)         NOT NULL DEFAULT '--',
            country_name    VARCHAR(100)    NOT NULL DEFAULT '',
            city            VARCHAR(100)    NOT NULL DEFAULT '',
            region          VARCHAR(100)    NOT NULL DEFAULT '',
            latitude        DECIMAL(9,6)    DEFAULT NULL,
            longitude       DECIMAL(9,6)    DEFAULT NULL,
            language        VARCHAR(10)     NOT NULL DEFAULT '',
            timezone        VARCHAR(60)     NOT NULL DEFAULT '',
            screen_width    SMALLINT UNSIGNED DEFAULT NULL,
            screen_height   SMALLINT UNSIGNED DEFAULT NULL,
            is_bot          TINYINT(1)      NOT NULL DEFAULT 0,
            wp_user_id      BIGINT UNSIGNED DEFAULT NULL,
            cookie_id       VARCHAR(64)     DEFAULT NULL,
            created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY uq_visitor_day (ip, date),
            KEY idx_date (date),
            KEY idx_ip_raw (ip_raw),
            KEY idx_cookie (cookie_id)
        ) $charset;" );

        // A2. vs_visits
        dbDelta( "CREATE TABLE {$p}visits (
            id             BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            visitor_id     BIGINT UNSIGNED NOT NULL,
            date           DATE            NOT NULL,
            page_uri       VARCHAR(2000)   NOT NULL DEFAULT '/',
            page_title     VARCHAR(500)    NOT NULL DEFAULT '',
            referrer       TEXT,
            referrer_host  VARCHAR(255)    NOT NULL DEFAULT '',
            referrer_type  VARCHAR(20)     NOT NULL DEFAULT 'direct',
            search_engine  VARCHAR(50)     NOT NULL DEFAULT '',
            search_query   VARCHAR(500)    NOT NULL DEFAULT '',
            utm_source     VARCHAR(200)    NOT NULL DEFAULT '',
            utm_medium     VARCHAR(200)    NOT NULL DEFAULT '',
            utm_campaign   VARCHAR(200)    NOT NULL DEFAULT '',
            utm_term       VARCHAR(200)    NOT NULL DEFAULT '',
            utm_content    VARCHAR(200)    NOT NULL DEFAULT '',
            load_time_ms   INT UNSIGNED    DEFAULT NULL,
            created_at     DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_visitor (visitor_id),
            KEY idx_date (date)
        ) $charset;" );

        // A3. vs_daily_summary
        dbDelta( "CREATE TABLE {$p}daily_summary (
            id           INT UNSIGNED NOT NULL AUTO_INCREMENT,
            date         DATE         NOT NULL,
            visitors     INT UNSIGNED NOT NULL DEFAULT 0,
            visits       INT UNSIGNED NOT NULL DEFAULT 0,
            page_views   INT UNSIGNED NOT NULL DEFAULT 0,
            PRIMARY KEY (id),
            UNIQUE KEY uq_date (date)
        ) $charset;" );

        // A4. vs_countries
        dbDelta( "CREATE TABLE {$p}countries (
            id           INT UNSIGNED NOT NULL AUTO_INCREMENT,
            date         DATE         NOT NULL,
            country_code CHAR(2)      NOT NULL DEFAULT '--',
            country_name VARCHAR(100) NOT NULL DEFAULT '',
            visitors     INT UNSIGNED NOT NULL DEFAULT 0,
            PRIMARY KEY (id),
            UNIQUE KEY uq_country_date (country_code, date)
        ) $charset;" );

        // A5. vs_browsers
        dbDelta( "CREATE TABLE {$p}browsers (
            id       INT UNSIGNED NOT NULL AUTO_INCREMENT,
            date     DATE         NOT NULL,
            browser  VARCHAR(100) NOT NULL DEFAULT '',
            version  VARCHAR(50)  NOT NULL DEFAULT '',
            visitors INT UNSIGNED NOT NULL DEFAULT 0,
            PRIMARY KEY (id),
            UNIQUE KEY uq_browser_date (browser, version, date)
        ) $charset;" );

        // A6. vs_platforms
        dbDelta( "CREATE TABLE {$p}platforms (
            id       INT UNSIGNED NOT NULL AUTO_INCREMENT,
            date     DATE         NOT NULL,
            platform VARCHAR(100) NOT NULL DEFAULT '',
            visitors INT UNSIGNED NOT NULL DEFAULT 0,
            PRIMARY KEY (id),
            UNIQUE KEY uq_platform_date (platform, date)
        ) $charset;" );

        // A7. vs_referrers
        dbDelta( "CREATE TABLE {$p}referrers (
            id       INT UNSIGNED NOT NULL AUTO_INCREMENT,
            date     DATE         NOT NULL,
            host     VARCHAR(255) NOT NULL DEFAULT '',
            url      TEXT,
            visits   INT UNSIGNED NOT NULL DEFAULT 0,
            PRIMARY KEY (id),
            UNIQUE KEY uq_referrer_date (host, date)
        ) $charset;" );

        // A8. vs_search_engines
        dbDelta( "CREATE TABLE {$p}search_engines (
            id     INT UNSIGNED NOT NULL AUTO_INCREMENT,
            date   DATE         NOT NULL,
            engine VARCHAR(50)  NOT NULL DEFAULT '',
            query  VARCHAR(500) NOT NULL DEFAULT '',
            visits INT UNSIGNED NOT NULL DEFAULT 0,
            PRIMARY KEY (id),
            KEY idx_date (date)
        ) $charset;" );

        // A9. vs_online
        dbDelta( "CREATE TABLE {$p}online (
            id         INT UNSIGNED    NOT NULL AUTO_INCREMENT,
            visitor_id BIGINT UNSIGNED DEFAULT NULL,
            ip_hash    VARCHAR(64)     NOT NULL DEFAULT '',
            ip_raw     VARCHAR(45)     NOT NULL DEFAULT '',
            page_uri   VARCHAR(2000)   NOT NULL DEFAULT '/',
            last_seen  DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY uq_ip (ip_hash),
            KEY idx_last_seen (last_seen)
        ) $charset;" );

        // B1. vs_sessions
        dbDelta( "CREATE TABLE {$p}sessions (
            id               BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            visitor_id       BIGINT UNSIGNED DEFAULT NULL,
            session_key      VARCHAR(36)     NOT NULL DEFAULT '',
            date             DATE            NOT NULL,
            page_uri         VARCHAR(2000)   NOT NULL DEFAULT '/',
            page_title       VARCHAR(500)    NOT NULL DEFAULT '',
            viewport_w       SMALLINT UNSIGNED DEFAULT NULL,
            viewport_h       SMALLINT UNSIGNED DEFAULT NULL,
            page_h           INT UNSIGNED     DEFAULT NULL,
            duration_ms      INT UNSIGNED     DEFAULT NULL,
            max_scroll_px    INT UNSIGNED     DEFAULT NULL,
            max_scroll_pct   TINYINT UNSIGNED DEFAULT NULL,
            click_count      SMALLINT UNSIGNED NOT NULL DEFAULT 0,
            scroll_count     SMALLINT UNSIGNED NOT NULL DEFAULT 0,
            input_count      SMALLINT UNSIGNED NOT NULL DEFAULT 0,
            rage_clicks      TINYINT UNSIGNED  NOT NULL DEFAULT 0,
            error_count      SMALLINT UNSIGNED NOT NULL DEFAULT 0,
            is_complete      TINYINT(1)       NOT NULL DEFAULT 0,
            started_at       DATETIME         NOT NULL DEFAULT CURRENT_TIMESTAMP,
            ended_at         DATETIME         DEFAULT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY uq_session_key (session_key),
            KEY idx_visitor (visitor_id),
            KEY idx_date (date)
        ) $charset;" );

        // B2. vs_session_events
        dbDelta( "CREATE TABLE {$p}session_events (
            id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            session_id  BIGINT UNSIGNED NOT NULL,
            t           INT UNSIGNED    NOT NULL,
            type        VARCHAR(30)     NOT NULL,
            x           SMALLINT         DEFAULT NULL,
            y           INT              DEFAULT NULL,
            scroll_x    INT UNSIGNED     DEFAULT NULL,
            scroll_y    INT UNSIGNED     DEFAULT NULL,
            tag         VARCHAR(30)      DEFAULT NULL,
            el_id       VARCHAR(200)     DEFAULT NULL,
            el_class    VARCHAR(300)     DEFAULT NULL,
            el_text     VARCHAR(200)     DEFAULT NULL,
            href        VARCHAR(2000)    DEFAULT NULL,
            input_type  VARCHAR(30)      DEFAULT NULL,
            input_name  VARCHAR(200)     DEFAULT NULL,
            vp_w        SMALLINT UNSIGNED DEFAULT NULL,
            vp_h        SMALLINT UNSIGNED DEFAULT NULL,
            meta        TEXT             DEFAULT NULL,
            PRIMARY KEY (id),
            KEY idx_session (session_id),
            KEY idx_type (type)
        ) $charset;" );

        // K1. vs_recording_config
        dbDelta( "CREATE TABLE {$p}recording_config (
            id                    INT UNSIGNED     NOT NULL AUTO_INCREMENT,
            sampling_rate         TINYINT UNSIGNED NOT NULL DEFAULT 100,
            session_limit         INT UNSIGNED     NOT NULL DEFAULT 500,
            retention_days        SMALLINT UNSIGNED NOT NULL DEFAULT 7,
            exclude_urls          TEXT             DEFAULT NULL,
            exclude_ips           TEXT             DEFAULT NULL,
            exclude_roles         TEXT             DEFAULT NULL,
            exclude_bots          TINYINT(1)       NOT NULL DEFAULT 1,
            exclude_wp_admin      TINYINT(1)       NOT NULL DEFAULT 1,
            exclude_logged_admins TINYINT(1)       NOT NULL DEFAULT 1,
            respect_dnt           TINYINT(1)       NOT NULL DEFAULT 0,
            mask_inputs           TINYINT(1)       NOT NULL DEFAULT 1,
            skip_idle             TINYINT(1)       NOT NULL DEFAULT 1,
            consent_required      TINYINT(1)       NOT NULL DEFAULT 0,
            consent_mode          VARCHAR(30)      NOT NULL DEFAULT 'none',
            consent_cookie_name   VARCHAR(100)     DEFAULT NULL,
            updated_at            DATETIME         DEFAULT NULL,
            PRIMARY KEY (id)
        ) $charset;" );

        // Insert default config row
        $config_table = $p . 'recording_config';
        $exists = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i", $config_table ) );
        if ( ! $exists ) {
            $wpdb->insert( $config_table, [
                'sampling_rate'  => 100,
                'session_limit'  => 500,
                'retention_days' => 7,
            ] );
        }

        update_option( 'vlens_db_version', VLENS_VERSION );
    }

    /**
     * Run incremental DB patches on existing installs.
     * Called on admin_init — uses a versioned option so each patch runs once.
     */
    public static function maybe_upgrade() {
        // Patch 1 — add cookie_id column to vs_visitors (for pre-existing installs)
        if ( get_option( 'vlens_db_patch_cookie_id' ) ) {
            return;
        }
        global $wpdb;
        $p = $wpdb->prefix . VLENS_TABLE_PREFIX;
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $charset = $wpdb->get_charset_collate();
        dbDelta( "CREATE TABLE {$p}visitors (
            id              BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            date            DATE            NOT NULL,
            ip              VARCHAR(64)     NOT NULL DEFAULT '',
            ip_raw          VARCHAR(45)     NOT NULL DEFAULT '',
            referred        TEXT,
            agent           VARCHAR(500)    NOT NULL DEFAULT '',
            platform        VARCHAR(100)    NOT NULL DEFAULT '',
            browser         VARCHAR(100)    NOT NULL DEFAULT '',
            browser_version VARCHAR(50)     NOT NULL DEFAULT '',
            device_type     VARCHAR(20)     NOT NULL DEFAULT 'unknown',
            country_code    CHAR(2)         NOT NULL DEFAULT '--',
            country_name    VARCHAR(100)    NOT NULL DEFAULT '',
            city            VARCHAR(100)    NOT NULL DEFAULT '',
            region          VARCHAR(100)    NOT NULL DEFAULT '',
            latitude        DECIMAL(9,6)    DEFAULT NULL,
            longitude       DECIMAL(9,6)    DEFAULT NULL,
            language        VARCHAR(10)     NOT NULL DEFAULT '',
            timezone        VARCHAR(60)     NOT NULL DEFAULT '',
            screen_width    SMALLINT UNSIGNED DEFAULT NULL,
            screen_height   SMALLINT UNSIGNED DEFAULT NULL,
            is_bot          TINYINT(1)      NOT NULL DEFAULT 0,
            wp_user_id      BIGINT UNSIGNED DEFAULT NULL,
            cookie_id       VARCHAR(64)     DEFAULT NULL,
            created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY uq_visitor_day (ip, date),
            KEY idx_date (date),
            KEY idx_ip_raw (ip_raw),
            KEY idx_cookie (cookie_id)
        ) {$charset};" );

        update_option( 'vlens_db_patch_cookie_id', '1' );
    }

    /**
     * Set default plugin options.
     */
    private static function set_default_options() {
        if ( false === get_option( 'vlens_tracker_secret' ) ) {
            update_option( 'vlens_tracker_secret', wp_generate_password( 32, false ) );
        }
        if ( false === get_option( 'vlens_ip_salt' ) ) {
            update_option( 'vlens_ip_salt', wp_generate_password( 32, false ) );
        }
        if ( false === get_option( 'vlens_geoip_enabled' ) ) {
            update_option( 'vlens_geoip_enabled', '0' );
        }
        if ( false === get_option( 'vlens_recording_enabled' ) ) {
            update_option( 'vlens_recording_enabled', '1' );
        }
        if ( false === get_option( 'vlens_tracking_enabled' ) ) {
            update_option( 'vlens_tracking_enabled', '1' );
        }
    }
}
