<?php
/**
 * Base class for handling logs in the Automation Web Platform.
 * Provides common functionality for AJAX handling, permissions, and DataTables logic.
 *
 * @package automation-web-platform
 */

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

/**
 * Class WAWP_Log_Base
 */
abstract class WAWP_Log_Base {
	use WAWP_Security_Trait;

	/**
	 * Table name for this log type.
	 *
	 * @var string
	 */
	protected $table_name;

	/**
	 * Nonce action for security.
	 *
	 * @var string
	 */
	protected $nonce_action;

	/**
	 * Capability required to access these logs.
	 *
	 * @var string
	 */
	protected $capability = WAWP_CAPABILITY;

	/**
	 * Current section name for the React dashboard.
	 *
	 * @var string
	 */
	protected $section;

	/**
	 * Gateway identifier for unified logs.
	 *
	 * @var string
	 */
	protected $gateway = '';

	/**
	 * Constructor: sets table name and registers basic AJAX handlers if needed.
	 */
	public function __construct() {
		$this->setup_properties();
	}

	/**
	 * Setup class properties like table name and section.
	 * Must be implemented by child classes.
	 */
	abstract protected function setup_properties();

	/**
	 * Generic AJAX handler to get logs for DataTables.
	 *
	 * @param array $params Request parameters.
	 * @return array
	 */
	public function get_logs( $params ) {
		global $wpdb;
		$table_name = $this->table_name;
		$draw       = isset( $params['draw'] ) ? intval( $params['draw'] ) : 1;
		$start      = isset( $params['start'] ) ? intval( $params['start'] ) : 0;
		$length     = isset( $params['length'] ) ? intval( $params['length'] ) : 20;

		$search        = isset( $params['search']['value'] ) ? sanitize_text_field( wp_unslash( $params['search']['value'] ) ) : ( isset( $params['search'] ) ? sanitize_text_field( wp_unslash( $params['search'] ) ) : '' );
		$status_filter = isset( $params['status_filter'] ) ? sanitize_text_field( wp_unslash( $params['status_filter'] ) ) : 'all';
		$type_filter   = isset( $params['type_filter'] ) ? sanitize_text_field( wp_unslash( $params['type_filter'] ) ) : 'all';
		$date_from     = isset( $params['date_from'] ) ? sanitize_text_field( wp_unslash( $params['date_from'] ) ) : '';
		$date_to       = isset( $params['date_to'] ) ? sanitize_text_field( wp_unslash( $params['date_to'] ) ) : '';
		$sort_by       = isset( $params['sort_by'] ) ? sanitize_text_field( wp_unslash( $params['sort_by'] ) ) : 'date';
		$sort_order    = isset( $params['sort_order'] ) ? sanitize_text_field( wp_unslash( $params['sort_order'] ) ) : 'desc';

		$allowed_sort = $this->get_allowed_sort_columns();
		$orderby      = ( isset( $allowed_sort[ $sort_by ] ) ) ? $allowed_sort[ $sort_by ] : reset( $allowed_sort );
		$order        = ( 'ASC' === strtoupper( $sort_order ) ) ? 'ASC' : 'DESC';
		$gateway_val  = ! empty( $this->gateway ) ? $this->gateway : '';
		$status_val   = ( 'all' !== $status_filter && ! empty( $status_filter ) ) ? $status_filter : '';
		$type_val     = ( 'all' !== $type_filter && ! empty( $type_filter ) ) ? $type_filter : '';
		$df_val       = ! empty( $date_from ) ? $date_from . ' 00:00:00' : '';
		$dt_val       = ! empty( $date_to ) ? $date_to . ' 23:59:59' : '';
		$search_val   = ! empty( $search ) ? '%' . $wpdb->esc_like( $search ) . '%' : '';

		$status_col_name = $this->get_status_column_name();
		$type_col_name   = $this->get_type_column_name();
		$date_col_name   = $this->get_date_column_name();

		$total_filtered = WAWP()->db->get_var(
			$wpdb->prepare(
				"SELECT COUNT(id) FROM %i WHERE (1=1) AND (%s = '' OR gateway = %s) AND (%s = '' OR %i = %s) AND (%s = '' OR %i = %s) AND (%s = '' OR %i >= %s) AND (%s = '' OR %i <= %s)",
				$table_name,
				$gateway_val,
				$gateway_val,
				$status_val,
				$status_col_name,
				$status_val,
				$type_val,
				$type_col_name,
				$type_val,
				$df_val,
				$date_col_name,
				$df_val,
				$dt_val,
				$date_col_name,
				$dt_val
			)
		);

		$cache_key_total = 'wawp_log_total_' . md5( $table_name . $this->gateway );
		$total_records   = wp_cache_get( $cache_key_total, 'wawp_database' );

		if ( false === $total_records ) {
			$total_records = WAWP()->db->get_var( $wpdb->prepare( 'SELECT COUNT(id) FROM %i WHERE (%s = "" OR gateway = %s)', $table_name, $gateway_val, $gateway_val ) );
			wp_cache_set( $cache_key_total, $total_records, 'wawp_database', 300 );
		}

		if ( 'ASC' === $order ) {
			$results = WAWP()->db->get_results_cached(
				$wpdb->prepare(
					"SELECT * FROM %i WHERE (1=1) AND (%s = '' OR gateway = %s) AND (%s = '' OR %i = %s) AND (%s = '' OR %i = %s) AND (%s = '' OR %i >= %s) AND (%s = '' OR %i <= %s) ORDER BY %i ASC LIMIT %d OFFSET %d",
					$table_name,
					$gateway_val,
					$gateway_val,
					$status_val,
					$status_col_name,
					$status_val,
					$type_val,
					$type_col_name,
					$type_val,
					$df_val,
					$date_col_name,
					$df_val,
					$dt_val,
					$date_col_name,
					$dt_val,
					$orderby,
					$length,
					$start
				),
				'wawp_logs_paged_' . md5( $table_name . wp_json_encode( $params ) ),
				'wawp_logs',
				300
			);
		} else {
			$results = WAWP()->db->get_results_cached(
				$wpdb->prepare(
					"SELECT * FROM %i WHERE (1=1) AND (%s = '' OR gateway = %s) AND (%s = '' OR %i = %s) AND (%s = '' OR %i = %s) AND (%s = '' OR %i >= %s) AND (%s = '' OR %i <= %s) ORDER BY %i DESC LIMIT %d OFFSET %d",
					$table_name,
					$gateway_val,
					$gateway_val,
					$status_val,
					$status_col_name,
					$status_val,
					$type_val,
					$type_col_name,
					$type_val,
					$df_val,
					$date_col_name,
					$df_val,
					$dt_val,
					$date_col_name,
					$dt_val,
					$orderby,
					$length,
					$start
				),
				'wawp_logs_paged_' . md5( $table_name . wp_json_encode( $params ) ),
				'wawp_logs',
				300
			);
		}

		$data = array();
		if ( $results ) {
			foreach ( $results as $log ) {
				$data[] = $this->format_log_row( $log );
			}
		}

		return array(
			'draw'            => $draw,
			'recordsTotal'    => (int) $total_records,
			'recordsFiltered' => (int) $total_filtered,
			'data'            => $data,
		);
	}

	/**
	 * Handle get logs AJAX request.
	 */
	public function handle_get_logs() {
		$this->check_permissions( $this->nonce_action );
		$params = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );
		$res    = $this->get_logs( $params ? $params : array() );
		$this->send_success( '', $res );
	}

	/**
	 * Generic page renderer for React dashboards.
	 */
	public function render_log_page() {
		$stats    = $this->get_base_stats( $this->get_status_column_name(), $this->get_recipient_column_name() );
		$statuses = $this->get_distinct_statuses();
		$types    = $this->get_distinct_types();

		if ( ! class_exists( 'WAWP_Enqueue_Scripts' ) ) {
			require_once WAWP_PLUGIN_DIR . 'views/wawp-enqueue-scripts.php';
		}

		$section_raw     = filter_input( INPUT_GET, 'wawp_section', FILTER_SANITIZE_SPECIAL_CHARS );
		$current_section = $section_raw ? sanitize_key( $section_raw ) : '';
		if ( ! $current_section ) {
			$current_section = $this->section;
		}

		$base_data = WAWP_Enqueue_Scripts::prepare_dashboard_data( $current_section, true );

		$log_data = array(
			'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
			'nonce'          => wp_create_nonce( $this->nonce_action ),
			'currentSection' => $current_section,
			'rtl'            => is_rtl(),
			'logStatuses'    => $statuses,
			'messageTypes'   => $types,
			'logStats'       => $stats,
			'i18n'           => array_merge( $this->get_common_i18n(), $this->get_page_strings() ),
		);

		$final_data         = array_merge( $base_data, $log_data );
		$final_data['i18n'] = array_merge( isset( $base_data['i18n'] ) ? $base_data['i18n'] : array(), $log_data['i18n'] );

		wp_localize_script( 'wawp-react-dashboard', 'wawpDashboardData', $final_data );
		echo '<div id="wawp-dashboard-root"></div>';
	}

	/**
	 * Build SQL WHERE clause from parameters.
	 *
	 * @param array $params Request parameters.
	 * @return string
	 */
	protected function build_where_clause( $params ) {
		global $wpdb;
		$where = array( '1=1' );

		if ( ! empty( $this->gateway ) ) {
			$where[] = $wpdb->prepare( 'gateway = %s', $this->gateway );
		}

		$status_filter = isset( $params['status_filter'] ) ? sanitize_text_field( wp_unslash( $params['status_filter'] ) ) : 'all';
		$type_filter   = isset( $params['type_filter'] ) ? sanitize_text_field( wp_unslash( $params['type_filter'] ) ) : 'all';
		$date_from     = isset( $params['date_from'] ) ? sanitize_text_field( wp_unslash( $params['date_from'] ) ) : '';
		$date_to       = isset( $params['date_to'] ) ? sanitize_text_field( wp_unslash( $params['date_to'] ) ) : '';
		$search        = isset( $params['search']['value'] ) ? sanitize_text_field( wp_unslash( $params['search']['value'] ) ) : ( isset( $params['search'] ) ? sanitize_text_field( wp_unslash( $params['search'] ) ) : '' );

		if ( 'all' !== $status_filter && ! empty( $status_filter ) ) {
			$status_col = $this->get_status_column_name();
			$where[]    = $wpdb->prepare( '%i = %s', $status_col, $status_filter );
		}

		if ( 'all' !== $type_filter && ! empty( $type_filter ) ) {
			$type_col = $this->get_type_column_name();
			$where[]  = $wpdb->prepare( '%i = %s', $type_col, $type_filter );
		}

		if ( ! empty( $date_from ) ) {
			$date_col = $this->get_date_column_name();
			$where[]  = $wpdb->prepare( '%i >= %s', $date_col, $date_from . ' 00:00:00' );
		}

		if ( ! empty( $date_to ) ) {
			$date_col = $this->get_date_column_name();
			$where[]  = $wpdb->prepare( '%i <= %s', $date_col, $date_to . ' 23:59:59' );
		}

		$search = isset( $params['search']['value'] ) ? sanitize_text_field( wp_unslash( $params['search']['value'] ) ) : ( isset( $params['search'] ) ? sanitize_text_field( wp_unslash( $params['search'] ) ) : '' );
		if ( ! empty( $search ) ) {
			$search_cols  = $this->get_search_columns();
			$search_parts = array();
			$like         = '%' . $wpdb->esc_like( $search ) . '%';

			foreach ( $search_cols as $col ) {
				$search_parts[] = $wpdb->prepare( '%i LIKE %s', $col, $like );
			}
			$where[] = '(' . implode( ' OR ', $search_parts ) . ')';
		}

		return implode( ' AND ', $where );
	}

	/**
	 * Get allowed sort columns.
	 *
	 * @return array
	 */
	protected function get_allowed_sort_columns() {
		return array( 'date' => $this->get_date_column_name() );
	}

	/**
	 * Get search columns.
	 *
	 * @return array
	 */
	protected function get_search_columns() {
		return array();
	}

	/**
	 * Get date column name.
	 *
	 * @return string
	 */
	protected function get_date_column_name() {
		return 'created_at';
	}

	/**
	 * Get status column name.
	 *
	 * @return string
	 */
	protected function get_status_column_name() {
		return 'log_status';
	}

	/**
	 * Get type column name.
	 *
	 * @return string
	 */
	protected function get_type_column_name() {
		return 'event_type';
	}

	/**
	 * Get recipient column name.
	 *
	 * @return string
	 */
	protected function get_recipient_column_name() {
		return 'phone';
	}

	/**
	 * Process status filter.
	 *
	 * @param array $statuses Statuses to filter.
	 * @return array
	 */
	protected function process_status_filter( $statuses ) {
		return $statuses;
	}

	/**
	 * Format a single log row for DataTables output.
	 *
	 * @param array $log Raw log data.
	 * @return array
	 */
	abstract protected function format_log_row( $log );

	/**
	 * Get page-specific i18n strings.
	 *
	 * @return array
	 */
	abstract protected function get_page_strings();

	/**
	 * Get distinct statuses from database.
	 *
	 * @return array
	 */
	protected function get_distinct_statuses() {
		global $wpdb;
		$col       = $this->get_status_column_name();
		$table     = $this->table_name;
		$gateway   = $this->gateway;
		$cache_key = 'wawp_distinct_statuses_' . md5( $table . $col . $gateway );
		$results   = wp_cache_get( $cache_key, 'wawp_logs' );

		if ( false === $results ) {
			$results = WAWP()->db->get_col(
				$wpdb->prepare(
					'SELECT DISTINCT %i FROM %i WHERE %i != "" AND (%s = "" OR gateway = %s)',
					$col,
					$table,
					$col,
					$gateway,
					$gateway
				)
			);
			$results = $results ? $results : array();
			wp_cache_set( $cache_key, $results, 'wawp_logs', HOUR_IN_SECONDS );
		}

		return $results;
	}

	/**
	 * Get distinct message types from database.
	 *
	 * @return array
	 */
	protected function get_distinct_types() {
		global $wpdb;
		$col       = $this->get_type_column_name();
		$table     = $this->table_name;
		$gateway   = $this->gateway;
		$cache_key = 'wawp_distinct_types_' . md5( $table . $col . $gateway );
		$results   = wp_cache_get( $cache_key, 'wawp_logs' );

		if ( false === $results ) {
			$results = WAWP()->db->get_col(
				$wpdb->prepare(
					'SELECT DISTINCT %i FROM %i WHERE %i != "" AND (%s = "" OR gateway = %s)',
					$col,
					$table,
					$col,
					$gateway,
					$gateway
				)
			);
			$results = $results ? $results : array();
			wp_cache_set( $cache_key, $results, 'wawp_logs', HOUR_IN_SECONDS );
		}

		return $results;
	}

	/**
	 * Generic AJAX handler to delete logs.
	 *
	 * @param array $params Request parameters.
	 * @return array
	 */
	public function delete_logs( $params ) {
		global $wpdb;
		$ids = isset( $params['log_ids'] ) ? array_map( 'intval', (array) $params['log_ids'] ) : array();
		if ( empty( $ids ) ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'No IDs provided.', 'automation-web-platform' ),
			);
		}

		foreach ( $ids as $id ) {
			WAWP()->db->delete_row( $this->table_name, array( 'id' => $id ) );
		}
		wp_cache_flush_group( 'wawp_logs' );
		$count = count( $ids ); // Assuming they were deleted.

		if ( false === $count ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Database error.', 'automation-web-platform' ),
			);
		}

		$this->after_delete( $ids );

		return array(
			'success' => true,
			'message' => esc_html__( 'Logs deleted successfully.', 'automation-web-platform' ),
			'count'   => $count,
		);
	}

	/**
	 * Handle delete logs AJAX request.
	 */
	public function handle_delete_logs() {
		$this->check_permissions( $this->nonce_action );
		$params = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );
		$res    = $this->delete_logs( $params ? $params : array() );
		if ( $res['success'] ) {
			$this->send_success( $res['message'], $res );
		} else {
			$this->send_error( $res['message'] );
		}
	}

	/**
	 * Hook called after a successful deletion.
	 *
	 * @param array $ids Deleted IDs.
	 */
	protected function after_delete( $ids ) {
		// Optional override.
	}

	/**
	 * Builds common i18n strings for the React dashboard.
	 */
	protected function get_common_i18n() {
		return array(
			'btnSettings'      => esc_html__( 'Settings', 'automation-web-platform' ),
			'btnHelp'          => esc_html__( 'Help', 'automation-web-platform' ),
			'btnDelete'        => esc_html__( 'Delete', 'automation-web-platform' ),
			'btnClearFilters'  => esc_html__( 'Clear Filters', 'automation-web-platform' ),
			'snapshotTitle'    => esc_html__( 'Snapshot', 'automation-web-platform' ),
			'totalLabel'       => esc_html__( 'Total messages history', 'automation-web-platform' ),
			'sentLabel'        => esc_html__( 'Successfully sent messages', 'automation-web-platform' ),
			'failedLabel'      => esc_html__( 'Failed to deliver', 'automation-web-platform' ),
			'uniqueLabel'      => esc_html__( 'Unique WhatsApp numbers', 'automation-web-platform' ),
			'liveSearch'       => esc_html__( 'Live search...', 'automation-web-platform' ),
			'perPage'          => esc_html__( 'Results Per Page', 'automation-web-platform' ),
			'dateRange'        => esc_html__( 'Date Range', 'automation-web-platform' ),
			'allTime'          => esc_html__( 'All Time', 'automation-web-platform' ),
			/* translators: %d: number of days */
			'lastDays'         => esc_html__( 'Last %d Days', 'automation-web-platform' ),
			'messageTypeTitle' => esc_html__( 'Message Type', 'automation-web-platform' ),
			'statusTitle'      => esc_html__( 'Status', 'automation-web-platform' ),
			'columnsTitle'     => esc_html__( 'Columns', 'automation-web-platform' ),
			'all'              => esc_html__( 'All', 'automation-web-platform' ),
			'confirmDelete'    => esc_html__( 'Are you sure you want to delete selected logs?', 'automation-web-platform' ),
			/* translators: 1: start entry, 2: end entry, 3: total entries */
			'showingEntries'   => esc_html__( 'Showing %1$d–%2$d of %3$d entries', 'automation-web-platform' ),
			'btnPrevious'      => esc_html__( 'Previous', 'automation-web-platform' ),
			'btnNext'          => esc_html__( 'Next', 'automation-web-platform' ),
			'detailsTitle'     => esc_html__( 'Message Details', 'automation-web-platform' ),
			'btnClose'         => esc_html__( 'Close', 'automation-web-platform' ),
			'btnCancel'        => esc_html__( 'Cancel', 'automation-web-platform' ),
			'btnConfirm'       => esc_html__( 'Confirm', 'automation-web-platform' ),
			'noUndone'         => esc_html__( '⚠️ This action cannot be undone.', 'automation-web-platform' ),
			/* translators: %d: number of log entries */
			'deleteWarning'    => esc_html__( 'You are about to permanently delete %d log entries.', 'automation-web-platform' ),
			'columns'          => array(
				'id'        => esc_html__( 'ID', 'automation-web-platform' ),
				'user'      => esc_html__( 'User ID', 'automation-web-platform' ),
				'order'     => esc_html__( 'Order', 'automation-web-platform' ),
				'campaign'  => esc_html__( 'Campaign', 'automation-web-platform' ),
				'name'      => esc_html__( 'Name', 'automation-web-platform' ),
				'date'      => esc_html__( 'Date', 'automation-web-platform' ),
				'recipient' => esc_html__( 'Recipient', 'automation-web-platform' ),
				'subject'   => esc_html__( 'Content', 'automation-web-platform' ),
				'status'    => esc_html__( 'Status', 'automation-web-platform' ),
				'extra'     => esc_html__( 'Type', 'automation-web-platform' ),
				'ref'       => esc_html__( 'Ref ID', 'automation-web-platform' ),
			),
		);
	}

	/**
	 * Common stats query with caching support.
	 *
	 * @param string $status_col    Status column name.
	 * @param string $recipient_col Recipient column name.
	 * @param array  $params        Search parameters.
	 * @return array
	 */
	public function get_base_stats( $status_col = 'log_status', $recipient_col = 'phone', $params = array() ) {
		global $wpdb;
		$table = esc_sql( $this->table_name );
		if ( empty( $table ) ) {
			return array(
				'total'  => 0,
				'sent'   => 0,
				'error'  => 0,
				'unique' => 0,
			);
		}

		$where_str = $this->build_where_clause( $params );
		$cache_key = 'wawp_log_stats_' . md5( $this->table_name . $where_str );
		$stats     = wp_cache_get( $cache_key, 'wawp_logs' );

		if ( false === $stats ) {
			$gw_val = ! empty( $this->gateway ) ? $this->gateway : '';
			$sf_val = ( isset( $params['status_filter'] ) && 'all' !== $params['status_filter'] ) ? $params['status_filter'] : '';
			$tf_val = ( isset( $params['type_filter'] ) && 'all' !== $params['type_filter'] ) ? $params['type_filter'] : '';
			$df_val = ! empty( $params['date_from'] ) ? $params['date_from'] . ' 00:00:00' : '';
			$dt_val = ! empty( $params['date_to'] ) ? $params['date_to'] . ' 23:59:59' : '';

			$total = (int) WAWP()->db->get_var(
				$wpdb->prepare(
					'SELECT COUNT(id) FROM %i WHERE (1=1) AND (%s = "" OR gateway = %s) AND (%s = "" OR %i = %s) AND (%s = "" OR %i = %s) AND (%s = "" OR %i >= %s) AND (%s = "" OR %i <= %s)',
					$this->table_name,
					$gw_val,
					$gw_val,
					$sf_val,
					$status_col,
					$sf_val,
					$tf_val,
					$this->get_type_column_name(),
					$tf_val,
					$df_val,
					$this->get_date_column_name(),
					$df_val,
					$dt_val,
					$this->get_date_column_name(),
					$dt_val
				)
			);

			$sent = (int) WAWP()->db->get_var(
				$wpdb->prepare(
					'SELECT COUNT(id) FROM %i WHERE (1=1) AND (%s = "" OR gateway = %s) AND (%s = "" OR %i = %s) AND (%s = "" OR %i = %s) AND (%s = "" OR %i >= %s) AND (%s = "" OR %i <= %s) AND %i IN (%s, %s, %s, %s)',
					$this->table_name,
					$gw_val,
					$gw_val,
					$sf_val,
					$status_col,
					$sf_val,
					$tf_val,
					$this->get_type_column_name(),
					$tf_val,
					$df_val,
					$this->get_date_column_name(),
					$df_val,
					$dt_val,
					$this->get_date_column_name(),
					$dt_val,
					$status_col,
					'success',
					'sent',
					'delivered',
					'read'
				)
			);

			$error = (int) WAWP()->db->get_var(
				$wpdb->prepare(
					'SELECT COUNT(id) FROM %i WHERE (1=1) AND (%s = "" OR gateway = %s) AND (%s = "" OR %i = %s) AND (%s = "" OR %i = %s) AND (%s = "" OR %i >= %s) AND (%s = "" OR %i <= %s) AND %i IN (%s, %s, %s, %s)',
					$this->table_name,
					$gw_val,
					$gw_val,
					$sf_val,
					$status_col,
					$sf_val,
					$tf_val,
					$this->get_type_column_name(),
					$tf_val,
					$df_val,
					$this->get_date_column_name(),
					$df_val,
					$dt_val,
					$this->get_date_column_name(),
					$dt_val,
					$status_col,
					'error',
					'failed',
					'failure',
					'blocked'
				)
			);

			$unique = (int) WAWP()->db->get_var(
				$wpdb->prepare(
					'SELECT COUNT(DISTINCT %i) FROM %i WHERE (1=1) AND (%s = "" OR gateway = %s) AND (%s = "" OR %i = %s) AND (%s = "" OR %i = %s) AND (%s = "" OR %i >= %s) AND (%s = "" OR %i <= %s)',
					$recipient_col,
					$this->table_name,
					$gw_val,
					$gw_val,
					$sf_val,
					$status_col,
					$sf_val,
					$tf_val,
					$this->get_type_column_name(),
					$tf_val,
					$df_val,
					$this->get_date_column_name(),
					$df_val,
					$dt_val,
					$this->get_date_column_name(),
					$dt_val
				)
			);

			$stats = array(
				'total'  => $total,
				'sent'   => $sent,
				'error'  => $error,
				'unique' => $unique,
			);
			wp_cache_set( $cache_key, $stats, 'wawp_logs', HOUR_IN_SECONDS );
		}

		return $stats;
	}
}
