<?php
/**
 * GDPR / RGPD personal data exporter integration.
 *
 * When a customer requests their personal data via WordPress's built-in export tool
 * (Tools > Export Personal Data), we contribute the list of invoices and credit notes
 * associated with that email address. The customer receives the data in the standard
 * WP archive ZIP alongside the rest of their personal information.
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

class GOFACTOX_GDPR {

    public static function init(): void {
        add_filter( 'wp_privacy_personal_data_exporters', [ __CLASS__, 'register_exporter' ] );
        add_filter( 'wp_privacy_personal_data_erasers', [ __CLASS__, 'register_eraser' ] );
    }

    /**
     * Register the exporter with WordPress.
     */
    public static function register_exporter( array $exporters ): array {
        $exporters['gofactox-invoices'] = [
            'exporter_friendly_name' => __( 'GoFactoX Invoices and Credit Notes', 'gofactox-e-invoicing-for-woocommerce' ),
            'callback'               => [ __CLASS__, 'export_personal_data' ],
        ];
        return $exporters;
    }

    /**
     * Register the eraser (anonymises invoices linked to the email).
     *
     * Invoices themselves are kept (legal retention obligation: 10 years per Code
     * de commerce L123-22) but customer-identifying metadata can be cleared.
     */
    public static function register_eraser( array $erasers ): array {
        $erasers['gofactox-invoices'] = [
            'eraser_friendly_name' => __( 'GoFactoX Invoices and Credit Notes', 'gofactox-e-invoicing-for-woocommerce' ),
            'callback'             => [ __CLASS__, 'erase_personal_data' ],
        ];
        return $erasers;
    }

    /**
     * Build the export entries for one user's email.
     *
     * @param string $email_address Customer email.
     * @param int    $page          Page number (we paginate by 50).
     * @return array{data:array, done:bool}
     */
    public static function export_personal_data( string $email_address, int $page = 1 ): array {
        $per_page = 50;
        $page     = max( 1, $page );

        $orders = wc_get_orders( [
            'limit'         => $per_page,
            'paged'         => $page,
            'billing_email' => $email_address,
            'type'          => 'shop_order',
            'return'        => 'objects',
        ] );

        $export_items = [];

        foreach ( $orders as $order ) {
            if ( ! $order instanceof \WC_Order ) {
                continue;
            }

            $invoice_number = (string) $order->get_meta( '_gofactox_invoice_number' );
            if ( $invoice_number ) {
                $invoice_id   = (int) $order->get_meta( '_gofactox_invoice_id' );
                $invoice_date = (string) get_post_meta( $invoice_id, '_gofactox_invoice_date', true );

                $export_items[] = [
                    'group_id'    => 'gofactox-invoices',
                    'group_label' => __( 'GoFactoX Invoices', 'gofactox-e-invoicing-for-woocommerce' ),
                    'item_id'     => 'invoice-' . $invoice_id,
                    'data'        => [
                        [ 'name' => __( 'Invoice number', 'gofactox-e-invoicing-for-woocommerce' ), 'value' => $invoice_number ],
                        [ 'name' => __( 'Invoice date', 'gofactox-e-invoicing-for-woocommerce' ), 'value' => $invoice_date ],
                        [ 'name' => __( 'Order', 'gofactox-e-invoicing-for-woocommerce' ), 'value' => $order->get_order_number() ],
                        [ 'name' => __( 'Total (TTC)', 'gofactox-e-invoicing-for-woocommerce' ), 'value' => sprintf( '%s %s', number_format( (float) $order->get_total(), 2, '.', ' ' ), $order->get_currency() ) ],
                    ],
                ];
            }

            foreach ( $order->get_refunds() as $refund ) {
                if ( ! $refund instanceof \WC_Order_Refund ) {
                    continue;
                }
                $cn_number = (string) $refund->get_meta( '_gofactox_credit_note_number' );
                if ( ! $cn_number ) {
                    continue;
                }
                $cn_id = (int) $refund->get_meta( '_gofactox_credit_note_id' );
                $cn_date = (string) get_post_meta( $cn_id, '_gofactox_invoice_date', true );

                $export_items[] = [
                    'group_id'    => 'gofactox-credit-notes',
                    'group_label' => __( 'GoFactoX Credit Notes', 'gofactox-e-invoicing-for-woocommerce' ),
                    'item_id'     => 'credit-note-' . $cn_id,
                    'data'        => [
                        [ 'name' => __( 'Credit note number', 'gofactox-e-invoicing-for-woocommerce' ), 'value' => $cn_number ],
                        [ 'name' => __( 'Credit note date', 'gofactox-e-invoicing-for-woocommerce' ), 'value' => $cn_date ],
                        [ 'name' => __( 'Original invoice', 'gofactox-e-invoicing-for-woocommerce' ), 'value' => (string) $order->get_meta( '_gofactox_invoice_number' ) ],
                        [ 'name' => __( 'Refund total', 'gofactox-e-invoicing-for-woocommerce' ), 'value' => sprintf( '%s %s', number_format( abs( (float) $refund->get_total() ), 2, '.', ' ' ), $order->get_currency() ) ],
                    ],
                ];
            }
        }

        return [
            'data' => $export_items,
            'done' => count( $orders ) < $per_page,
        ];
    }

    /**
     * Anonymise invoices linked to an email. Invoices are kept for 10 years (legal
     * retention) but customer-identifying metadata on the source order is wiped
     * separately by WooCommerce's own eraser, so we just acknowledge here.
     */
    public static function erase_personal_data( string $email_address, int $page = 1 ): array {
        return [
            'items_removed'  => false,
            'items_retained' => true,
            'messages'       => [
                __( 'Invoices and credit notes are retained for the legal 10-year period (article L123-22 of the French Commercial Code). Customer-identifying data on the original orders is erased separately by WooCommerce.', 'gofactox-e-invoicing-for-woocommerce' ),
            ],
            'done'           => true,
        ];
    }
}
