<?php
if (!defined('ABSPATH')) die('Restricted Access');

class AIFLT_Privacy_Logic {
    
    /**
     * Registers the privacy policy content and data exporter/eraser hooks.
     * Called from the main plugin file on admin_init.
     */
    public static function register_privacy_hooks() {
        // Add suggested privacy policy content
        if (function_exists('wp_add_privacy_policy_content')) {
            $content = self::get_privacy_policy_content();
            wp_add_privacy_policy_content(__('AI Flash Tune', 'ai-flash-tune'), $content);
        }

        // Register Data Exporter
        add_filter('wp_privacy_personal_data_exporters', array(__CLASS__, 'register_privacy_exporter'));

        // Register Data Eraser
        add_filter('wp_privacy_personal_data_erasers', array(__CLASS__, 'register_privacy_eraser'));
    }

    /**
     * Returns the suggested privacy policy text.
     */
    private static function get_privacy_policy_content() {
        return 
            '<p class="privacy-policy-tutorial">' . 
            __('AI Flash Tune collects data to help store owners optimize their sales funnel. This includes anonymous session data and, for logged-in users, user IDs linked to browsing behavior.', 'ai-flash-tune') . 
            '</p>' .
            '<strong class="privacy-policy-tutorial">' . __('What we collect', 'ai-flash-tune') . '</strong>' .
            '<ul class="privacy-policy-tutorial">' .
            '<li>' . __('Pages visited and timestamps', 'ai-flash-tune') . '</li>' .
            '<li>' . __('Products viewed and added to cart', 'ai-flash-tune') . '</li>' .
            '<li>' . __('Anonymized IP addresses (if enabled in settings)', 'ai-flash-tune') . '</li>' .
            '<li>' . __('Device type (Desktop/Mobile)', 'ai-flash-tune') . '</li>' .
            '</ul>';
    }

    /**
     * Registers the personal data exporter.
     */
    public static function register_privacy_exporter($exporters) {
        $exporters['ai-flash-tune'] = array(
            'exporter_friendly_name' => __('AI Flash Tune Data', 'ai-flash-tune'),
            'callback' => array(__CLASS__, 'privacy_exporter_callback'),
        );
        return $exporters;
    }

    /**
     * Registers the personal data eraser.
     */
    public static function register_privacy_eraser($erasers) {
        $erasers['ai-flash-tune'] = array(
            'eraser_friendly_name' => __('AI Flash Tune Data', 'ai-flash-tune'),
            'callback' => array(__CLASS__, 'privacy_eraser_callback'),
        );
        return $erasers;
    }

    /**
     * Callback for the data exporter.
     * Finds funnel and behavior data for a given email address.
     */
    public static function privacy_exporter_callback($email_address, $page = 1) {
        $number = 500; // Limit per page
        $page = (int) $page;
        $export_items = array();

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

        $user_id = $user->ID;
        
        // 1. Fetch Funnel Data
        $funnel_data = self::get_data_from_table('aiflt_funnel_data', $user_id, true, true);
        foreach ($funnel_data as $row) {
            $export_items[] = array(
                'group_id' => 'aiflt_funnel',
                'group_label' => __('Funnel Tracking Data', 'ai-flash-tune'),
                'item_id' => 'funnel-' . $row['id'], // Assuming 'id' is in the raw result before cleaning, but let's use what's available
                'data' => array(
                    array(
                        'name' => __('Page Visited', 'ai-flash-tune'),
                        'value' => $row['page_name']
                    ),
                    array(
                        'name' => __('Timestamp', 'ai-flash-tune'),
                        'value' => $row['timestamp']
                    ),
                    array(
                        'name' => __('Device', 'ai-flash-tune'),
                        'value' => $row['device_type']
                    )
                )
            );
        }

        // 2. Fetch Behavior Data
        $behavior_data = self::get_data_from_table('aiflt_behavior_data', $user_id, true, true);
        foreach ($behavior_data as $row) {
            $export_items[] = array(
                'group_id' => 'aiflt_behavior',
                'group_label' => __('Behavioral Data', 'ai-flash-tune'),
                'item_id' => 'behavior-' . $row['id'],
                'data' => array(
                    array(
                        'name' => __('Event Type', 'ai-flash-tune'),
                        'value' => $row['event_label'] // Using the readable label
                    ),
                    array(
                        'name' => __('Product ID', 'ai-flash-tune'),
                        'value' => $row['product_id']
                    ),
                    array(
                        'name' => __('Timestamp', 'ai-flash-tune'),
                        'value' => $row['timestamp']
                    )
                )
            );
        }

        return array(
            'data' => $export_items,
            'done' => true, // We are doing it in one batch for now
        );
    }

    /**
     * Callback for the data eraser.
     * Deletes funnel and behavior data for a given email address.
     */
    public static function privacy_eraser_callback($email_address, $page = 1) {
        $user = get_user_by('email', $email_address);
        $items_removed = false;
        $items_retained = false;
        $messages = array();

        if ($user) {
            $user_id = $user->ID;
            $deleted_rows = self::delete_data_by_identifier($user_id); // Reusing existing logic
            
            $total_deleted = $deleted_rows['funnel_data'] + $deleted_rows['behavior_data'];

            if ($total_deleted > 0) {
                $items_removed = true;
                $messages[] = sprintf(
                    /* translators: %d: number of tracking records removed during privacy erasure. */
                    __('AI Flash Tune: Removed %d tracking records.', 'ai-flash-tune'),
                    $total_deleted
                );
            }
        }

        return array(
            'items_removed' => $items_removed,
            'items_retained' => $items_retained,
            'messages' => $messages,
            'done' => true,
        );
    }

    /**
     * Finds and exports all data associated with an identifier (IP or User ID).
     *
     * This function is now the central entry point for both direct form submission 
     * (non-AJAX) and AJAX submission for file download.
     * * @param string $aiflt_identifier The IP address or User ID to search for.
     */
    public static function export_data_by_identifier($aiflt_identifier) {
        
        if (empty($aiflt_identifier)) {
            return; // Exit silently if identifier is empty after cleaning the buffer.
        }
        // CRITICAL FIX: Aggressive Output Buffer Clean MUST be the first thing, 
        // even before identifier checks, to catch output from core WP files.
        if (ob_get_level() > 0) {
            ob_clean();
        }

        $is_user_id = is_numeric($aiflt_identifier);
        
        // Use the cleaned data, respecting the current WC status for cleaning.
        $data_to_export = [
            'funnel_data' => self::get_data_from_table('aiflt_funnel_data', $aiflt_identifier, $is_user_id, true),
            'behavior_data' => self::get_data_from_table('aiflt_behavior_data', $aiflt_identifier, $is_user_id, true),
        ];

        $filename = 'aiflt_privacy_export_' . sanitize_file_name($aiflt_identifier) . '_' . gmdate('Y-m-d') . '.json';
        
        // Generate content and calculate its size BEFORE sending headers
        $json_output = wp_json_encode($data_to_export, JSON_PRETTY_PRINT);
        $file_size = strlen($json_output);

        // Set headers and content
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . $file_size);
        
        // Output the file content
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Data is JSON encoded for file download, escaping HTML would break the file format.
        echo $json_output;
        
        // CRITICAL: Exit the script immediately
        exit;
    }


    /**
     * Handles the AJAX request to export user data.
     * @return void Sends JSON output and exits.
     */
    public static function ajax_export_data() {
        // NOTE: The main logic is in export_data_by_identifier, 
        // we just handle security/input validation here.
        
        check_ajax_referer('aiflt_privacy_actions', '_ajax_nonce');

        if (!current_user_can('manage_options')) {
            wp_die( esc_html__('Permission denied.', 'ai-flash-tune'), '', array('response' => 403) );
        }
        
        $aiflt_identifier = isset($_POST['identifier']) ? sanitize_text_field(wp_unslash($_POST['identifier'])) : '';
        
        if (empty($aiflt_identifier)) {
            wp_die( esc_html__('Identifier is missing.', 'ai-flash-tune'), '', array('response' => 400) );
        }

        // Call the core export function directly.
        self::export_data_by_identifier($aiflt_identifier); 
        
        // This is necessary if export_data_by_identifier failed early.
        exit; 
    }

    /**
     * Finds and deletes all data associated with an identifier.
     *
     * @param string $aiflt_identifier The IP address or User ID to search for.
     * @return array The number of rows deleted from each table.
     */
    public static function delete_data_by_identifier($aiflt_identifier) {
        if (empty($aiflt_identifier)) {
            return ['funnel_data' => 0, 'behavior_data' => 0];
        }
        
        $is_user_id = is_numeric($aiflt_identifier);
        $aiflt_deleted_rows = [
            'funnel_data' => self::delete_data_from_table('aiflt_funnel_data', $aiflt_identifier, $is_user_id),
            'behavior_data' => self::delete_data_from_table('aiflt_behavior_data', $aiflt_identifier, $is_user_id),
        ];
        
        return $aiflt_deleted_rows;
    }

    /**
     * Helper to get data from a specific table and clean it up for export.
     * * @param string $table_suffix The suffix of the table name.
     * @param string $aiflt_identifier The IP address or User ID.
     * @param bool $is_user_id Is the identifier a user ID?
     * @param bool $cleanup Should the data be cleaned/formatted for export?
     * @return array The retrieved and cleaned data.
     */
    private static function get_data_from_table($table_suffix, $aiflt_identifier, $is_user_id, $cleanup = false) {
        global $wpdb;
        $allowed_tables = array('aiflt_funnel_data', 'aiflt_behavior_data');
        if (!in_array($table_suffix, $allowed_tables, true)) {
            return array();
        }
        $table_name = esc_sql($wpdb->prefix . $table_suffix);
        if ($is_user_id) {
            $column_key = 'user_id';
            $format = '%d';
        } elseif (is_string($aiflt_identifier) && strpos($aiflt_identifier, 'aiflt_session_') === 0) {
            $column_key = 'session_id';
            $format = '%s';
        } else {
            $column_key = 'ip_address';
            $format = '%s';
        }

        $allowed_columns = array(
            'user_id'    => 'user_id',
            'session_id' => 'session_id',
            'ip_address' => 'ip_address',
        );
        $column = $allowed_columns[$column_key];

        $raw_results = $wpdb->get_results(
            $wpdb->prepare("SELECT * FROM {$table_name} WHERE {$column} = {$format}", $aiflt_identifier),
            ARRAY_A
        );
        
        if (!$cleanup || empty($raw_results)) {
            return $raw_results;
        }

        // Check WooCommerce status once for robust conditional logic
        $aiflt_is_wc_active = class_exists('WooCommerce');
        $cleaned_results = [];
        
        foreach ($raw_results as $row) {
            $new_row = $row;
            
            // 1. Remove database internal ID if not needed for export logic, 
            // but keep it for Erasure/Exporter callbacks which might reference it.
            // unset($new_row['id']); 
            
            // 2. Humanize timestamp
            $new_row['timestamp'] = wp_date('Y-m-d H:i:s T', strtotime($row['timestamp']));

            // 3. Handle Funnel Data specifics
            if ($table_suffix === 'aiflt_funnel_data') {
                if (!empty($row['cart_data'])) {
                    $aiflt_cart_data = maybe_unserialize($row['cart_data']);
                    
                    // CRITICAL FIX: Only attempt to clean WC-formatted strings if WC is active.
                    if ($aiflt_is_wc_active && is_array($aiflt_cart_data)) { 
                        if (is_array($aiflt_cart_data) && isset($aiflt_cart_data['cart_total'])) {
                        // Strip HTML from cart total and other price strings
                            $aiflt_cart_data['cart_total'] = wp_strip_all_tags($aiflt_cart_data['cart_total']);
                        }
                        if (is_array($aiflt_cart_data) && isset($aiflt_cart_data['contents']) && is_array($aiflt_cart_data['contents'])) {
                        // Strip HTML/tags from product names
                            foreach ($aiflt_cart_data['contents'] as &$aiflt_item) {
                                $aiflt_item['name'] = wp_strip_all_tags($aiflt_item['name']);
                            }
                        }
                    }
                    // If WC is inactive, the data remains unserialized, avoiding function calls that rely on WC.

                    $new_row['cart_data'] = $aiflt_cart_data;
                }
            }
            
            // 4. Handle Behavior Data specifics
            if ($table_suffix === 'aiflt_behavior_data') {
                if (!empty($row['behavior_value'])) {
                    // Try to decode JSON, fallback to raw string if it fails
                    $decoded_value = json_decode($row['behavior_value'], true);
                    $new_row['behavior_value'] = is_array($decoded_value) ? $decoded_value : $row['behavior_value'];
                }
                
                // Add a readable event label
                $new_row['event_label'] = self::get_behavior_event_label($row['behavior_type']);
            }
            
            $cleaned_results[] = $new_row;
        }

        return $cleaned_results;
    }

    /**
     * Provides a human-readable label for common behavior events.
     */
    private static function get_behavior_event_label($type) {
        switch ($type) {
            case 'rage_click': return 'User experienced frustration (Rage Clicks)';
            case 'quick_bounce': return 'User left quickly (Quick Bounce)';
            case 'scroll_stop': return 'User hesitated/stuck (Scroll Stop)';
            case 'add_to_cart': return 'Product Added to Cart';
            case 'checkout_field_exit': return 'Exited Checkout Field';
            case 'payment_method_selected': return 'Payment Method Selected';
            default: return $type;
        }
    }

    /**
     * Helper to delete data from a specific table.
     */
    private static function delete_data_from_table($table_suffix, $aiflt_identifier, $is_user_id) {
        global $wpdb;
        $allowed_tables = array('aiflt_funnel_data', 'aiflt_behavior_data');
        if (!in_array($table_suffix, $allowed_tables, true)) {
            return array();
        }
        $table_name = esc_sql($wpdb->prefix . $table_suffix);
        if ($is_user_id) {
            $column = 'user_id';
            $format = '%d';
        } elseif (is_string($aiflt_identifier) && strpos($aiflt_identifier, 'aiflt_session_') === 0) {
            $column = 'session_id';
            $format = '%s';
        } else {
            $column = 'ip_address';
            $format = '%s';
        }
        
        return $wpdb->delete($table_name, [$column => $aiflt_identifier], [$format]);
    }
}
