<?php

namespace SerpIQ\Core;

use SerpIQ\Admin\Admin;
use SerpIQ\Api\Rest;
use SerpIQ\Cron\Scheduler;
use SerpIQ\Database\Schema;
use SerpIQ\Helpers\Options;

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

final class Plugin {
	private static ?Plugin $instance = null;

	private function __construct() {}

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

	public function init(): void {
		add_action( 'init', array( $this, 'load_textdomain' ) );
		add_action( 'plugins_loaded', array( $this, 'maybe_upgrade' ), 5 );

		Admin::instance()->init();
		Rest::instance()->init();
		Scheduler::instance()->init();
	}

	public function load_textdomain(): void {
		load_plugin_textdomain( 'seotune-search-insights', false, dirname( SERPIQ_PLUGIN_BASENAME ) . '/languages' );
	}

	public function maybe_upgrade(): void {
		$installed = (string) get_option( Options::db_version_key(), '0' );
		if ( $installed === (string) SERPIQ_DB_VERSION ) {
			return;
		}

		Schema::install();
		update_option( Options::db_version_key(), (string) SERPIQ_DB_VERSION, false );
	}

	public static function activate(): void {
		if ( ! current_user_can( SERPIQ_CAPABILITY ) ) {
			return;
		}

		Schema::install();
		update_option( Options::db_version_key(), (string) SERPIQ_DB_VERSION, false );
		add_option( Options::delete_data_on_uninstall_key(), 0, '', false );

		Scheduler::instance()->activate();
	}

	public static function deactivate(): void {
		Scheduler::instance()->deactivate();
	}
}

