<?php
/**
 * Plugin Name:       Seotune Search Insights
 * Plugin URI:        https://wordpress.org/plugins/seotune-search-insights/
 * Description:       Seotune Search Insights: dashboards and SEO reports from Google Search Console data (OAuth). Keywords, opportunities, cannibalization, and more. Third-party plugin; not affiliated with Google.
 * Version:           1.0.2
 * Author:            Seotune
 * Author URI:        https://seotune.app
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       seotune-search-insights
 * Domain Path:       /languages
 * Requires at least: 6.2
 * Requires PHP:      8.0
 */

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

define( 'SERPIQ_VERSION', '1.0.2' );
define( 'SERPIQ_DB_VERSION', '3' );
define( 'SERPIQ_PLUGIN_FILE', __FILE__ );
define( 'SERPIQ_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'SERPIQ_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'SERPIQ_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );

/** Capability required for admin UI, Settings actions, and REST (see Rest_Permission). */
define( 'SERPIQ_CAPABILITY', 'manage_options' );

// Load Composer autoload (Google API client) if bundled.
if ( file_exists( SERPIQ_PLUGIN_DIR . 'vendor/autoload.php' ) ) {
	require_once SERPIQ_PLUGIN_DIR . 'vendor/autoload.php';
}

/**
 * Lightweight autoloader for plugin classes under the `SerpIQ\` PHP namespace.
 *
 * Maps:
 * - SerpIQ\Core\Plugin -> includes/core/class-plugin.php
 * - SerpIQ\Api\Controllers\Status_Controller -> includes/api/controllers/class-status-controller.php
 */
spl_autoload_register(
	static function ( $class ) {
		$prefix = 'SerpIQ\\';
		$base_dir = SERPIQ_PLUGIN_DIR . 'includes/';

		$len = strlen( $prefix );
		if ( strncmp( $prefix, $class, $len ) !== 0 ) {
			return;
		}

		$relative = substr( $class, $len );
		$relative = str_replace( '\\', '/', $relative );
		$parts = array_values( array_filter( explode( '/', $relative ) ) );
		if ( empty( $parts ) ) {
			return;
		}

		$class_name = array_pop( $parts );
		$dirs = array_map( static fn( $p ) => strtolower( $p ), $parts );
		$filename = 'class-' . strtolower( preg_replace( '/_+/', '-', $class_name ) ) . '.php';
		$file = $base_dir . ( $dirs ? implode( '/', $dirs ) . '/' : '' ) . $filename;

		if ( file_exists( $file ) ) {
			require $file;
		}
	}
);

require_once SERPIQ_PLUGIN_DIR . 'includes/core/class-plugin.php';

// WP-CLI integration (optional).
if ( defined( 'WP_CLI' ) && WP_CLI ) {
	try {
		SerpIQ\Cli\Cli::register();
	} catch ( \Throwable $e ) {
		// Never break WP-CLI bootstrap if something goes wrong.
	}
}

register_activation_hook(
	__FILE__,
	static function () {
		SerpIQ\Core\Plugin::activate();
	}
);

register_deactivation_hook(
	__FILE__,
	static function () {
		SerpIQ\Core\Plugin::deactivate();
	}
);

function SERPIQ() {
	return SerpIQ\Core\Plugin::instance();
}

SERPIQ()->init();

