<?php

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

class AVIN_Plugin {
	private static $instance = null;

	private $repository;
	private $analytics;
	private $wc_metrics;
	private $bot_filter;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	private function __construct() {
		$this->repository = new AVIN_Views_Repository();
		$this->analytics  = new AVIN_Analytics_Repository();
		$this->wc_metrics = new AVIN_WooCommerce_Metrics();
		$this->bot_filter = new AVIN_Bot_Filter();
	}

	public function init() {
		$this->maybe_upgrade();

		$tracker = new AVIN_Tracker( $this->repository, $this->analytics, $this->bot_filter );
		$tracker->init();

		$columns = new AVIN_Admin_Columns( $this->repository );
		$columns->init();

		$admin = new AVIN_Admin( $this->repository, $this->analytics, $this->wc_metrics );
		$admin->init();

		add_action( 'avin_daily_maintenance', array( $this, 'daily_maintenance' ) );
	}

	private function maybe_upgrade() {
		if ( AVIN_DB_VERSION !== get_option( 'avin_db_version' ) ) {
			AVIN_Installer::create_tables();
			AVIN_Installer::seed_options();
			update_option( 'avin_version', AVIN_VERSION, false );
			update_option( 'avin_db_version', AVIN_DB_VERSION, false );
		}
	}

	public function daily_maintenance() {
		$retention = absint( get_option( 'avin_retention_days', 730 ) );
		if ( $retention > 0 ) {
			$this->repository->delete_daily_older_than( $retention );
			$this->analytics->delete_daily_older_than( $retention );
		}
		$this->analytics->prune_presence( 30 );
	}
}
