<?php
/**
 * Sentinel Privacy Class
 * 
 * Handles GDPR compliance features including data deletion requests and anonymization.
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class Sentinel_Privacy {
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->init_hooks();
    }
    
    /**
     * Initialize WordPress hooks
     */
    private function init_hooks() {
        // Register shortcode for data deletion request form
        add_shortcode('sentinel_data_deletion_request', array($this, 'render_deletion_request_form'));
        
        // Handle form submission
        add_action('wp_ajax_sentinel_submit_deletion_request', array($this, 'handle_deletion_request_submission'));
        add_action('wp_ajax_nopriv_sentinel_submit_deletion_request', array($this, 'handle_deletion_request_submission'));
        
        // Handle admin processing of deletion requests
        add_action('wp_ajax_sentinel_process_deletion_request', array($this, 'handle_admin_process_deletion_request'));
        
        // Add dashboard widget
        add_action('wp_dashboard_setup', array($this, 'add_dashboard_widget'));
        
        // Enqueue scripts and styles (frontend only)
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
    }
    
    /**
     * Enqueue scripts and styles for privacy features (frontend)
     */
    public function enqueue_scripts() {
        // Only enqueue if shortcode is present on the page
        global $post;
        if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'sentinel_data_deletion_request')) {
            wp_enqueue_style(
                'sentinel-privacy',
                SENTINEL_PLUGIN_URL . 'assets/css/sentinel-privacy.css',
                array(),
                SENTINEL_VERSION
            );
            
            wp_enqueue_script(
                'sentinel-privacy',
                SENTINEL_PLUGIN_URL . 'assets/js/sentinel-privacy.js',
                array('jquery'),
                SENTINEL_VERSION,
                true
            );
            
            // Localize script for AJAX URL
            wp_localize_script('sentinel-privacy', 'sentinelPrivacyAjax', array(
                'ajaxurl' => admin_url('admin-ajax.php')
            ));
        }
    }
    
    /**
     * Render the data deletion request form shortcode
     * 
     * @param array $atts Shortcode attributes
     * @return string Form HTML
     */
    public function render_deletion_request_form($atts = array()) {
        // Check if Right to be Forgotten is enabled
        $settings = get_option('sentinel_log_management', array());
        if (empty($settings['right_to_be_forgotten'])) {
            return '<p class="sentinel-privacy-disabled">Data deletion requests are currently disabled.</p>';
        }
        
        // Check if user is logged in
        if (!is_user_logged_in()) {
            return '<p class="sentinel-privacy-login-required">You must be logged in to submit a data deletion request.</p>';
        }
        
        // Check if user already has a pending request
        $user_id = get_current_user_id();
        if ($this->user_has_pending_request($user_id)) {
            return '<p class="sentinel-privacy-pending">You already have a pending data deletion request. Please wait for admin approval.</p>';
        }
        
        // Parse shortcode attributes
        $atts = shortcode_atts(array(
            'title' => 'Request Data Deletion',
            'description' => 'Submit a request to have your personal data anonymized from our security logs.',
            'button_text' => 'Submit Request'
        ), $atts, 'sentinel_data_deletion_request');
        
        // Start output buffering
        ob_start();
        ?>
<div class="sentinel-privacy-form-container">
    <form id="sentinel-deletion-request-form" class="sentinel-privacy-form">
        <?php wp_nonce_field('sentinel_deletion_request', 'sentinel_deletion_nonce'); ?>

        <h3><?php echo esc_html($atts['title']); ?></h3>
        <p><?php echo esc_html($atts['description']); ?></p>

        <div class="sentinel-privacy-disclaimer">
            <strong>⚠️ Important Notice:</strong> This request only affects data collected by the Sentinel security
            plugin (activity logs, IP addresses, etc.). It does not delete your account, posts, comments, or other
            website data. For complete account deletion, please contact the website administrator.
        </div>

        <div class="sentinel-form-field">
            <label for="deletion_reason">Reason for deletion request:</label>
            <select name="deletion_reason" id="deletion_reason" required>
                <option value="">Select a reason...</option>
                <option value="privacy_concerns">Privacy concerns</option>
                <option value="account_deletion">Account deletion</option>
                <option value="data_accuracy">Inaccurate data</option>
                <option value="legal_requirement">Legal requirement</option>
                <option value="other">Other</option>
            </select>
        </div>

        <div class="sentinel-form-field">
            <label for="deletion_details">Additional details (optional):</label>
            <textarea name="deletion_details" id="deletion_details" rows="4"
                placeholder="Please provide any additional context for your request..."></textarea>
        </div>

        <div class="sentinel-form-field">
            <label class="sentinel-checkbox-label">
                <input type="checkbox" name="confirm_deletion" id="confirm_deletion" required>
                <span>I understand that this request will anonymize my personal data from security logs while preserving
                    system security.</span>
            </label>
        </div>

        <div class="sentinel-form-field">
            <button type="submit" class="sentinel-submit-btn">
                <?php echo esc_html($atts['button_text']); ?>
            </button>
        </div>

        <div id="sentinel-form-message" class="sentinel-form-message" style="display: none;"></div>
    </form>
</div>
<?php

return ob_get_clean();
    }
    
    /**
     * Handle deletion request form submission
     */
    public function handle_deletion_request_submission() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'sentinel_deletion_request')) {
            wp_send_json_error(array('message' => 'Security check failed.'));
        }
        
        // Check if user is logged in
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'You must be logged in to submit this request.'));
        }
        
        // Check if Right to be Forgotten is enabled
        $settings = get_option('sentinel_log_management', array());
        if (empty($settings['right_to_be_forgotten'])) {
            wp_send_json_error(array('message' => 'Data deletion requests are currently disabled.'));
        }
        
        // Validate form data
        $user_id = get_current_user_id();
        $reason = sanitize_text_field($_POST['reason']);
        $details = sanitize_textarea_field($_POST['details']);
        $confirm = isset($_POST['confirm']) && $_POST['confirm'] === 'true';
        
        if (empty($reason)) {
            wp_send_json_error(array('message' => 'Please select a reason for your request.'));
        }
        
        if (!$confirm) {
            wp_send_json_error(array('message' => 'You must confirm that you understand the implications of this request.'));
        }
        
        // Check if user already has a pending request
        if ($this->user_has_pending_request($user_id)) {
            wp_send_json_error(array('message' => 'You already have a pending data deletion request.'));
        }
        
        // Rate limiting: prevent spam requests (max 1 per 24 hours)
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        $recent_requests = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
            WHERE user_id = %d 
            AND event_key = 'user_deletion_request' 
            AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)",
            $user_id
        ));
        
        if ($recent_requests > 0) {
            wp_send_json_error(array('message' => 'You can only submit one deletion request per 24 hours.'));
        }
        
        // Log the deletion request
        $request_data = array(
            'user_id' => $user_id,
            'reason' => $reason,
            'details' => $details,
            'status' => 'pending',
            'request_date' => current_time('mysql')
        );
        
        $logged = sentinel_log_event('user_deletion_request', $request_data, $user_id);
        
        if ($logged) {
            wp_send_json_success(array(
                'message' => 'Your data deletion request has been submitted successfully. An administrator will review your request and you will be notified of the outcome.'
            ));
        } else {
            wp_send_json_error(array('message' => 'Failed to submit your request. Please try again.'));
        }
    }
    
    /**
     * Check if user has a pending deletion request
     * 
     * @param int $user_id User ID to check
     * @return bool True if user has pending request
     */
    private function user_has_pending_request($user_id) {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        $pending_request = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table 
             WHERE event_key = 'user_deletion_request' 
             AND user_id = %d 
             AND data LIKE %s",
            $user_id, '%"status":"pending"%'
        ));
        
        return $pending_request > 0;
    }
    
    /**
     * Handle admin processing of deletion requests (approve/deny)
     */
    public function handle_admin_process_deletion_request() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'sentinel_process_deletion_request')) {
            wp_send_json_error(array('message' => 'Security check failed.'));
        }
        
        // Check if user is admin
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Insufficient permissions.'));
        }
        
        // Validate input
        $log_id = isset($_POST['log_id']) ? intval($_POST['log_id']) : 0;
        $action = isset($_POST['request_action']) ? sanitize_text_field($_POST['request_action']) : '';
        $admin_notes = isset($_POST['admin_notes']) ? sanitize_textarea_field($_POST['admin_notes']) : '';
        
        if (!$log_id || !in_array($action, array('approve', 'deny'))) {
            wp_send_json_error(array('message' => 'Invalid request parameters.'));
        }
        
        // Get the log entry
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        $log = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id = %d", $log_id));
        
        if (!$log || $log->event_key !== 'user_deletion_request') {
            wp_send_json_error(array('message' => 'Invalid log entry.'));
        }
        
        // Check if user still exists
        $user = get_user_by('id', $log->user_id);
        if (!$user) {
            wp_send_json_error(array('message' => 'User account no longer exists.'));
        }
        
        // Parse existing data
        $data = json_decode($log->data, true);
        if (!is_array($data)) {
            $data = array();
        }
        
        // Check if already processed
        if (isset($data['status']) && $data['status'] !== 'pending') {
            wp_send_json_error(array('message' => 'Request has already been processed.'));
        }
        
        // Update the request data
        $data['status'] = $action === 'approve' ? 'approved' : 'denied';
        $data['processed_date'] = current_time('mysql');
        $data['processed_by'] = wp_get_current_user()->display_name;
        if (!empty($admin_notes)) {
            $data['admin_notes'] = $admin_notes;
        }
        
        // Update the log entry
        $updated = $wpdb->update(
            $table,
            array('data' => json_encode($data)),
            array('id' => $log_id),
            array('%s'),
            array('%d')
        );
        
        if ($updated === false) {
            wp_send_json_error(array('message' => 'Failed to update request status.'));
        }
        
        // If approved, anonymize the user's data
        if ($action === 'approve') {
            $anonymization_result = self::anonymize_user_data($log->user_id, 'admin_approved');
            
            // Log the anonymization action
            sentinel_log_event('user_data_anonymized', array(
                'user_id' => $log->user_id,
                'reason' => 'admin_approved',
                'request_log_id' => $log_id,
                'anonymized_count' => $anonymization_result['anonymized_count'],
                'summary' => $anonymization_result['summary']
            ));
        }
        
        // Log the admin action
        sentinel_log_event('admin_deletion_request_processed', array(
            'request_log_id' => $log_id,
            'user_id' => $log->user_id,
            'action' => $action,
            'admin_notes' => $admin_notes
        ));
        
        wp_send_json_success(array(
            'message' => 'Request ' . ($action === 'deny' ? 'denied' : $action . 'd') . ' successfully.',
            'status' => $data['status']
        ));
    }
    
    /**
     * Anonymize user data from logs
     * 
     * @param int $user_id User ID to anonymize
     * @param string $reason Reason for anonymization
     * @return array Result information
     */
    public static function anonymize_user_data($user_id, $reason = 'deletion_request') {
        global $wpdb;
        $tables = array(
            $wpdb->prefix . 'sentinel_logs',
            $wpdb->prefix . 'sentinel_logs_archive'
        );
        
        $anonymized_count = 0;
        $summary = array();
        
        foreach ($tables as $table) {
            // Get all logs for this user
            $user_logs = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM $table WHERE user_id = %d",
                $user_id
            ));
            
            $table_anonymized = 0;
            
            foreach ($user_logs as $log) {
                // Skip if already anonymized
                if (strpos($log->ip_address, '.xxx.xxx') !== false) {
                    continue;
                }
                
                // Anonymize IP address
                $anonymized_ip = $log->ip_address;
                if (!empty($anonymized_ip) && filter_var($anonymized_ip, FILTER_VALIDATE_IP)) {
                    $parts = explode('.', $anonymized_ip);
                    if (count($parts) === 4) {
                        $anonymized_ip = $parts[0] . '.' . $parts[1] . '.xxx.xxx';
                    }
                }
                
                // Anonymize data field
                $anonymized_data = $log->data;
                if (!empty($anonymized_data)) {
                    $data_arr = json_decode($anonymized_data, true);
                    if (is_array($data_arr)) {
                        // Anonymize email addresses
                        if (isset($data_arr['email']) && is_string($data_arr['email'])) {
                            $email = $data_arr['email'];
                            $at = strpos($email, '@');
                            if ($at !== false && $at > 0) {
                                $user = substr($email, 0, 1) . 'xxx';
                                $domain = substr($email, $at + 1);
                                $dot = strpos($domain, '.');
                                if ($dot !== false && $dot > 0) {
                                    $domain_part = substr($domain, 0, 1) . 'xxxx';
                                    $tld = substr($domain, $dot);
                                    $data_arr['email'] = $user . '@' . $domain_part . $tld;
                                } else {
                                    $data_arr['email'] = $user . '@xxxx';
                                }
                            } else {
                                $data_arr['email'] = 'xxx';
                            }
                        }
                        
                        // Anonymize usernames
                        if (isset($data_arr['username']) && is_string($data_arr['username'])) {
                            $uname = $data_arr['username'];
                            $data_arr['username'] = substr($uname, 0, 1) . 'xxx';
                        }
                        
                        // Anonymize user_login
                        if (isset($data_arr['user_login']) && is_string($data_arr['user_login'])) {
                            $login = $data_arr['user_login'];
                            $data_arr['user_login'] = substr($login, 0, 1) . 'xxx';
                        }
                        
                        // Anonymize display_name
                        if (isset($data_arr['display_name']) && is_string($data_arr['display_name'])) {
                            $display = $data_arr['display_name'];
                            $data_arr['display_name'] = substr($display, 0, 1) . 'xxx';
                        }
                        
                        $anonymized_data = json_encode($data_arr);
                    }
                }
                
                // Update the log entry
                $updated = $wpdb->update(
                    $table,
                    array(
                        'ip_address' => $anonymized_ip,
                        'data' => $anonymized_data
                    ),
                    array('id' => $log->id),
                    array('%s', '%s'),
                    array('%d')
                );
                
                if ($updated !== false) {
                    $table_anonymized++;
                }
            }
            
            $anonymized_count += $table_anonymized;
            $summary[$table] = $table_anonymized;
        }
        
        // Log the anonymization action
        sentinel_log_event('user_data_anonymized', array(
            'user_id' => $user_id,
            'reason' => $reason,
            'anonymized_count' => $anonymized_count,
            'summary' => $summary
        ));
        
        return array(
            'success' => true,
            'anonymized_count' => $anonymized_count,
            'summary' => $summary
        );
    }
    
    /**
     * Add dashboard widget for pending deletion requests
     */
    public function add_dashboard_widget() {
        // Only show to users who can manage options
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Check if Right to be Forgotten is enabled
        $settings = get_option('sentinel_log_management', array());
        if (empty($settings['right_to_be_forgotten'])) {
            return;
        }
        
        wp_add_dashboard_widget(
            'sentinel_privacy_widget',
            '🔒 Pending Data Deletion Requests',
            array($this, 'render_dashboard_widget')
        );
    }
    
    /**
     * Render the dashboard widget content
     */
    public function render_dashboard_widget() {
        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';
        
        // Get pending deletion requests
        $pending_requests = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table 
            WHERE event_key = 'user_deletion_request' 
            AND data LIKE %s 
            ORDER BY created_at DESC 
            LIMIT 10",
            '%"status":"pending"%'
        ));
        
        ob_start();
        if (empty($pending_requests)) {
            echo '<div class="sentinel-privacy-widget-empty"><span class="dashicons dashicons-lock"></span> No pending data deletion requests.</div>';
        } else {
            echo '<div class="sentinel-privacy-widget-list">';
            foreach ($pending_requests as $request) {
                $data = json_decode($request->data, true);
                $user = get_user_by('id', $request->user_id);
                $username = $user ? $user->display_name : 'Unknown User (ID: ' . $request->user_id . ')';
                $request_date = date('M j, Y g:i A', strtotime($request->created_at));
                $reason = isset($data['reason']) ? ucfirst(str_replace('_', ' ', $data['reason'])) : 'No reason provided';
                $details = !empty($data['details']) ? esc_html(substr($data['details'], 0, 100)) . (strlen($data['details']) > 100 ? '...' : '') : '';
                ?>
<div class="sentinel-privacy-widget-card">
    <div class="sentinel-privacy-widget-card-header">
        <span class="dashicons dashicons-admin-users sentinel-privacy-widget-usericon"></span>
        <span class="sentinel-privacy-widget-username"><?php echo esc_html($username); ?></span>
        <span class="sentinel-privacy-widget-date"><?php echo esc_html($request_date); ?></span>
    </div>
    <div class="sentinel-privacy-widget-reason"><strong>Reason:</strong> <?php echo esc_html($reason); ?></div>
    <?php if ($details): ?>
    <div class="sentinel-privacy-widget-details"><?php echo $details; ?></div>
    <?php endif; ?>
</div>
<?php
            }
            echo '</div>';
            ?>
<div class="sentinel-privacy-widget-footer">
    <a href="<?php echo admin_url('admin.php?page=sentinel-logs&event_filter=user_deletion_request'); ?>"
        class="button button-primary">Review Requests</a>
</div>
<?php
        }
        echo ob_get_clean();
    }
} 