<?php

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 ) ? array( 'success' => array( $file_name ) ) : array( 'failed' => array( $file_name ) );
		}
		return array( 'failed' => array( $file_name ?: "({$type})" ) );
	}

	/**
	 * Generates all available data files.
	 *
	 * @return array The results of the operation.
	 */
	public function generate_all_files() {
		$results      = array(
			'success' => array(),
			'failed'  => array(),
		);
		$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( array( 'content' => 'all' ) );
		return ob_get_clean();
	}

	private function get_content_admin_options() {
		$option_keys = Sifency_Demo_Helper::get_admin_option_keys();
		$data        = array();
		$wxr_options = array();

		if ( class_exists( 'Sifency_Addons_WXR_Settings' ) ) {
			$wxr_options = Sifency_Addons_WXR_Settings::instance()->get_export_options();
		}

		foreach ( $option_keys as $key ) {
			$data[ $key ] = array_key_exists( $key, $wxr_options ) ? $wxr_options[ $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       = array(
			'template' => $theme_slug,
			'mods'     => $mods ? $mods : array(),
			'options'  => array(),
		);
		return serialize( $data );
	}

	private function get_content_widgets() {
		global $wp_registered_sidebars;
		$widget_data      = array();
		$sidebars_widgets = get_option( 'sidebars_widgets', array() );
		$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, array() );
					$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( array( 'public' => true ), 'names' );
		$data       = array();
		$query_args = array(
			'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 );
	}
}
