<?php

namespace EasyContentManager\Utils\Traits;

use EasyContentManager\Utils\Helper;
use WP_Query;

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

trait ToolsHelper {

	private function handle_file_upload() {
		if ( ! isset( $_FILES['file'] ) || empty( $_FILES['file']['tmp_name'] ) ) {
			return new \WP_Error( 'no_file', __( 'No file uploaded.', 'easy-content-manager' ) );
		}

		$file = $_FILES['file'];

		if ( $file['error'] !== UPLOAD_ERR_OK ) {
			return new \WP_Error( 'upload_error', __( 'File upload failed.', 'easy-content-manager' ) );
		}

		if ( wp_check_filetype( $file['name'] )['ext'] !== 'zip' ) {
			return new \WP_Error( 'invalid_type', __( 'Only ZIP files are allowed.', 'easy-content-manager' ) );
		}

		$upload_dir = wp_upload_dir();
		$temp_file = $upload_dir['basedir'] . '/ecm_import_' . time() . '.zip';

		if ( ! move_uploaded_file( $file['tmp_name'], $temp_file ) ) {
			return new \WP_Error( 'move_failed', __( 'Failed to process file.', 'easy-content-manager' ) );
		}

		return [ 'path' => $temp_file ];
	}

	private function read_manifest_from_zip( $zip ) {
		$content = $zip->getFromName( 'manifest.json' );
		return $content ? json_decode( $content, true ) : null;
	}

	private function cleanup_temp_file( $path ) {
		if ( file_exists( $path ) ) {
			wp_delete_file( $path );
		}
	}
	
	private function get_existing_post_type_post( $slug ) {
		$posts = get_posts( [
			'post_type'      => Helper::ECM_POST_TYPE_NAME,
			'name'           => sanitize_title( $slug ),
			'posts_per_page' => 1,
			'post_status'    => 'any',
		] );
		return $posts[0] ?? null;
	}

	private function create_post_type_from_import( $data ) {
		$post_content = $data['post_content'];
		$slug = $data['post_name'] ?? $post_content['post_slug'] ?? sanitize_title( $data['post_title'] );
		
		return wp_insert_post( [
			'post_title'   => sanitize_text_field( $data['post_title'] ),
			'post_name'    => sanitize_title( $slug ),
			'post_content' => maybe_serialize( $post_content ),
			'post_status'  => $data['post_status'] ?? 'publish',
			'post_type'    => Helper::ECM_POST_TYPE_NAME,
		], true );
	}

	private function update_post_type_from_import( $post_id, $data ) {
		$post_content = $data['post_content'];
		$slug = $data['post_name'] ?? $post_content['post_slug'] ?? sanitize_title( $data['post_title'] );
		
		return wp_update_post( [
			'ID'           => $post_id,
			'post_title'   => sanitize_text_field( $data['post_title'] ),
			'post_name'    => sanitize_title( $slug ),
			'post_content' => maybe_serialize( $post_content ),
		], true );
	}

	private function get_all_custom_post_types() {
		$query = new WP_Query( [
			'post_type'      => Helper::ECM_POST_TYPE_NAME,
			'posts_per_page' => -1,
			'post_status'    => 'any',
		] );

		$posts = [];
		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) {
				$query->the_post();
				$post = get_post();
				$posts[] = [
					'ID'           => $post->ID,
					'post_title'   => $post->post_title,
					'post_name'    => $post->post_name,
					'post_content' => maybe_unserialize( $post->post_content ),
					'post_status'  => $post->post_status,
				];
			}
			wp_reset_postdata();
		}
		return $posts;
	}
	
	private function get_existing_taxonomy_post( $slug ) {
		$posts = get_posts( [
			'post_type'      => Helper::ECM_TAXONOMY_POST_TYPE_NAME,
			'name'           => sanitize_title( $slug ),
			'posts_per_page' => 1,
			'post_status'    => 'any',
		] );
		return $posts[0] ?? null;
	}

	private function create_taxonomy_from_import( $data ) {
		$post_content = $data['post_content'];
		$slug = $data['post_name'] ?? $post_content['taxonomy_slug'] ?? $data['post_title'];
		
		return wp_insert_post( [
			'post_title'   => $slug,
			'post_name'    => $slug,
			'post_content' => maybe_serialize( $post_content ),
			'post_status'  => $data['post_status'] ?? 'publish',
			'post_type'    => Helper::ECM_TAXONOMY_POST_TYPE_NAME,
		], true );
	}

	private function update_taxonomy_from_import( $post_id, $data ) {
		$post_content = $data['post_content'];
		$slug = $data['post_name'] ?? $post_content['taxonomy_slug'] ?? $data['post_title'];
		
		return wp_update_post( [
			'ID'           => $post_id,
			'post_title'   => $slug,
			'post_name'    => $slug,
			'post_content' => maybe_serialize( $post_content ),
		], true );
	}

	private function link_taxonomy_to_post_types( $taxonomy_slug, $object_types ) {
		foreach ( (array) $object_types as $post_type ) {
			$post_type_slug = $post_type['post_type'] ?? $post_type['title'] ?? ( is_string( $post_type ) ? $post_type : null );
			if ( ! $post_type_slug ) continue;

			$posts = get_posts( [
				'name'           => $post_type_slug,
				'post_type'      => Helper::ECM_POST_TYPE_NAME,
				'posts_per_page' => 1,
				'post_status'    => 'any',
			] );

			if ( empty( $posts ) ) continue;

			$post_content = maybe_unserialize( $posts[0]->post_content );
			$post_content['taxonomies'] = $post_content['taxonomies'] ?? [];

			if ( ! in_array( $taxonomy_slug, $post_content['taxonomies'], true ) ) {
				$post_content['taxonomies'][] = $taxonomy_slug;
				wp_update_post( [
					'ID'           => $posts[0]->ID,
					'post_content' => maybe_serialize( $post_content ),
				] );
			}
		}
	}

	private function get_all_custom_taxonomies() {
		$query = new WP_Query( [
			'post_type'      => Helper::ECM_TAXONOMY_POST_TYPE_NAME,
			'posts_per_page' => -1,
			'post_status'    => 'any',
			'orderby'        => 'post_title',
			'order'          => 'asc',
		] );

		$results = [];
		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) {
				$query->the_post();
				$post = get_post();
				$results[] = [
					'ID'           => $post->ID,
					'post_title'   => $post->post_title,
					'post_name'    => $post->post_name,
					'post_content' => maybe_unserialize( $post->post_content ),
					'post_status'  => $post->post_status,
				];
			}
			wp_reset_postdata();
		}
		return $results;
	}
	
	private function get_existing_setting_post( $slug ) {
		$posts = get_posts( [
			'post_type'      => Helper::ECM_SETTINGS_POST_TYPE_NAME,
			'name'           => sanitize_title( $slug ),
			'posts_per_page' => 1,
			'post_status'    => 'any',
		] );
		
		return $posts[0] ?? null;
	}

	private function create_setting_from_import( $data ) {
		$post_content = $data['post_content'];
		$slug = $data['post_name'] ?? $post_content['slug'] ?? sanitize_title( $data['post_title'] );
		$title = $post_content['label'] ?? $data['post_title'];
		
		$post_id = wp_insert_post( [
			'post_title'   => sanitize_text_field( $title ),
			'post_name'    => sanitize_title( $slug ),
			'post_content' => maybe_serialize( $post_content ),
			'post_status'  => 'publish',
			'post_type'    => Helper::ECM_SETTINGS_POST_TYPE_NAME,
		], true );
		
		return $post_id;
	}

	private function update_setting_from_import( $post_id, $data ) {
		$post_content = $data['post_content'];
		$slug = $data['post_name'] ?? $post_content['slug'] ?? sanitize_title( $data['post_title'] );
		$title = $post_content['label'] ?? $data['post_title'];
		
		$result = wp_update_post( [
			'ID'           => $post_id,
			'post_title'   => sanitize_text_field( $title ),
			'post_name'    => sanitize_title( $slug ),
			'post_content' => maybe_serialize( $post_content ),
		], true );
		
		return $result;
	}

	private function get_all_settings() {
		$posts = get_posts( [
			'post_type'      => Helper::ECM_SETTINGS_POST_TYPE_NAME,
			'post_status'    => 'any',
			'posts_per_page' => -1,
			'orderby'        => [ 'menu_order' => 'ASC', 'title' => 'ASC' ],
			'order'          => 'ASC',
		] );

		return [
			'items' => array_map( function ( $post ) {
				return [
					'id'           => $post->ID,
					'post_title'   => $post->post_title,
					'post_name'    => $post->post_name,
					'post_content' => maybe_unserialize( $post->post_content ) ?? [],
				];
			}, $posts ),
		];
	}
	
	private function get_existing_field_group_post( $title ) {
		$posts = get_posts( [
			'post_type'      => Helper::ECM_FIELD_GROUP_POST_TYPE_NAME,
			'title'          => $title,
			'posts_per_page' => 1,
			'post_status'    => 'any',
		] );
		return $posts[0] ?? null;
	}

	private function create_field_group_from_import( $data ) {
		$post_content = $data['post_content'];
		
		$post_id = wp_insert_post( [
			'post_title'   => sanitize_text_field( $data['post_title'] ),
			'post_name'    => sanitize_title( $data['post_name'] ?? $data['post_title'] ),
			'post_content' => maybe_serialize( $post_content ),
			'post_status'  => $data['post_status'] ?? 'publish',
			'post_type'    => Helper::ECM_FIELD_GROUP_POST_TYPE_NAME,
		], true );

		if ( ! is_wp_error( $post_id ) && isset( $data['meta'] ) ) {
			foreach ( $data['meta'] as $meta_key => $meta_value ) {
				update_post_meta( $post_id, $meta_key, $meta_value );
			}
		}

		if ( ! is_wp_error( $post_id ) && isset( $post_content['location'] ) ) {
			$field_group_location = Helper::get_post_types_from_location_array( $post_content['location'] );
			update_post_meta( $post_id, 'ecm_field_group_location', maybe_serialize( $field_group_location ) );
		}

		return $post_id;
	}

	private function update_field_group_from_import( $post_id, $data ) {
		$post_content = $data['post_content'];
		
		$result = wp_update_post( [
			'ID'           => $post_id,
			'post_title'   => sanitize_text_field( $data['post_title'] ),
			'post_name'    => sanitize_title( $data['post_name'] ?? $data['post_title'] ),
			'post_content' => maybe_serialize( $post_content ),
		], true );

		if ( ! is_wp_error( $result ) && isset( $data['meta'] ) ) {
			foreach ( $data['meta'] as $meta_key => $meta_value ) {
				update_post_meta( $post_id, $meta_key, $meta_value );
			}
		}

		if ( ! is_wp_error( $result ) && isset( $post_content['location'] ) ) {
			$field_group_location = Helper::get_post_types_from_location_array( $post_content['location'] );
			update_post_meta( $post_id, 'ecm_field_group_location', maybe_serialize( $field_group_location ) );
		}

		return $result;
	}

	private function get_all_field_groups() {
		$query = new WP_Query( [
			'post_type'      => Helper::ECM_FIELD_GROUP_POST_TYPE_NAME,
			'posts_per_page' => -1,
			'post_status'    => 'any',
		] );

		$groups = [];
		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) {
				$query->the_post();
				$post = get_post();
				$groups[] = [
					'ID'           => $post->ID,
					'post_title'   => $post->post_title,
					'post_name'    => $post->post_name,
					'post_content' => maybe_unserialize( $post->post_content ),
					'post_status'  => $post->post_status,
					'meta'         => get_post_meta( $post->ID ),
				];
			}
			wp_reset_postdata();
		}
		return $groups;
	}
	
	private function get_base_settings() {
		$possible_names = [
			defined( 'EASY_CONTENT_MANAGER_SETTINGS_NAME' ) ? constant( 'EASY_CONTENT_MANAGER_SETTINGS_NAME' ) : null,
			'easy_content_manager_settings',
			'ecm_settings'
		];
		
		$main_settings = [];
		$main_option_name = '';
		
		foreach ( $possible_names as $option_name ) {
			if ( ! $option_name ) continue;
			
			$settings = get_option( $option_name, false );
			
			if ( $settings !== false ) {
				if ( is_string( $settings ) ) {
					$settings = json_decode( $settings, true );
				}
				
				$main_settings = $settings ?: [];
				$main_option_name = $option_name;
				break;
			}
		}
		
		if ( empty( $main_option_name ) ) {
			$main_option_name = 'easy_content_manager_settings';
		}

		$addon_settings = [];
		$addon_option_names = [
			'ecm_addons_settings',
			'easy_content_manager_addons_settings'
		];

		if ( defined( 'EASY_CONTENT_MANAGER_ADDONS_SETTINGS_NAME' ) ) {
			array_unshift( $addon_option_names, constant( 'EASY_CONTENT_MANAGER_ADDONS_SETTINGS_NAME' ) );
		}
		
		foreach ( $addon_option_names as $addon_option ) {
			$addons = get_option( $addon_option, false );
			if ( $addons !== false ) {
				if ( is_string( $addons ) ) {
					$addons = json_decode( $addons, true );
				}
				$addon_settings = $addons ?: [];
				break;
			}
		}

		return [
			'option_name' => $main_option_name,
			'data' => $main_settings,
			'addon_settings' => $addon_settings
		];
	}

	private function import_base_settings_data( $data ) {
		$settings_option = 'easy_content_manager_settings';
		
		if ( defined( 'EASY_CONTENT_MANAGER_SETTINGS_NAME' ) ) {
			$settings_option = constant( 'EASY_CONTENT_MANAGER_SETTINGS_NAME' );
		}

		$json_data = is_string( $data ) ? $data : wp_json_encode( $data );
		
		delete_option( $settings_option );
		
		$result = add_option( $settings_option, $json_data, '', 'no' );
		
		return $result;
	}

	private function import_addon_settings_data( $addon_data ) {
		if ( empty( $addon_data ) ) {
			return true;
		}
		
		$addon_option = 'ecm_addons_settings';
		
		if ( defined( 'EASY_CONTENT_MANAGER_ADDONS_SETTINGS_NAME' ) ) {
			$addon_option = constant( 'EASY_CONTENT_MANAGER_ADDONS_SETTINGS_NAME' );
		}
		
		$current_addons = (array) json_decode( get_option( $addon_option, '{}' ), true );
		
		$json_addon_data = is_string( $addon_data ) ? $addon_data : wp_json_encode( $addon_data );
		
		delete_option( $addon_option );
		$result = add_option( $addon_option, $json_addon_data, '', 'no' );
		
		if ( $result && is_array( $addon_data ) ) {
			foreach ( $addon_data as $addon_slug => $status ) {
				$status = (bool) $status;
				$was_active = isset( $current_addons[ $addon_slug ] ) ? (bool) $current_addons[ $addon_slug ] : false;
				
				if ( $status && ! $was_active ) {
					do_action( 'easy_content_manager/before_active_addon', $addon_slug, [] );
					
					do_action( "easy-content-manager/addons/activated_{$addon_slug}", $status );
				} elseif ( ! $status && $was_active ) {
					do_action( "easy-content-manager/addons/deactivated_{$addon_slug}", $status );
				}
			}
		}
		
		return $result;
	}
}