<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Krátký provozní log cronu a souvisejících úloh.
 */
class ElementSell_Cron_Log {

    /** @var array{trigger: string, parts: string[]}|null */
    private static $run = null;

    /**
     * @param string $trigger d | x | t | o
     * @return void
     */
    public static function begin( $trigger = 'd' ) {
        self::$run = [
            'trigger' => sanitize_key( (string) $trigger ),
            'parts'   => [],
        ];
    }

    /**
     * @return bool
     */
    public static function is_active() {
        return self::$run !== null;
    }

    /**
     * @param string $message
     * @return void
     */
    public static function add( $message ) {
        if ( ! self::$run ) {
            return;
        }

        $message = trim( wp_strip_all_tags( (string) $message ) );

        if ( $message !== '' ) {
            self::$run['parts'][] = $message;
        }
    }

    /**
     * @param string $key
     * @return string
     */
    private static function get_trigger_label( $key ) {
        $labels = [
            'd' => 'Denní kontrola',
            'x' => 'Ruční spuštění',
            't' => 'Test upomínek',
            'o' => 'Po zaplacení objednávky',
        ];

        return $labels[ $key ] ?? 'Kontrola';
    }

    /**
     * @return void
     */
    public static function commit() {
        if ( ! self::$run ) {
            return;
        }

        $parts = array_filter( (array) self::$run['parts'] );
        $line  = self::get_trigger_label( self::$run['trigger'] );

        if ( ! empty( $parts ) ) {
            $line .= ' · ' . implode( ' · ', $parts );
        }

        $entry = [
            'at'   => time(),
            'line' => $line,
        ];

        $log = get_option( 'elementsell_ops_log', [] );

        if ( ! is_array( $log ) ) {
            $log = [];
        }

        array_unshift( $log, $entry );
        $log = array_slice( $log, 0, 50 );

        update_option( 'elementsell_ops_log', $log, false );
        self::$run = null;
    }

    /**
     * @return array<int, array{at: int, line: string}>
     */
    public static function get_entries() {
        $log = get_option( 'elementsell_ops_log', [] );

        return is_array( $log ) ? $log : [];
    }
}

/**
 * @return void
 */
function elementsell_cron_log_begin_daily() {
    $trigger = ( defined( 'DOING_CRON' ) && DOING_CRON ) ? 'd' : 'x';
    ElementSell_Cron_Log::begin( $trigger );
}

add_action( 'elementsell_daily_billing_check', 'elementsell_cron_log_begin_daily', 0 );
add_action( 'elementsell_daily_billing_check', 'elementsell_cron_log_commit', 100 );

/**
 * @return void
 */
function elementsell_cron_log_commit() {
    ElementSell_Cron_Log::commit();
}

/**
 * @return void
 */
function elementsell_render_cron_log_panel() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $entries = ElementSell_Cron_Log::get_entries();
    $next    = wp_next_scheduled( 'elementsell_daily_billing_check' );
    $next_ts = $next ? wp_date( 'j.n. G:i', $next ) : '—';

    ?>
    <details class="elementsell-ops-log">
        <summary>Provoz</summary>
        <div class="elementsell-ops-log__body">
            <p class="elementsell-ops-log__meta">Další automatická kontrola cca: <?php echo esc_html( $next_ts ); ?></p>
            <?php if ( empty( $entries ) ) : ?>
                <p class="elementsell-ops-log__line">Zatím žádný záznam.</p>
            <?php else : ?>
                <?php foreach ( $entries as $entry ) : ?>
                    <p class="elementsell-ops-log__line"><?php echo esc_html( elementsell_format_ops_log_line( $entry ) ); ?></p>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </details>
    <style>
        .elementsell-ops-log {
            margin: 28px 0 0;
            max-width: 640px;
            color: #a7aaad;
            font-size: 11px;
            line-height: 1.55;
        }
        .elementsell-ops-log summary {
            cursor: pointer;
            user-select: none;
            color: #c3c4c7;
        }
        .elementsell-ops-log__body {
            margin-top: 8px;
            padding: 8px 10px;
            border: 1px solid #f0f0f1;
            border-radius: 4px;
            background: #fafafa;
        }
        .elementsell-ops-log__meta {
            margin: 0 0 8px;
            font-size: 10px;
            color: #b4b4b4;
        }
        .elementsell-ops-log__line {
            margin: 0 0 6px;
            font-size: 11px;
            color: #8c8f94;
        }
        .elementsell-ops-log__line:last-child {
            margin-bottom: 0;
        }
    </style>
    <?php
}

/**
 * @param array{at?: int, line?: string} $entry
 * @return string
 */
function elementsell_format_ops_log_line( $entry ) {
    $at   = isset( $entry['at'] ) ? (int) $entry['at'] : 0;
    $line = isset( $entry['line'] ) ? (string) $entry['line'] : '';

    if ( $at <= 0 ) {
        return $line;
    }

    return wp_date( 'j.n. G:i', $at ) . ' — ' . $line;
}

/**
 * @param string       $trigger
 * @param string|array $messages
 * @return void
 */
function elementsell_ops_log_write_quick( $trigger, $messages ) {
    ElementSell_Cron_Log::begin( $trigger );

    if ( is_array( $messages ) ) {
        foreach ( $messages as $message ) {
            ElementSell_Cron_Log::add( $message );
        }
    } else {
        ElementSell_Cron_Log::add( (string) $messages );
    }

    ElementSell_Cron_Log::commit();
}
