<?php
namespace Kitgenix\PDF_Invoicing\Modules\Settings;

defined( 'ABSPATH' ) || exit;

/**
 * Simple per-plugin activity log for Kitgenix PDF Invoicing for WooCommerce.
 *
 * Records admin actions (settings saves, invoice generation events, PDF errors,
 * bulk operations) to a capped WP option visible in the admin Log tab.
 *
 * Storage format (per entry):
 *   [ 'time' => int, 'context' => string, 'outcome' => string, 'note' => string, 'code' => string ]
 */
final class Event_Log {

    private const OPTION_KEY  = 'kitgenix_pdf_invoicing_event_log';
    private const MAX_ENTRIES = 100;

    /**
     * Record an event to the log.
     *
     * @param string $context  Short slug (e.g. 'settings-saved', 'invoice-generated', 'pdf-error').
     * @param string $outcome  'success', 'error', or any short outcome label.
     * @param string $note     Optional plain-English detail (e.g. order ID, error message).
     * @param string $code     Optional structured event code, mapped via get_category_and_note().
     */
    public static function record( string $context, string $outcome, string $note = '', string $code = '' ): void {
        $log   = self::get_raw_log();
        $log[] = [
            'time'    => time(),
            'context' => sanitize_text_field( $context ),
            'outcome' => sanitize_text_field( $outcome ),
            'note'    => sanitize_text_field( $note ),
            'code'    => sanitize_key( $code ),
        ];

        if ( count( $log ) > self::MAX_ENTRIES ) {
            $log = array_slice( $log, -self::MAX_ENTRIES );
        }

        update_option( self::OPTION_KEY, $log, false );
    }

    /**
     * Map a structured event code to a short category slug and a plain-English hint note.
     *
     * Lets the admin Log tab distinguish genuine problems (needs action) from likely
     * false positives / expected skips (usually not a problem) at a glance.
     *
     * @return array{category: string, note: string}
     */
    public static function get_category_and_note( string $code ): array {
        $map = [
            'settings-saved' => [
                'category' => 'settings-saved',
                'note'     => __( 'Plugin settings were updated by an administrator.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],

            // Genuine problems – needs action.
            'dompdf_render_failed' => [
                'category' => 'render-error',
                'note'     => __( 'The PDF renderer failed unexpectedly while generating this document. If this repeats, the order content or a custom template may be malformed.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],
            'dir_resolve_failed' => [
                'category' => 'storage-error',
                'note'     => __( 'The plugin could not resolve its archive storage directory inside your WordPress uploads folder.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],
            'mkdir_failed' => [
                'category' => 'storage-error',
                'note'     => __( 'The plugin could not create its archive storage folder. Check file system permissions on the uploads directory.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],
            'write_failed' => [
                'category' => 'storage-error',
                'note'     => __( 'The plugin could not write the generated PDF file to disk. Check available disk space and folder permissions.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],
            'attachment_generation_failed' => [
                'category' => 'email-attachment-missing',
                'note'     => __( 'A WooCommerce email was sent without its PDF attachment because the document could not be generated. Check the log around the same time for the underlying PDF generation error.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],
            'generation_failed' => [
                'category' => 'generation-failed',
                'note'     => __( 'The PDF could not be generated for this order during a bulk operation. Check the log around the same time for the underlying error.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],

            // Likely false positives / expected – usually not a problem.
            'dompdf_resource_limit' => [
                'category' => 'resource-limit',
                'note'     => __( 'PDF generation hit a PHP memory or time limit – likely just a very large order, not necessarily a bug. If this repeats, raise PHP memory_limit and max_execution_time.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],
            'order_not_found' => [
                'category' => 'order-not-found',
                'note'     => __( 'A selected order no longer exists (it may have been deleted). This is expected – the order was skipped automatically.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],
            'not_eligible' => [
                'category' => 'not-eligible',
                'note'     => __( 'The order was skipped because this document type does not apply to it (for example, a credit note requested for an order with no refunds). This is expected behavior.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
            ],
        ];

        if ( isset( $map[ $code ] ) ) {
            return $map[ $code ];
        }

        return [
            'category' => '' !== $code ? $code : 'unspecified',
            'note'     => __( 'No further detail is available for this event.', 'kitgenix-pdf-invoicing-for-woocommerce' ),
        ];
    }

    /**
     * Return all stored entries (oldest first).
     *
     * @return array<int,array<string,mixed>>
     */
    public static function get_raw_log(): array {
        $log = get_option( self::OPTION_KEY, [] );
        return is_array( $log ) ? $log : [];
    }

    /** Delete all stored entries. */
    public static function clear(): void {
        delete_option( self::OPTION_KEY );
    }

    /**
     * Return the log as a formatted multi-line string for the admin textarea.
     */
    public static function get_log_text(): string {
        $entries = self::get_raw_log();
        if ( empty( $entries ) ) {
            return __( 'No recent events recorded yet.', 'kitgenix-pdf-invoicing-for-woocommerce' );
        }

        $format = (string) get_option( 'date_format' ) . ' ' . (string) get_option( 'time_format' );
        $lines  = [ '# Columns: timestamp | context | outcome | note' ];

        foreach ( array_reverse( $entries ) as $entry ) {
            $time = isset( $entry['time'] ) ? (int) $entry['time'] : 0;
            if ( function_exists( 'wp_date' ) ) {
                $when = $time ? (string) wp_date( $format, $time ) : '';
            } else {
                $when = $time ? (string) date_i18n( $format, $time ) : '';
            }

            $lines[] = sprintf(
                '%1$s | %2$s | %3$s | %4$s',
                $when ?: __( 'Unknown time', 'kitgenix-pdf-invoicing-for-woocommerce' ),
                (string) ( $entry['context'] ?? '' ),
                (string) ( $entry['outcome'] ?? '' ),
                (string) ( $entry['note']    ?? '' )
            );
        }

        return implode( "\n", $lines );
    }
}
