<?php
namespace features;

/**
 * Forumax Auto Close Topics
 * Automatically close topics with no new replies after a configurable number of days.
 */
class forumax_auto_close_topics {

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'init', [ $this, 'schedule_events' ] );
        add_action( 'frmx_auto_close_stale_topics', [ $this, 'close_stale_topics' ] );
    }

    /**
     * Schedule or unschedule the cron event based on settings.
     */
    public function schedule_events() {
        if ( forumax_get_opt( 'auto_close_stale_topics' ) ) {
            if ( ! wp_next_scheduled( 'frmx_auto_close_stale_topics' ) ) {
                wp_schedule_event( time(), 'daily', 'frmx_auto_close_stale_topics' );
            }
        } else {
            $timestamp = wp_next_scheduled( 'frmx_auto_close_stale_topics' );
            if ( $timestamp ) {
                wp_unschedule_event( $timestamp, 'frmx_auto_close_stale_topics' );
            }
        }
    }

    /**
     * Close stale topics.
     */
    public function close_stale_topics() {
        if ( ! forumax_get_opt( 'auto_close_stale_topics' ) ) {
            return;
        }

        $days = absint( forumax_get_opt( 'auto_close_days', 90 ) );
        if ( $days < 1 ) {
            return;
        }

        $cutoff = date( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) );

        // Get open topics with no recent replies
        $args = [
            'post_type'      => 'topic',
            'post_status'    => 'publish',
            'posts_per_page' => 50, // Batch to avoid timeouts
            'meta_query'     => [
                [
                    'key'     => '_bbp_last_active_time',
                    'value'   => $cutoff,
                    'compare' => '<',
                    'type'    => 'DATETIME',
                ],
            ],
            'fields'         => 'ids',
        ];

        $stale_topics = get_posts( $args );

        if ( ! empty( $stale_topics ) ) {
            foreach ( $stale_topics as $topic_id ) {
                // Skip already closed topics (though query checks post_status=publish, bbp_is_topic_closed checks meta)
                if ( bbp_is_topic_closed( $topic_id ) ) {
                    continue;
                }
                // Skip sticky topics (they're intentionally persistent)
                if ( bbp_is_topic_sticky( $topic_id ) || bbp_is_topic_super_sticky( $topic_id ) ) {
                    continue;
                }

                bbp_close_topic( $topic_id );

                // Add a meta flag so admins know it was auto-closed
                update_post_meta( $topic_id, '_frmx_auto_closed', current_time( 'mysql' ) );
            }
        }
    }
}

// Instantiate the class.
new forumax_auto_close_topics();
