<?php
/**
 * Bounded, privacy-safe operational health history.
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class YATOON_Health_History {
    const OPTION = 'yatoon_health_history_v1';
    const LIMIT  = 250;

    public static function record( $kind, array $health ) {
        $entry = array(
            'kind'        => sanitize_key( $kind ),
            'status'      => sanitize_key( $health['status'] ?? 'unknown' ),
            'checked_at'  => sanitize_text_field( $health['checked_at'] ?? current_time( 'mysql' ) ),
            'duration_ms' => absint( $health['duration_ms'] ?? 0 ),
            'attempt'     => absint( $health['attempt'] ?? 0 ),
            'updated'     => absint( $health['updated'] ?? 0 ),
            'inserted'    => absint( $health['inserted'] ?? 0 ),
            'cancelled'   => absint( $health['cancelled'] ?? 0 ),
            'error'       => sanitize_text_field( $health['error'] ?? '' ),
        );
        $history = (array) get_option( self::OPTION, array() );
        $history[] = $entry;
        if ( count( $history ) > self::LIMIT ) {
            $history = array_slice( $history, -self::LIMIT );
        }
        update_option( self::OPTION, $history, false );
    }

    public static function recent( $days = 7 ) {
        $cutoff = time() - max( 1, absint( $days ) ) * DAY_IN_SECONDS;
        return array_values( array_filter( (array) get_option( self::OPTION, array() ), static function ( $entry ) use ( $cutoff ) {
            $time = strtotime( (string) ( $entry['checked_at'] ?? '' ) );
            return $time && $time >= $cutoff;
        } ) );
    }

    public static function summary( $days = 7 ) {
        $summary = array( 'total' => 0, 'success' => 0, 'failed' => 0, 'retry' => 0, 'average_ms' => 0 );
        $duration_total = 0;
        $duration_count = 0;
        foreach ( self::recent( $days ) as $entry ) {
            ++$summary['total'];
            $status = sanitize_key( $entry['status'] ?? '' );
            if ( in_array( $status, array( 'ok', 'ok_after_retry', 'ignored', 'duplicate' ), true ) ) {
                ++$summary['success'];
            } elseif ( false !== strpos( $status, 'retry' ) ) {
                ++$summary['retry'];
            } elseif ( 'failed' === $status ) {
                ++$summary['failed'];
            }
            if ( ! empty( $entry['duration_ms'] ) ) {
                $duration_total += absint( $entry['duration_ms'] );
                ++$duration_count;
            }
        }
        $summary['average_ms'] = $duration_count ? (int) round( $duration_total / $duration_count ) : 0;
        return $summary;
    }

    public static function technical_summary( array $checks = array() ) {
        $sync = (array) get_option( 'yatoon_square_sync_health', array() );
        $webhook = (array) get_option( 'yatoon_square_webhook_health', array() );
        $failed = array_values( array_map( static function ( $check ) {
            return (string) ( $check['label'] ?? '' );
        }, array_filter( $checks, static function ( $check ) {
            return empty( $check['ok'] );
        } ) ) );
        return implode( "\n", array(
            'Yatoon ' . ( defined( 'YATOON_VERSION' ) ? YATOON_VERSION : '-' ) . ' / DB ' . get_option( 'yatoon_schema_version', '-' ),
            'WordPress ' . get_bloginfo( 'version' ) . ' / PHP ' . PHP_VERSION,
            'Platform: ' . sanitize_key( get_option( 'yatoon_active_platform', 'local' ) ),
            'Business timezone: ' . yatoon_timezone_string(),
            'Square sync: ' . sanitize_key( $sync['status'] ?? 'unknown' ) . ' @ ' . sanitize_text_field( $sync['checked_at'] ?? '-' ),
            'Square webhook: ' . sanitize_key( $webhook['status'] ?? 'unknown' ) . ' @ ' . sanitize_text_field( $webhook['checked_at'] ?? '-' ),
            'Checks needing attention: ' . ( $failed ? implode( ', ', $failed ) : 'none' ),
        ) );
    }
}
