<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 *
 * Handles the logic for generating content and writing it to export files.
 */
final class Sifency_Exporter {

	/**
	 * Generates a single data file based on the specified type.
	 *
	 * @param string $type The type of data to export (e.g., 'wxr', 'admin_options').
	 * @return array The results of the operation.
	 */
	public function generate_file( $type ) {
		$content   = $this->get_export_content( $type );
		$file_name = Sifency_Demo_Helper::get_filename( $type );
		$file_path = Sifency_Demo_Helper::get_filepath( $type );

		if ( ! empty( $content ) && ! empty( $file_name ) && ! empty( $file_path ) ) {
			wp_mkdir_p( dirname( $file_path ) );
			$result = file_put_contents( $file_path, $content );
			return ( $result ) ? [ 'success' => [ $file_name ] ] : [ 'failed' => [ $file_name ] ];
		}
		return [ 'failed' => [ $file_name ?: "({$type})" ] ];
	}

	/**
	 * Generates all available data files.
	 *
	 * @return array The results of the operation.
	 */
	public function generate_all_files() {
		$results      = [ 'success' => [], 'failed' => [] ];
		$export_types = Sifency_Demo_Helper::get_export_types();

		foreach ( $export_types as $type ) {
			$result = $this->generate_file( $type );
			if ( ! empty( $result['success'] ) ) {
				$results['success'] = array_merge( $results['success'], $result['success'] );
			} else {
				$results['failed'] = array_merge( $results['failed'], $result['failed'] );
			}
		}
		return $results;
	}

	/**
	 * A router to get the content for a specific export type.
	 *
	 * @param string $type The export type.
	 * @return string The content to be written to the file.
	 */
	private function get_export_content( $type ) {
		$method_name = "get_content_{$type}";
		if ( method_exists( $this, $method_name ) ) {
			return $this->{$method_name}();
		}
		return '';
	}

	private function get_content_wxr() {
		if ( ! file_exists( ABSPATH . 'wp-admin/includes/export.php' ) ) {
			return '';
		}
		require_once ABSPATH . 'wp-admin/includes/export.php';
		ob_start();
		export_wp( [ 'content' => 'all' ] );
		return ob_get_clean();
	}

	private function get_content_admin_options() {
		$option_keys = Sifency_Demo_Helper::get_admin_option_keys();
		$data        = [];
		foreach ( $option_keys as $key ) {
			$data[ $key ] = get_option( $key );
		}
		return wp_json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
	}

	private function get_content_customizer() {
		$theme_slug = get_stylesheet();
		$mods       = get_option( "theme_mods_{$theme_slug}" );
		$data       = [
			'template' => $theme_slug,
			'mods'     => $mods ? $mods : [],
			'options'  => [],
		];
		return serialize( $data );
	}

	private function get_content_widgets() {
		global $wp_registered_sidebars;
		$widget_data      = [];
		$sidebars_widgets = get_option( 'sidebars_widgets', [] );
		$active_widgets   = array_filter( $sidebars_widgets, fn( $v, $k ) => 'wp_inactive_widgets' !== $k && ! empty( $v ), ARRAY_FILTER_USE_BOTH );

		foreach ( $active_widgets as $sidebar_id => $widget_ids ) {
			if ( isset( $wp_registered_sidebars[ $sidebar_id ] ) ) {
				foreach ( $widget_ids as $widget_id ) {
					$base_id      = preg_replace( '/-[0-9]+$/', '', $widget_id );
					$options      = get_option( 'widget_' . $base_id, [] );
					$instance_key = substr( $widget_id, strlen( $base_id ) + 1 );
					if ( isset( $options[ $instance_key ] ) ) {
						$widget_data[ $sidebar_id ][ $widget_id ] = $options[ $instance_key ];
					}
				}
			}
		}
		return wp_json_encode( $widget_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
	}

	private function get_content_elementor_kit() {
		if ( ! did_action( 'elementor/loaded' ) || ! class_exists( '\Elementor\Plugin' ) ) {
			return '';
		}
		$kit = \Elementor\Plugin::$instance->kits_manager->get_active_kit();
		if ( $kit ) {
			$settings = $kit->get_settings();
			return ! empty( $settings ) ? wp_json_encode( $settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) : '';
		}
		return '';
	}

	private function get_content_meta_options() {
		$meta_keys  = Sifency_Demo_Helper::get_csf_meta_keys();
		$post_types = get_post_types( [ 'public' => true ], 'names' );
		$data       = [];
		$query_args = [
			'posts_per_page' => -1,
			'post_status'    => 'any',
			'fields'         => 'ids',
		];

		foreach ( $post_types as $pt ) {
			$query_args['post_type'] = $pt;
			$posts                   = get_posts( $query_args );
			foreach ( $posts as $post_id ) {
				foreach ( $meta_keys as $key ) {
					$val = get_post_meta( $post_id, $key, true );
					if ( ! empty( $val ) ) {
						$data[ $pt ][ get_post_field( 'post_name', $post_id ) ][ $key ] = $val;
					}
				}
			}
		}
		return wp_json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
	}
}
