<?php
// Block direct access
if (!defined('ABSPATH')) {
    exit;
}
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-flash-tune'));
}

// Check WooCommerce status
$aiflt_is_wc_active = aiflt_is_woocommerce_active();

/**
 * Basic validation check for identifier structure.
 */
function aiflt_is_valid_identifier($aiflt_identifier) {
    // Check 1: Valid User ID (numeric, non-zero)
    if (is_numeric($aiflt_identifier) && (int)$aiflt_identifier > 0) {
        return true;
    }
    // Check 2: Valid IP address (IPv4 or IPv6)
    if (filter_var($aiflt_identifier, FILTER_VALIDATE_IP)) {
        return true;
    }
    // Check 3: Anonymous visit/session ID created by AI Flash Tune
    if (preg_match('/^aiflt_session_[A-Za-z0-9_.-]+$/', $aiflt_identifier)) {
        return true;
    }
    return false;
}

// --- Form Submission Logic ---
$aiflt_message = '';
$aiflt_message_type = 'success'; // Can be 'success' or 'error'
$aiflt_identifier = '';

if ($aiflt_is_wc_active && isset($_POST['aiflt_privacy_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aiflt_privacy_nonce'])), 'aiflt_privacy_actions')) {
    
    $aiflt_identifier = isset($_POST['identifier']) ? sanitize_text_field(wp_unslash($_POST['identifier'])) : '';

    if (!empty($aiflt_identifier)) {
        
        // --- NEW VALIDATION CHECK ---
        if (!aiflt_is_valid_identifier($aiflt_identifier)) {
            $aiflt_message = esc_html__('Error: Please enter a valid User ID, Visit ID, or IP Address.', 'ai-flash-tune');
            $aiflt_message_type = 'error';
        } else {
            // Handle Delete Action
            if (isset($_POST['delete_data'])) {
                // Ensure class name AIFLT_Privacy_Logic is used (as refactored)
                $aiflt_deleted_rows = AIFLT_Privacy_Logic::delete_data_by_identifier($aiflt_identifier);
                $aiflt_total_deleted = (int) ($aiflt_deleted_rows['funnel_data'] ?? 0) + (int) ($aiflt_deleted_rows['behavior_data'] ?? 0);
                
                // --- NEW MESSAGE LOGIC (Fix 2) ---
                if ($aiflt_total_deleted > 0) {
                    $aiflt_message = esc_html__('Successfully deleted ', 'ai-flash-tune') . $aiflt_total_deleted . 
                            esc_html__(' record(s) associated with the identifier', 'ai-flash-tune') . ' "' . 
                            esc_html($aiflt_identifier) . 
                            '".';
                    $aiflt_message_type = 'success';
                } else {
                    $aiflt_message = esc_html__('No record(s) found for the identifier. No data was deleted.', 'ai-flash-tune');
                    $aiflt_message_type = 'error'; // Indicate failure to delete (no records found)
                }
            }

            // Handle Export Action (Note: this action will exit the script to force a file download)
            if (isset($_POST['export_data'])) {
                // Ensure class name AIFLT_Privacy_Logic is used (as refactored)
                AIFLT_Privacy_Logic::export_data_by_identifier($aiflt_identifier);
            }
        } // End of valid identifier check
    } else {
        $aiflt_message = esc_html__('Error: Please enter a User ID, Visit ID, or IP Address to search for.', 'ai-flash-tune');
        $aiflt_message_type = 'error';
    }
}
?>
<?php // ---> FIX: The wrapper and sidebar include were missing. They are now restored. ?>
<div class="ai-flash-tune-admin-wrapper">
    <?php include_once('ai-flash-tune-admin-sidebar.php'); ?>
    <div class="ai-flash-tune-main-content">
        <span class="ai-flash-tune-main-title"><?php echo esc_html__('Privacy Tools', 'ai-flash-tune'); ?></span>
        <p class="ai-flash-tune-text-gray-600 ai-flash-tune-mb-6">
            <?php echo esc_html__('Manage personal data collected by AI Flash Tune in compliance with privacy regulations like GDPR. Use these tools to export or erase user data from your database.', 'ai-flash-tune'); ?>
        </p>

        <?php if (!empty($aiflt_message)) : ?>
            <?php 
                $aiflt_notice_class = $aiflt_message_type === 'success' ? 'ai-flash-tune-notice-success' : 'ai-flash-tune-notice-error';
                $aiflt_icon_class = $aiflt_message_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle';
            ?>
            <div class="ai-flash-tune-notice-bar <?php echo esc_attr($aiflt_notice_class); ?> ai-flash-tune-mb-6">
                 <div class="ai-flash-tune-notice-content">
                    <i class="fas <?php echo esc_attr($aiflt_icon_class); ?>"></i>
                    <span><?php echo esc_html($aiflt_message); ?></span>
                </div>
            </div>
        <?php endif; ?>

        <div class="ai-flash-tune-grid ai-flash-tune-grid-cols-1 lg:ai-flash-tune-grid-cols-3 ai-flash-tune-gap-6">
            
            <div class="lg:ai-flash-tune-col-span-2">
                <div class="ai-flash-tune-card">
                    <h2 class="ai-flash-tune-card-title ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-mb-4">
                        <i class="fas fa-search ai-flash-tune-text-indigo-600 ai-flash-tune-mr-2"></i>
                        <?php echo esc_html__('Find & Manage User Data', 'ai-flash-tune'); ?>
                    </h2>
                    <p class="ai-flash-tune-text-gray-600 ai-flash-tune-mb-6">
                        <?php echo esc_html__('Enter a known identifier to find, export, or permanently delete all associated data stored by this plugin.', 'ai-flash-tune'); ?>
                    </p>
                    
                    <?php if ($aiflt_is_wc_active) : ?>
                        <form method="POST" action="" class="ai-flash-tune-privacy-form">
                            <?php wp_nonce_field('aiflt_privacy_actions', 'aiflt_privacy_nonce'); ?>
                            
                            <div class="ai-flash-tune-form-field ai-flash-tune-mb-4">
                                <label for="identifier" class="ai-flash-tune-form-label">
                                    <?php echo esc_html__('User ID, Visit ID, or IP Address', 'ai-flash-tune'); ?>
                                </label>
                                <input type="text" id="identifier" name="identifier" class="ai-flash-tune-input" placeholder="e.g., 123, aiflt_session_..., or 192.168.1.1" value="<?php echo esc_attr($aiflt_identifier); ?>" required>
                            </div>

                            <div class="ai-flash-tune-flex ai-flash-tune-items-center ai-flash-tune-mt-6">
                                <button type="submit" name="export_data" class="ai-flash-tune-btn ai-flash-tune-btn-blue">
                                    <i class="fas fa-download ai-flash-tune-mr-2"></i>
                                    <?php echo esc_html__('Export Data', 'ai-flash-tune'); ?>
                                </button>
                                <button type="submit" name="delete_data" class="ai-flash-tune-btn ai-flash-tune-btn-red ai-flash-tune-ml-4" onclick="return confirm('<?php echo esc_js(__('Are you sure you want to permanently delete this data? This action cannot be undone.', 'ai-flash-tune')); ?>');">
                                    <i class="fas fa-trash-alt ai-flash-tune-mr-2"></i>
                                    <?php echo esc_html__('Delete Data', 'ai-flash-tune'); ?>
                                </button>
                            </div>
                        </form>
                    <?php else : 
                        // Show WooCommerce required notice when inactive
                        $aiflt_wc_status = aiflt_get_woocommerce_status(); // Call the helper function
                    ?>
                        <div class="ai-flash-tune-wc-required-notice" style="border: none; padding: 0;">
                            <i class="fas fa-plug ai-flash-tune-notice-icon"></i>
                            <p class="ai-flash-tune-notice-title"><?php echo esc_html__('WooCommerce is Required', 'ai-flash-tune'); ?></p>
                            <p class="ai-flash-tune-notice-text"><?php echo esc_html__('This page relies on WooCommerce data to function. Please install or activate WooCommerce to manage user data.', 'ai-flash-tune'); ?></p>
                            <a href="<?php echo esc_url($aiflt_wc_status['action_url']); ?>" class="ai-flash-tune-notice-button">
                                <?php echo esc_html($aiflt_wc_status['button_text']); ?>
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div>
                <div class="ai-flash-tune-card">
                     <h2 class="ai-flash-tune-card-title ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-mb-4">
                        <i class="fas fa-database ai-flash-tune-text-green-500 ai-flash-tune-mr-2"></i>
                        <?php echo esc_html__('Data Handled by This Tool', 'ai-flash-tune'); ?>
                    </h2>
                    <p class="ai-flash-tune-text-gray-600 ai-flash-tune-mb-4">
                        <?php echo esc_html__('This tool searches for the provided identifier in the following database tables and columns:', 'ai-flash-tune'); ?>
                    </p>
                    <ul class="ai-flash-tune-space-y-3">
                        <li class="ai-flash-tune-text-sm">
                            <strong class="ai-flash-tune-font-semibold ai-flash-tune-text-gray-800"><?php echo esc_html__('1. Funnel Data', 'ai-flash-tune'); ?></strong>
                            <p class="ai-flash-tune-text-gray-600" style="margin: 0.25rem 0 0 0;"><?php echo esc_html__('Table:', 'ai-flash-tune'); ?><code class="ai-flash-tune-text-xs"><?php global $wpdb; echo esc_html($wpdb->prefix . 'aiflt_funnel_data'); ?></code></p>
                            <p class="ai-flash-tune-text-gray-600" style="margin: 0.25rem 0 0 0;"><?php echo esc_html__('Columns Searched:', 'ai-flash-tune'); ?> `user_id`, `session_id`, `ip_address`</p>
                        </li>
                        <li class="ai-flash-tune-text-sm">
                            <strong class="ai-flash-tune-font-semibold ai-flash-tune-text-gray-800"><?php echo esc_html__('2. Behavior Data', 'ai-flash-tune'); ?></strong>
                            <p class="ai-flash-tune-text-gray-600" style="margin: 0.25rem 0 0 0;"><?php echo esc_html__('Table:', 'ai-flash-tune'); ?> <code class="ai-flash-tune-text-xs"><?php global $wpdb; echo esc_html($wpdb->prefix . 'aiflt_behavior_data'); ?></code></p>
                            <p class="ai-flash-tune-text-gray-600" style="margin: 0.25rem 0 0 0;"><?php echo esc_html__('Columns Searched:', 'ai-flash-tune'); ?> `user_id`, `session_id`, `ip_address`</p>
                        </li>
                    </ul>
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500 ai-flash-tune-mt-6">
                        <?php echo esc_html__('Exporting creates a JSON file with all matching records. Deleting permanently removes these records from your database.', 'ai-flash-tune'); ?>
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
