<?php
/**
 * Gestion de la confidentialité (RGPD / WP Privacy Tools)
 *
 * Enregistre l'exportateur, l'effaceur et le texte de politique de confidentialité.
 *
 * @package SlideMind\Core
 * @since 2.8.0
 */

namespace SlideMind\Core;

if (!defined('ABSPATH')) {
    exit;
}

class Privacy {

    /**
     * @var LearnerMemory
     */
    private $learner_memory;

    /**
     * Constructeur
     *
     * @param LearnerMemory $learner_memory
     */
    public function __construct(LearnerMemory $learner_memory) {
        $this->learner_memory = $learner_memory;
    }

    /**
     * Enregistre les hooks WordPress privacy
     */
    public function register_hooks(): void {
        add_filter('wp_privacy_personal_data_exporters', [$this, 'register_exporter']);
        add_filter('wp_privacy_personal_data_erasers',   [$this, 'register_eraser']);
        add_action('admin_init', [$this, 'add_privacy_policy_content']);
    }

    /**
     * Enregistre l'exportateur de données personnelles
     *
     * @param array $exporters
     * @return array
     */
    public function register_exporter(array $exporters): array {
        $exporters['slidemind'] = [
            'exporter_friendly_name' => __('SlideMind Learner Memory', 'slidemind'),
            'callback'               => [$this, 'export_user_data'],
        ];
        return $exporters;
    }

    /**
     * Exporte les données personnelles d'un apprenant
     *
     * @param string $email
     * @param int    $page
     * @return array
     */
    public function export_user_data(string $email, int $page = 1): array {
        $user = get_user_by('email', $email);

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

        global $wpdb;
        $table = $wpdb->prefix . 'slidemind_learner_memory';

        // phpcs:disable WordPress.DB.DirectDatabaseQuery
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT scope, scope_id, variable_name, variable_value, updated_at FROM %i WHERE wp_user_id = %d ORDER BY scope, variable_name",
                $table,
                $user->ID
            ),
            ARRAY_A
        );
        // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

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

        $data = [];
        foreach ($rows as $row) {
            $data[] = [
                'group_id'    => 'slidemind-learner-memory',
                'group_label' => __('SlideMind Learner Memory', 'slidemind'),
                'item_id'     => 'sm-memory-' . $row['scope'] . '-' . $row['scope_id'] . '-' . sanitize_key($row['variable_name']),
                'data'        => [
                    [
                        'name'  => __('Scope', 'slidemind'),
                        'value' => esc_html($row['scope']),
                    ],
                    [
                        'name'  => __('Variable name', 'slidemind'),
                        'value' => esc_html($row['variable_name']),
                    ],
                    [
                        'name'  => __('Value', 'slidemind'),
                        'value' => esc_html($row['variable_value']),
                    ],
                    [
                        'name'  => __('Last updated', 'slidemind'),
                        'value' => esc_html($row['updated_at']),
                    ],
                ],
            ];
        }

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

    /**
     * Enregistre l'effaceur de données personnelles
     *
     * @param array $erasers
     * @return array
     */
    public function register_eraser(array $erasers): array {
        $erasers['slidemind'] = [
            'eraser_friendly_name' => __('SlideMind Learner Memory', 'slidemind'),
            'callback'             => [$this, 'erase_user_data'],
        ];
        return $erasers;
    }

    /**
     * Efface les données personnelles d'un apprenant
     *
     * @param string $email
     * @param int    $page
     * @return array
     */
    public function erase_user_data(string $email, int $page = 1): array {
        $user = get_user_by('email', $email);

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

        $deleted = $this->learner_memory->purge_user($user->ID);

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

    /**
     * Ajoute le texte de politique de confidentialité suggéré
     *
     * Ce texte est une suggestion à l'intention de l'administrateur du site — il lui appartient
     * de l'intégrer dans sa propre politique de confidentialité et de l'adapter à sa situation.
     * SlideMind/Zaprène est un fournisseur d'outil et n'assume aucune responsabilité quant à
     * l'utilisation du plugin ou au choix du fournisseur d'IA par le client.
     */
    public function add_privacy_policy_content(): void {
        if (!function_exists('wp_add_privacy_policy_content')) {
            return;
        }

        $content = '<h2>' . esc_html__('AI-assisted interactions (SlideMind)', 'slidemind') . '</h2>';

        $content .= '<p>' . esc_html__(
            'This site uses SlideMind, a plugin that enables AI-assisted interactions in e-learning modules. When you interact with an AI assistant, your messages and certain profile variables may be sent to the AI provider configured by this site\'s administrator.',
            'slidemind'
        ) . '</p>';

        $content .= '<p>' . esc_html__(
            'This site\'s administrator is responsible for the processing of your personal data and for compliance with applicable privacy laws.',
            'slidemind'
        ) . '</p>';

        $content .= '<h3>' . esc_html__('Data collected', 'slidemind') . '</h3>';
        $content .= '<ul>';
        $content .= '<li>' . esc_html__(
            'Conversation messages you send to the AI assistant.',
            'slidemind'
        ) . '</li>';
        $content .= '<li>' . esc_html__(
            'Profile variables resolved from your user account (such as name, role, or LMS-specific fields), if configured by the administrator.',
            'slidemind'
        ) . '</li>';
        $content .= '<li>' . esc_html__(
            'Memory variables stored between sessions to personalize your learning experience.',
            'slidemind'
        ) . '</li>';
        $content .= '</ul>';

        $content .= '<h3>' . esc_html__('Data transmission', 'slidemind') . '</h3>';
        $content .= '<p>' . esc_html__(
            'Your messages are transmitted to the AI provider configured by this site\'s administrator (such as OpenRouter or another LLM service). This site\'s administrator is solely responsible for their choice of AI provider and for ensuring that provider\'s compliance with applicable laws.',
            'slidemind'
        ) . '</p>';

        $content .= '<h3>' . esc_html__('Your rights', 'slidemind') . '</h3>';
        $content .= '<p>' . esc_html__(
            'You may request export or erasure of the memory variables stored about you using the personal data tools available on this site (Tools > Export Personal Data / Erase Personal Data in the WordPress administration).',
            'slidemind'
        ) . '</p>';

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