<?php
/**
 * Message retention: scheduled cleanup of old conversations.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class CPECS_Cleanup {

	const CRON_HOOK = 'cpecs_daily_cleanup';
	const AJAX_ACTION = 'cpecs_run_cleanup_now';

	/** @var CPECS_DB */
	private $db;

	/** @var CPECS_Settings */
	private $settings;

	public function __construct( CPECS_DB $db, CPECS_Settings $settings ) {
		$this->db       = $db;
		$this->settings = $settings;

		add_action( self::CRON_HOOK, array( $this, 'run' ) );
		add_action( 'wp_ajax_' . self::AJAX_ACTION, array( $this, 'ajax_run_now' ) );
	}

	public static function schedule_event() {
		if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::CRON_HOOK );
		}
	}

	public static function unschedule_event() {
		$timestamp = wp_next_scheduled( self::CRON_HOOK );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, self::CRON_HOOK );
		}
	}

	/**
	 * Runs the retention trim. Deletes conversations (and their messages)
	 * whose created_at is older than the configured number of days.
	 * No-op if retention is disabled in settings.
	 *
	 * @return int Number of conversations deleted.
	 */
	public function run() {
		if ( ! $this->settings->get( 'retention_enabled' ) ) {
			return 0;
		}

		$days = (int) $this->settings->get( 'retention_days', 30 );
		if ( $days < 1 ) {
			return 0;
		}

		// created_at is stored as site-local wall-clock time (current_time('mysql'),
		// which is $gmt=false), so the cutoff must be computed on the same
		// local basis — not GMT — or the comparison drifts by the site's
		// UTC offset.
		$cutoff = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days", current_time( 'timestamp' ) ) );

		$deleted = $this->db->delete_conversations_older_than( $cutoff );

		update_option( 'cpecs_last_cleanup_run', current_time( 'mysql' ) );
		update_option( 'cpecs_last_cleanup_count', $deleted );

		return $deleted;
	}

	/**
	 * AJAX handler for the "Run cleanup now" button on the Settings page.
	 * Runs regardless of the retention_enabled toggle, using whatever
	 * retention_days is currently set, so users can test/trim on demand.
	 */
	public function ajax_run_now() {
		check_ajax_referer( 'cpecs_admin', 'nonce' );

		if ( ! current_user_can( apply_filters( 'cpecs_admin_capability', 'manage_options' ) ) ) {
			wp_send_json_error( array( 'message' => __( 'Not allowed.', 'capripio-easy-chat-support' ) ), 403 );
		}

		$days = (int) $this->settings->get( 'retention_days', 30 );
		if ( $days < 1 ) {
			$days = 30;
		}

		// See run() for why this must stay on the local (not GMT) basis.
		$cutoff  = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days", current_time( 'timestamp' ) ) );
		$deleted = $this->db->delete_conversations_older_than( $cutoff );

		update_option( 'cpecs_last_cleanup_run', current_time( 'mysql' ) );
		update_option( 'cpecs_last_cleanup_count', $deleted );

		wp_send_json_success(
			array(
				'deleted' => $deleted,
				'ran_at'  => current_time( 'mysql' ),
			)
		);
	}
}
