<?php
/**
 * Privacy / GDPR Compliance Dashboard.
 *
 * Stärkt unseren EU-USP: kein Wettbewerber bietet ein dediziertes
 * DSGVO-Workflow-Center.
 *
 * Features:
 * - „Datenkarte" — welche Plugins speichern welche personenbezogenen Daten
 *   (Liste aller bekannten PII-Tabellen: wp_users, wp_usermeta, wp_comments,
 *    wp_woocommerce_*, wp_school_*, Sessions, IP-Logs etc.)
 * - DSGVO Art. 15 (Auskunft) — One-Click-Export aller Daten zu einer Mail
 * - DSGVO Art. 17 (Löschung) — One-Click-Lösch-Workflow (nutzt WP-Core erase)
 * - DSGVO Art. 20 (Übertragung) — portables JSON
 * - „Letzter Audit" Zeitstempel + Audit-Trail
 *
 * Nutzt WP-Core Privacy-Tools (Tools → Erase Personal Data + Export Personal
 * Data), bietet aber UI-First-Workflow + zusätzliche Daten-Map.
 *
 * @package Brainwerk Security Suite
 */

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

class Shieldforge_Privacy_Dashboard {

    public static function register( Shieldforge_Loader $loader ) {
        $loader->add_action( 'admin_post_shieldforge_privacy_export', __CLASS__, 'handle_export' );
        $loader->add_action( 'admin_post_shieldforge_privacy_erase',  __CLASS__, 'handle_erase' );
    }

    /**
     * Scannt die DB nach allen Stellen wo personenbezogene Daten liegen.
     * Returnt eine kategorisierte Liste — basis für die „Datenkarte".
     */
    public static function data_map() {
        global $wpdb;
        $map = array(
            array( 'category' => 'WordPress Core', 'table' => $wpdb->users,       'fields' => array( 'user_email', 'user_login', 'user_registered', 'user_url', 'display_name' ), 'lawful_basis' => __( 'Vertrag (Schul-Anmeldung) bzw. berechtigtes Interesse (Admin-Konten)', 'brainwerk-security-suite' ) ),
            array( 'category' => 'WordPress Core', 'table' => $wpdb->usermeta,    'fields' => array( 'meta_key', 'meta_value (kann PII enthalten)' ), 'lawful_basis' => __( 'Vertrag', 'brainwerk-security-suite' ) ),
            array( 'category' => 'WordPress Core', 'table' => $wpdb->comments,    'fields' => array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' ), 'lawful_basis' => __( 'Einwilligung des Kommentierenden', 'brainwerk-security-suite' ) ),
            // Brainwerk Security Suite selbst
            array( 'category' => 'Brainwerk Security Suite', 'table' => $wpdb->base_prefix . 'shieldforge_logins',    'fields' => array( 'username', 'ip_anon', 'user_agent' ), 'retention_days' => 30,  'lawful_basis' => __( 'Berechtigtes Interesse (Brute-Force-Schutz, Art. 6 Abs. 1 lit. f DSGVO)', 'brainwerk-security-suite' ) ),
            array( 'category' => 'Brainwerk Security Suite', 'table' => $wpdb->base_prefix . 'shieldforge_blocks',    'fields' => array( 'ip', 'reason' ), 'retention_days' => 90, 'lawful_basis' => __( 'Berechtigtes Interesse', 'brainwerk-security-suite' ) ),
            array( 'category' => 'Brainwerk Security Suite', 'table' => $wpdb->base_prefix . 'shieldforge_audit_log', 'fields' => array( 'user_id', 'ip_anon', 'action', 'object' ), 'retention_days' => 90, 'lawful_basis' => __( 'Rechtliche Verpflichtung (Nachvollziehbarkeit Admin-Aktionen)', 'brainwerk-security-suite' ) ),
            // SEOForge (falls aktiv)
            array( 'category' => 'SEOForge (Analytics)', 'table' => 'wp_seoforge_visits', 'fields' => array( 'ip_anon', 'visitor_hash', 'user_agent', 'referrer_url' ), 'retention_days' => 180, 'lawful_basis' => __( 'Berechtigtes Interesse (Reichweitenmessung, anonymisiert)', 'brainwerk-security-suite' ), 'optional' => true ),
            // Schul-Anmeldung
            array( 'category' => 'Schul-Anmeldung', 'table' => 'wp_postmeta (key LIKE _anm_*)', 'fields' => array( 'AES-256-verschlüsselte Personendaten (Kind, Eltern, Adressen, Scans)' ), 'retention_days' => 180, 'lawful_basis' => __( 'Vertrag (Schulanmeldung)', 'brainwerk-security-suite' ), 'optional' => true ),
        );

        // Live-Counts holen (defensive — bei fehlender Tabelle 0)
        foreach ( $map as &$entry ) {
            if ( false !== strpos( (string) $entry['table'], 'LIKE' ) ) { $entry['rows'] = 'n/a'; continue; }
            $count = self::safe_count( "SELECT COUNT(*) FROM `{$entry['table']}`" );
            $entry['rows'] = $count;
        }
        return $map;
    }

    private static function safe_count( $sql ) {
        global $wpdb;
        $prev = $wpdb->hide_errors();
        // $sql is built internally from a fixed table-name map (see collect_tables), never from user input.
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom security table; direct live read by design; not cacheable.
        $v = (int) $wpdb->get_var( $sql );
        if ( $prev ) $wpdb->show_errors();
        return $v;
    }

    /**
     * DSGVO Art. 15 (Auskunft) — bündelt alle Personendaten zu einer Mail-Adresse
     * in ein portables JSON. Re-nutzt das WP-Core Privacy-Export-Framework
     * (wp_privacy_personal_data_export_file) für maximale Plugin-Abdeckung.
     */
    public static function handle_export() {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( '403', 403 );
        check_admin_referer( 'shieldforge_privacy_export' );
        $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
        if ( ! is_email( $email ) ) wp_die( esc_html__( 'Bitte gültige E-Mail-Adresse angeben.', 'brainwerk-security-suite' ), 400 );
        // Triggert WP-Core Privacy-Export — User bekommt Bestätigungs-Mail mit Download-Link
        $request_id = wp_create_user_request( $email, 'export_personal_data' );
        if ( is_wp_error( $request_id ) ) wp_die( esc_html( $request_id->get_error_message() ), 400 );
        wp_send_user_request( $request_id );
        wp_safe_redirect( add_query_arg( 'shieldforge_privacy_msg', 'export_sent', wp_get_referer() ?: admin_url() ) );
        exit;
    }

    /**
     * DSGVO Art. 17 (Löschung) — startet Lösch-Workflow für eine Mail-Adresse.
     */
    public static function handle_erase() {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( '403', 403 );
        check_admin_referer( 'shieldforge_privacy_erase' );
        $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
        if ( ! is_email( $email ) ) wp_die( esc_html__( 'Bitte gültige E-Mail-Adresse angeben.', 'brainwerk-security-suite' ), 400 );
        $request_id = wp_create_user_request( $email, 'remove_personal_data' );
        if ( is_wp_error( $request_id ) ) wp_die( esc_html( $request_id->get_error_message() ), 400 );
        wp_send_user_request( $request_id );
        wp_safe_redirect( add_query_arg( 'shieldforge_privacy_msg', 'erase_sent', wp_get_referer() ?: admin_url() ) );
        exit;
    }
}
