<?php

/**
 * AJAX Handler for theme installation and activation.
 *
 * @package Cine_Movie_Engine
 */

namespace MovieEngine\Admin\Ajax;

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

class ThemeInstaller {

	/**
	 * Initialize the class.
	 */
	public function __construct() {
		add_action('wp_ajax_me_install_theme', [$this, 'install_theme']);
	}

	/**
	 * Handle the AJAX request to install and activate a theme.
	 */
	public function install_theme() {
		$slug   = isset($_POST['slug']) ? sanitize_key(wp_unslash($_POST['slug'])) : '';
		$source = isset($_POST['source']) ? esc_url_raw(wp_unslash($_POST['source'])) : '';

		if (! $slug) {
			wp_send_json_error(['message' => esc_html__('Invalid theme slug.', 'cine-movie-engine')]);
		}

		check_ajax_referer('me_install_theme_' . $slug, 'nonce');

		if (! current_user_can('install_themes') || ! current_user_can('switch_themes')) {
			wp_send_json_error(['message' => esc_html__('You do not have permission to install or switch themes.', 'cine-movie-engine')]);
		}

		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		require_once ABSPATH . 'wp-admin/includes/theme.php';
		require_once ABSPATH . 'wp-admin/includes/file.php';

		$theme = wp_get_theme($slug);

		// 1. If not installed, install it.
		if (! $theme->exists()) {

			$install_source = '';

			if (! empty($source)) {
				// Use provided GitHub Zip
				$install_source = $source;
			} else {
				// Try to fetch from WordPress.org API
				require_once ABSPATH . 'wp-admin/includes/theme-install.php';
				$api = themes_api('theme_information', [
					'slug'   => $slug,
					'fields' => ['sections' => false],
				]);

				if (is_wp_error($api)) {
					wp_send_json_error(['message' => sprintf(
						/* translators: %s: error message */
						esc_html__('WordPress.org Error: %s', 'cine-movie-engine'),
						$api->get_error_message()
					)]);
				}

				$install_source = $api->download_link;
			}

			if (! $install_source) {
				wp_send_json_error(['message' => esc_html__('Could not find a valid download source for this theme.', 'cine-movie-engine')]);
			}

			$skin     = new \Automatic_Upgrader_Skin();
			$upgrader = new \Theme_Upgrader($skin);
			$result   = $upgrader->install($install_source);

			if (is_wp_error($result)) {
				wp_send_json_error(['message' => $result->get_error_message()]);
			}

			if (! $result) {
				wp_send_json_error(['message' => esc_html__('Theme installation failed.', 'cine-movie-engine')]);
			}

			// GitHub Zip specific fix: GitHub branches are often extracted to a folder named 'repo-branch'
			// We might need to rename it if the slug mismatch occurs.
			$this->maybe_rename_github_theme_folder($slug);
		}

		// 2. Activate the theme.
		switch_theme($slug);

		wp_send_json_success([
			'message' => esc_html__('Theme installed and activated successfully!', 'cine-movie-engine'),
			'reload'  => true,
		]);
	}

	/**
	 * If the theme was installed from GitHub, the folder name might be 'hello-movieengine-main'.
	 * We try to rename it to the expected slug so WordPress recognizes it.
	 *
	 * @param string $slug Expected theme slug.
	 */
	private function maybe_rename_github_theme_folder($slug) {
		$theme_root = get_theme_root();
		$dirs       = array_diff(scandir($theme_root), ['..', '.']);

		foreach ($dirs as $dir) {
			// If we find a directory starting with the slug and containing '-main' or '-master'
			if (strpos($dir, $slug) === 0 && (strpos($dir, '-main') !== false || strpos($dir, '-master') !== false)) {
				$old_path = $theme_root . '/' . $dir;
				$new_path = $theme_root . '/' . $slug;

				if (! file_exists($new_path)) {
					global $wp_filesystem;
					if (empty($wp_filesystem)) {
						require_once ABSPATH . 'wp-admin/includes/file.php';
						WP_Filesystem();
					}

					if ($wp_filesystem) {
						$wp_filesystem->move($old_path, $new_path);
					} else {
						rename($old_path, $new_path); // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename
					}
				}
				break;
			}
		}
	}
}
