<?php
/**
 * Repository: database access for the update log.
 */

defined( 'ABSPATH' ) || exit;

class BW_Update_Server_Repository {

	public static function log_check( array $data ) {
		global $wpdb;

		$defaults = array(
			'plugin_slug'       => '',
			'site_url'          => '',
			'installed_version' => '',
			'latest_version'    => '',
			'wp_version'        => '',
			'php_version'       => '',
			'ip_address'        => '',
			'user_agent'        => '',
			'checked_at'        => current_time( 'mysql', 1 ),
		);

		$row = array_intersect_key( array_merge( $defaults, $data ), $defaults );

		$wpdb->insert(
			BW_Update_Server_Installer::table_name(),
			$row,
			array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
		);
	}

	public static function recent_checks( $slug = null, $limit = 100 ) {
		global $wpdb;
		$table = BW_Update_Server_Installer::table_name();
		$limit = absint( $limit );

		if ( $slug ) {
			return $wpdb->get_results(
				$wpdb->prepare(
					"SELECT * FROM {$table} WHERE plugin_slug = %s ORDER BY checked_at DESC LIMIT %d",
					$slug,
					$limit
				)
			);
		}
		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$table} ORDER BY checked_at DESC LIMIT %d",
				$limit
			)
		);
	}
}
