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

/**
 * GDPR / WordPress Privacy compliance.
 *
 * - Registers a privacy policy suggestion via wp_add_privacy_policy_content().
 * - Registers a personal data exporter via wp_privacy_personal_data_exporters.
 * - Registers a personal data eraser  via wp_privacy_personal_data_erasers.
 */
class VLENS_Privacy {

    public function __construct() {
        add_action( 'admin_init',                           [ $this, 'add_privacy_policy_content' ] );
        add_filter( 'wp_privacy_personal_data_exporters',   [ $this, 'register_exporter' ] );
        add_filter( 'wp_privacy_personal_data_erasers',     [ $this, 'register_eraser' ] );
    }

    // -------------------------------------------------------------------------
    // Privacy Policy suggestion
    // -------------------------------------------------------------------------

    public function add_privacy_policy_content() {
        if ( ! function_exists( 'wp_add_privacy_policy_content' ) ) {
            return;
        }

        $content = '<h2>' . __( 'VisitorLens – Analytics & Session Replay', 'visitor-lens' ) . '</h2>';

        $content .= '<p>' . __( 'We use the VisitorLens plugin to collect anonymous visitor analytics and, where enabled, to record browsing sessions for UX research purposes.', 'visitor-lens' ) . '</p>';

        $content .= '<h3>' . __( 'What data we collect', 'visitor-lens' ) . '</h3>';
        $content .= '<ul>';
        $content .= '<li>' . __( 'IP address (stored as a one-way cryptographic hash by default; raw IP is stored only when explicitly configured)', 'visitor-lens' ) . '</li>';
        $content .= '<li>' . __( 'Browser type, version, and operating system (user agent string)', 'visitor-lens' ) . '</li>';
        $content .= '<li>' . __( 'Approximate geographic location (country, region, city) — when GeoIP is enabled, the visitor\'s IP address is sent to ip-api.com to resolve country/region/city; GeoIP can be disabled in Settings', 'visitor-lens' ) . '</li>';
        $content .= '<li>' . __( 'Screen resolution and viewport size', 'visitor-lens' ) . '</li>';
        $content .= '<li>' . __( 'Pages visited, referrer URLs, search queries, and UTM campaign parameters', 'visitor-lens' ) . '</li>';
        $content .= '<li>' . __( 'Session recording events: mouse movements, clicks, scroll depth, and — when mask_inputs is disabled — form field interactions (input values are masked by default)', 'visitor-lens' ) . '</li>';
        $content .= '<li>' . __( 'WordPress user ID, if the visitor is logged in', 'visitor-lens' ) . '</li>';
        $content .= '</ul>';

        $content .= '<h3>' . __( 'How we use this data', 'visitor-lens' ) . '</h3>';
        $content .= '<p>' . __( 'Data is used solely for website analytics, diagnosing usability issues, and improving site performance. It is never sold or shared with third parties.', 'visitor-lens' ) . '</p>';

        $content .= '<h3>' . __( 'Data retention', 'visitor-lens' ) . '</h3>';
        $content .= '<p>' . __( 'Session recordings are automatically deleted after the retention period configured in VisitorLens → Settings → Data Management (default: 7 days). Aggregate analytics data may be retained indefinitely in anonymised form.', 'visitor-lens' ) . '</p>';

        $content .= '<h3>' . __( 'Third-party services', 'visitor-lens' ) . '</h3>';
        $content .= '<p>' . __( 'VisitorLens does not send any visitor data to third-party services. Geo-location lookup is performed locally using a bundled database.', 'visitor-lens' ) . '</p>';

        $content .= '<h3>' . __( 'Your rights', 'visitor-lens' ) . '</h3>';
        $content .= '<p>' . __( 'If you are a logged-in WordPress user, you may request an export or deletion of your recorded session data via the built-in WordPress privacy tools (Tools → Erase Personal Data / Export Personal Data).', 'visitor-lens' ) . '</p>';

        wp_add_privacy_policy_content( 'VisitorLens', wp_kses_post( $content ) );
    }

    // -------------------------------------------------------------------------
    // Personal Data Exporter
    // -------------------------------------------------------------------------

    public function register_exporter( $exporters ) {
        $exporters['visitor-lens'] = [
            'exporter_friendly_name' => __( 'VisitorLens Session Data', 'visitor-lens' ),
            'callback'               => [ $this, 'export_personal_data' ],
        ];
        return $exporters;
    }

    /**
     * Export all visitor/session rows linked to a WP user account.
     *
     * @param string $email_address User email.
     * @param int    $page          Pagination page (1-indexed).
     * @return array { data, done }
     */
    public function export_personal_data( $email_address, $page = 1 ) {
        global $wpdb;

        $user = get_user_by( 'email', $email_address );
        if ( ! $user ) {
            return [ 'data' => [], 'done' => true ];
        }

        $t_visitors = VLENS_Helpers::table( 'visitors' );
        $t_sessions = VLENS_Helpers::table( 'sessions' );
        $per_page   = 50;
        $offset     = ( $page - 1 ) * $per_page;
        $user_id    = (int) $user->ID;

        // Visitor rows for this WP user.
        $visitors = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT id, date, ip, country_name, city, region, browser, browser_version,
                        platform, device_type, language, timezone, screen_width, screen_height, created_at
                   FROM %i
                  WHERE wp_user_id = %d
                  LIMIT %d OFFSET %d",
                $t_visitors, $user_id, $per_page, $offset
            )
        );

        if ( empty( $visitors ) ) {
            return [ 'data' => [], 'done' => true ];
        }

        $export_items = [];

        foreach ( $visitors as $row ) {
            $visitor_data = [
                [ 'name' => __( 'Date', 'visitor-lens' ),             'value' => esc_html( $row->date ) ],
                [ 'name' => __( 'IP Hash', 'visitor-lens' ),          'value' => esc_html( $row->ip ) ],
                [ 'name' => __( 'Country', 'visitor-lens' ),          'value' => esc_html( $row->country_name ) ],
                [ 'name' => __( 'City', 'visitor-lens' ),             'value' => esc_html( $row->city ) ],
                [ 'name' => __( 'Region', 'visitor-lens' ),           'value' => esc_html( $row->region ) ],
                [ 'name' => __( 'Browser', 'visitor-lens' ),          'value' => esc_html( $row->browser . ' ' . $row->browser_version ) ],
                [ 'name' => __( 'Platform', 'visitor-lens' ),         'value' => esc_html( $row->platform ) ],
                [ 'name' => __( 'Device', 'visitor-lens' ),           'value' => esc_html( $row->device_type ) ],
                [ 'name' => __( 'Language', 'visitor-lens' ),         'value' => esc_html( $row->language ) ],
                [ 'name' => __( 'Timezone', 'visitor-lens' ),         'value' => esc_html( $row->timezone ) ],
                [ 'name' => __( 'Screen', 'visitor-lens' ),           'value' => esc_html( $row->screen_width . 'x' . $row->screen_height ) ],
                [ 'name' => __( 'Recorded At', 'visitor-lens' ),      'value' => esc_html( $row->created_at ) ],
            ];

            // Sessions for this visitor.
            $sessions = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT session_key, page_uri, page_title, duration_ms, click_count, started_at
                       FROM %i
                      WHERE visitor_id = %d",
                    $t_sessions, (int) $row->id
                )
            );

            foreach ( $sessions as $idx => $s ) {
                $visitor_data[] = [
                    'name'  => sprintf( __( 'Session %d URL', 'visitor-lens' ), $idx + 1 ),
                    'value' => esc_html( $s->page_uri ),
                ];
                $visitor_data[] = [
                    'name'  => sprintf( __( 'Session %d Started', 'visitor-lens' ), $idx + 1 ),
                    'value' => esc_html( $s->started_at ),
                ];
            }

            $export_items[] = [
                'group_id'    => 'visitor-lens-visitor',
                'group_label' => __( 'VisitorLens Analytics Record', 'visitor-lens' ),
                'item_id'     => 'visitor-lens-' . (int) $row->id,
                'data'        => $visitor_data,
            ];
        }

        // More pages if we got a full page.
        $done = count( $visitors ) < $per_page;

        return [ 'data' => $export_items, 'done' => $done ];
    }

    // -------------------------------------------------------------------------
    // Personal Data Eraser
    // -------------------------------------------------------------------------

    public function register_eraser( $erasers ) {
        $erasers['visitor-lens'] = [
            'eraser_friendly_name' => __( 'VisitorLens Session Data', 'visitor-lens' ),
            'callback'             => [ $this, 'erase_personal_data' ],
        ];
        return $erasers;
    }

    /**
     * Erase all visitor/session rows linked to a WP user account.
     *
     * @param string $email_address User email.
     * @param int    $page          Pagination page (1-indexed).
     * @return array { items_removed, items_retained, messages, done }
     */
    public function erase_personal_data( $email_address, $page = 1 ) {
        global $wpdb;

        $user = get_user_by( 'email', $email_address );
        if ( ! $user ) {
            return [
                'items_removed'  => false,
                'items_retained' => false,
                'messages'       => [],
                'done'           => true,
            ];
        }

        $t_visitors = VLENS_Helpers::table( 'visitors' );
        $t_sessions = VLENS_Helpers::table( 'sessions' );
        $t_events   = VLENS_Helpers::table( 'session_events' );
        $t_visits   = VLENS_Helpers::table( 'visits' );
        $per_page   = 50;
        $offset     = ( $page - 1 ) * $per_page;
        $user_id    = (int) $user->ID;

        $visitor_ids = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT id FROM %i WHERE wp_user_id = %d LIMIT %d OFFSET %d",
                $t_visitors, $user_id, $per_page, $offset
            )
        );

        if ( empty( $visitor_ids ) ) {
            return [
                'items_removed'  => false,
                'items_retained' => false,
                'messages'       => [],
                'done'           => true,
            ];
        }

        $placeholders = implode( ',', array_fill( 0, count( $visitor_ids ), '%d' ) );

        // Delete session_events → sessions → visits → visitors (child-first).
        $session_ids = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT id FROM %i WHERE visitor_id IN ($placeholders)",
                $t_sessions, ...$visitor_ids
            )
        );

        if ( ! empty( $session_ids ) ) {
            $s_ph = implode( ',', array_fill( 0, count( $session_ids ), '%d' ) );
            $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE session_id IN ($s_ph)", $t_events, ...$session_ids ) );
            $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE id IN ($s_ph)", $t_sessions, ...$session_ids ) );
        }

        $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE visitor_id IN ($placeholders)", $t_visits, ...$visitor_ids ) );
        $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE id IN ($placeholders)", $t_visitors, ...$visitor_ids ) );

        $done = count( $visitor_ids ) < $per_page;

        return [
            'items_removed'  => true,
            'items_retained' => false,
            'messages'       => [],
            'done'           => $done,
        ];
    }
}
