<?php

namespace FleekDash\Core;

// Load debug helpers
if (!function_exists('fleekdash_log_info')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

use FleekDash\Database\Core\MigrationManager;
use FleekDash\Database\Seeders\Accounts as SeedersAccounts;
use FleekDash\Services\SiteGrowthMeterService;
use FleekDash\Traits\Base;

defined('ABSPATH') || exit;

/**
 * Plugin Installation Handler
 *
 * Handles plugin activation and setup using the new Migration System
 */
class Install
{
	use Base;

	/**
	 * Initialize the class
	 *
	 * @return void
	 */
	public function init()
	{
		$this->install_tables();
		$this->insert_data();
		$this->initialize_services();
	}

	/**
	 * Install all tables using Migration Manager
	 *
	 * @return void
	 */
	private function install_tables()
	{
		try {
			$manager = new MigrationManager();
			$results = $manager->run();

			if (isset($results['message'])) {
				// No migrations to run
				fleekdash_log_info('FleekDash Install: ' . $results['message']);
			} else {
				// Migrations executed
				$success_count = 0;
				foreach ($results['migrations'] as $result) {
					if ($result['success']) {
						$success_count++;
					} else {
						fleekdash_log_error("FleekDash Install: Migration failed - {$result['migration']}: {$result['error']}");
					}
				}

				fleekdash_log_info("FleekDash Install: {$success_count} migrations executed successfully");
			}
		} catch (\Throwable $e) {
			fleekdash_log_error('FleekDash Install: Failed to run migrations - ' . $e->getMessage());
		}
	}

	/**
	 * Insert initial data using seeders
	 *
	 * @return void
	 */
	private function insert_data()
	{
		try {
			SeedersAccounts::run();
		} catch (\Throwable $e) {
			fleekdash_log_error('FleekDash Install: Failed to run seeders - ' . $e->getMessage());
		}
	}

	/**
	 * Initialize services that need post-migration setup
	 *
	 * @return void
	 */
	private function initialize_services()
	{
		// Initialize Site Growth Meter
		try {
			$growth_service = new SiteGrowthMeterService();
			$result = $growth_service->initializeSiteGrowthMeter();

			if ($result['success']) {
				fleekdash_log_info("FleekDash Install: Site Growth Meter initialized - Events: {$result['events_created']}, Goals: {$result['goals_created']}");
			} else {
				fleekdash_log_error("FleekDash Install: Failed to initialize Site Growth Meter: {$result['message']}");
			}
		} catch (\Throwable $e) {
			fleekdash_log_error("FleekDash Install: Error initializing Site Growth Meter - " . $e->getMessage());
		}
	}
}
