<?php
// phpcs:disable WordPress.DB.SlowDBQuery
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Add Import/Export submenu under Price Lists — Pro only
function chcpl_add_import_export_page() {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' ) ) ) {
		return;
	}
	add_submenu_page(
		'edit.php?post_type=price_list',
		__( 'Import / Export', 'ad-pro-price-list' ),
		__( 'Import / Export', 'ad-pro-price-list' ),
		'manage_options',
		'chcpl_import_export',
		'chcpl_render_import_export_page'
	);
}
add_action( 'admin_menu', 'chcpl_add_import_export_page' );

function chcpl_render_import_export_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	// Handle Import request
	if ( isset( $_POST['chcpl_do_import'] ) && check_admin_referer( 'chcpl_import', 'chcpl_import_nonce' ) ) {
		$overwrite_settings = ! empty( $_POST['chcpl_overwrite_settings'] );
		$attach_as_draft = ! empty( $_POST['chcpl_import_draft'] );
		$target_list_title_prefix = isset( $_POST['chcpl_title_prefix'] ) ? sanitize_text_field( wp_unslash( $_POST['chcpl_title_prefix'] ) ) : '';
		$import_result = chcpl_handle_import( $overwrite_settings, $attach_as_draft, $target_list_title_prefix );
		if ( is_wp_error( $import_result ) ) {
			echo '<div class="notice notice-error"><p>' . esc_html( $import_result->get_error_message() ) . '</p></div>';
		} else {
			echo '<div class="notice notice-success"><p>' . esc_html__( 'Import completed successfully.', 'ad-pro-price-list' ) . '</p></div>';
		}
	}

	$lists = get_posts( array(
		'post_type' => 'price_list',
		'numberposts' => -1,
		'post_status' => array( 'publish', 'draft' ),
		'orderby' => 'title',
		'order' => 'ASC',
	) );
	?>
	<div class="wrap chcpl-admin">
		<h1><?php echo esc_html__( 'Import / Export Price Lists', 'ad-pro-price-list' ); ?></h1>

		<div class="chcpl-card" style="max-width:680px;margin-top:16px;">
			<h2 class="chcpl-card-title"><?php echo esc_html__( 'Export', 'ad-pro-price-list' ); ?></h2>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<input type="hidden" name="action" value="chcpl_export" />
				<?php wp_nonce_field( 'chcpl_export', 'chcpl_export_nonce' ); ?>
				<p>
					<label for="chcpl_export_list_id"><strong><?php echo esc_html__( 'Select Price List', 'ad-pro-price-list' ); ?></strong></label><br />
					<select id="chcpl_export_list_id" name="chcpl_export_list_id" style="min-width:320px;margin-top:6px;">
						<option value="0"><?php echo esc_html__( '— All Price Lists —', 'ad-pro-price-list' ); ?></option>
						<?php foreach ( $lists as $list ) : ?>
							<option value="<?php echo esc_attr( $list->ID ); ?>"><?php echo esc_html( $list->post_title ); ?></option>
						<?php endforeach; ?>
					</select>
				</p>
				<p>
					<label class="chcpl-body"><input type="checkbox" name="chcpl_include_settings" value="1" /> <?php echo esc_html__( 'Include plugin global settings', 'ad-pro-price-list' ); ?></label>
				</p>
				<p>
					<button type="submit" class="chcpl-btn chcpl-btn-green" name="chcpl_do_export" value="1"><?php echo esc_html__( 'Download Export (JSON)', 'ad-pro-price-list' ); ?></button>
				</p>
			</form>
		</div>

		<div class="chcpl-card" style="max-width:680px;">
			<h2 class="chcpl-card-title"><?php echo esc_html__( 'Import', 'ad-pro-price-list' ); ?></h2>
			<form method="post" enctype="multipart/form-data">
				<?php wp_nonce_field( 'chcpl_import', 'chcpl_import_nonce' ); ?>
				<p>
					<label for="chcpl_import_file"><strong><?php echo esc_html__( 'Upload JSON file exported by this plugin', 'ad-pro-price-list' ); ?></strong></label><br />
					<input type="file" id="chcpl_import_file" name="chcpl_import_file" accept="application/json,.json" required style="margin-top:6px;" />
				</p>
				<p>
					<label class="chcpl-body"><input type="checkbox" name="chcpl_overwrite_settings" value="1" /> <?php echo esc_html__( 'Overwrite plugin global settings from file', 'ad-pro-price-list' ); ?></label>
				</p>
				<p>
					<label class="chcpl-body"><input type="checkbox" name="chcpl_import_draft" value="1" /> <?php echo esc_html__( 'Import as draft (lists and services)', 'ad-pro-price-list' ); ?></label>
				</p>
				<p>
					<label for="chcpl_title_prefix"><strong><?php echo esc_html__( 'Title prefix (optional)', 'ad-pro-price-list' ); ?></strong></label><br />
					<input type="text" id="chcpl_title_prefix" name="chcpl_title_prefix" class="regular-text" placeholder="Imported - " style="margin-top:6px;" />
				</p>
				<p>
					<button type="submit" class="chcpl-btn chcpl-btn-green" name="chcpl_do_import" value="1"><?php echo esc_html__( 'Run Import', 'ad-pro-price-list' ); ?></button>
				</p>
			</form>
		</div>
	</div>
	<?php
}

function chcpl_collect_export_data( $list_id = 0, $include_settings = false ) {
	$data = array(
		'plugin' => 'ad-pro-price-list',
		'version' => defined( 'CHCPL_VERSION' ) ? CHCPL_VERSION : '1.0.0',
		'exported_at' => current_time( 'mysql' ),
		'lists' => array(),
		'services' => array(),
		'categories' => array(),
		'settings' => array(),
	);

	$lists_query = array(
		'post_type' => 'price_list',
		'numberposts' => -1,
		'post_status' => array( 'publish', 'draft' ),
	);
	if ( $list_id > 0 ) {
		$lists_query['include'] = array( $list_id );
	}
	$lists = get_posts( $lists_query );

	$list_ids = array();
	foreach ( $lists as $list ) {
		$list_ids[] = $list->ID;
		$data['lists'][] = array(
			'ID' => (int) $list->ID,
			'post_title' => $list->post_title,
			'post_status' => $list->post_status,
			'meta' => array(
				'_chcpl_lock_enabled' => get_post_meta( $list->ID, '_chcpl_lock_enabled', true ),
				'_chcpl_lock_title' => get_post_meta( $list->ID, '_chcpl_lock_title', true ),
				'_chcpl_lock_description' => get_post_meta( $list->ID, '_chcpl_lock_description', true ),
				'_chcpl_lock_expires_type' => get_post_meta( $list->ID, '_chcpl_lock_expires_type', true ),
				'_chcpl_lock_expires' => get_post_meta( $list->ID, '_chcpl_lock_expires', true ),
			),
		);
	}

	// Services attached to lists
	if ( ! empty( $list_ids ) ) {
		$services = get_posts( array(
			'post_type' => 'price_service',
			'numberposts' => -1,
			'post_status' => array( 'publish', 'draft' ),
			'meta_query' => array(
				array(
					'key' => '_chcpl_list_id',
					'value' => $list_ids,
					'compare' => 'IN',
				),
			),
		) );
	} else {
		$services = get_posts( array(
			'post_type' => 'price_service',
			'numberposts' => -1,
			'post_status' => array( 'publish', 'draft' ),
		) );
	}

	$category_ids = array();
	foreach ( $services as $service ) {
		$terms = wp_get_post_terms( $service->ID, 'price_category' );
		foreach ( $terms as $t ) {
			$category_ids[ $t->term_id ] = true;
		}
		$image_id = (int) get_post_meta( $service->ID, '_chcpl_service_image', true );
		$data['services'][] = array(
			'ID' => (int) $service->ID,
			'post_title' => $service->post_title,
			'post_status' => $service->post_status,
			'menu_order' => (int) $service->menu_order,
			'list_id' => (int) get_post_meta( $service->ID, '_chcpl_list_id', true ),
			'categories' => wp_list_pluck( $terms, 'name' ),
			'category_slugs' => wp_list_pluck( $terms, 'slug' ),
			'category_ids' => wp_list_pluck( $terms, 'term_id' ),
			'image_id' => $image_id,
			'image_url' => $image_id ? wp_get_attachment_image_url( $image_id, 'full' ) : '',
			'meta' => array(
				'_chcpl_service_description' => get_post_meta( $service->ID, '_chcpl_service_description', true ),
				'_chcpl_service_price' => get_post_meta( $service->ID, '_chcpl_service_price', true ),
				'_chcpl_service_sur_devis' => get_post_meta( $service->ID, '_chcpl_service_sur_devis', true ),
				'_chcpl_list_id' => get_post_meta( $service->ID, '_chcpl_list_id', true ),
				'_chcpl_service_image' => $image_id,
			),
		);
	}

	if ( ! empty( $category_ids ) ) {
		$category_ids = array_keys( $category_ids );
		$terms = get_terms( array(
			'taxonomy' => 'price_category',
			'include' => $category_ids,
			'hide_empty' => false,
		) );
		foreach ( $terms as $term ) {
			$data['categories'][] = array(
				'term_id' => (int) $term->term_id,
				'name' => $term->name,
				'slug' => $term->slug,
				'parent' => (int) $term->parent,
				'meta' => array(
					'_chcpl_category_order' => get_term_meta( $term->term_id, '_chcpl_category_order', true ),
					'_chcpl_category_icon' => get_term_meta( $term->term_id, '_chcpl_category_icon', true ),
				),
			);
		}
	}

	if ( $include_settings && function_exists( 'chcpl_get_settings' ) ) {
		$data['settings'] = chcpl_get_settings();
	}

	// Always include global passwords in export
	if ( function_exists( 'chcpl_get_global_passwords' ) ) {
		$data['global_passwords'] = chcpl_get_global_passwords();
	}

	return $data;
}

function chcpl_handle_export( $list_id = 0, $include_settings = false ) {
	$data = chcpl_collect_export_data( $list_id, $include_settings );
	$filename = 'chcpl-export-' . gmdate( 'Y-m-d-His' ) . '.json';
	$json = wp_json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
	if ( ! headers_sent() ) {
		// Force download in all browsers
		header( 'Content-Description: File Transfer' );
		header( 'Content-Type: application/octet-stream' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Transfer-Encoding: binary' );
		header( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0' );
		header( 'Cache-Control: post-check=0, pre-check=0', false );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );
		header( 'Content-Length: ' . strlen( $json ) );
	}
	echo $json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	exit;
}

// Dedicated admin-post handler so headers are sent before any HTML.
function chcpl_handle_export_request() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Unauthorized.', 'ad-pro-price-list' ) );
	}
	check_admin_referer( 'chcpl_export', 'chcpl_export_nonce' );
	$list_id = isset( $_POST['chcpl_export_list_id'] ) ? (int) $_POST['chcpl_export_list_id'] : 0;
	$include_settings = ! empty( $_POST['chcpl_include_settings'] );
	chcpl_handle_export( $list_id, $include_settings );
}
add_action( 'admin_post_chcpl_export', 'chcpl_handle_export_request' );

function chcpl_handle_import( $overwrite_settings, $import_as_draft, $title_prefix ) {
	// phpcs:ignore WordPress.Security.NonceVerification.Missing
	if ( ! isset( $_FILES['chcpl_import_file'] ) || empty( $_FILES['chcpl_import_file']['tmp_name'] ) ) {
		return new WP_Error( 'chcpl_no_file', __( 'No file uploaded.', 'ad-pro-price-list' ) );
	}

	// Use security validation function
	// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
	$file_validation = chcpl_validate_uploaded_file( $_FILES['chcpl_import_file'], 10485760 ); // 10MB max
	if ( is_wp_error( $file_validation ) ) {
		return $file_validation;
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
	$raw = file_get_contents( $_FILES['chcpl_import_file']['tmp_name'] );
	if ( ! $raw ) {
		return new WP_Error( 'chcpl_empty', __( 'Could not read uploaded file.', 'ad-pro-price-list' ) );
	}
	$data = json_decode( $raw, true );
	if ( ! is_array( $data ) || ! isset( $data['plugin'] ) || $data['plugin'] !== 'ad-pro-price-list' ) {
		return new WP_Error( 'chcpl_invalid', __( 'Invalid export file.', 'ad-pro-price-list' ) );
	}

	// Settings
	if ( $overwrite_settings && isset( $data['settings'] ) && is_array( $data['settings'] ) ) {
		$sanitized = function_exists( 'chcpl_sanitize_settings' ) ? chcpl_sanitize_settings( $data['settings'] ) : $data['settings'];
		update_option( 'chcpl_settings', $sanitized );
	}

	// Import global passwords (always import, not just when overwriting settings)
	if ( isset( $data['global_passwords'] ) && is_array( $data['global_passwords'] ) && function_exists( 'chcpl_save_global_passwords' ) ) {
		chcpl_save_global_passwords( $data['global_passwords'] );
	}

	// Import categories first, map by slug
	$term_slug_map = array();
	if ( ! empty( $data['categories'] ) && is_array( $data['categories'] ) ) {
		foreach ( $data['categories'] as $cat ) {
			$name = isset( $cat['name'] ) ? $cat['name'] : '';
			$slug = isset( $cat['slug'] ) ? $cat['slug'] : '';
			$parent_slug = '';
			$parent_id = 0; // Parent relationships by slug are not preserved reliably; create flat then order via meta
			$existing = get_term_by( 'slug', $slug, 'price_category' );
			if ( $existing && ! is_wp_error( $existing ) ) {
				$term_id = (int) $existing->term_id;
			} else {
				$result = wp_insert_term( $name, 'price_category', array( 'slug' => $slug, 'parent' => $parent_id ) );
				if ( is_wp_error( $result ) ) {
					continue;
				}
				$term_id = (int) $result['term_id'];
			}
			$term_slug_map[ $slug ] = $term_id;
			if ( isset( $cat['meta']['_chcpl_category_order'] ) ) {
				update_term_meta( $term_id, '_chcpl_category_order', (int) $cat['meta']['_chcpl_category_order'] );
			}
			if ( isset( $cat['meta']['_chcpl_category_icon'] ) ) {
				$icon_id = (int) $cat['meta']['_chcpl_category_icon'];
				if ( $icon_id > 0 ) {
					update_term_meta( $term_id, '_chcpl_category_icon', $icon_id );
				} else {
					delete_term_meta( $term_id, '_chcpl_category_icon' );
				}
			}
		}
	}

	// Import lists, keep an ID map from old ID to new ID
	$list_id_map = array();
	if ( ! empty( $data['lists'] ) && is_array( $data['lists'] ) ) {
		foreach ( $data['lists'] as $list ) {
			$title = ( $title_prefix ? $title_prefix : '' ) . ( isset( $list['post_title'] ) ? $list['post_title'] : 'Price List' );
			$status = $import_as_draft ? 'draft' : ( isset( $list['post_status'] ) ? $list['post_status'] : 'publish' );
			$new_list_id = wp_insert_post( array(
				'post_type' => 'price_list',
				'post_title' => $title,
				'post_status' => $status,
			), true );
			if ( is_wp_error( $new_list_id ) ) {
				continue;
			}
			$old_id = isset( $list['ID'] ) ? (int) $list['ID'] : 0;
			$list_id_map[ $old_id ] = (int) $new_list_id;
			if ( ! empty( $list['meta'] ) && is_array( $list['meta'] ) ) {
				$allowed_list_meta = array( '_chcpl_lock_enabled', '_chcpl_lock_title', '_chcpl_lock_surtitle', '_chcpl_lock_description', '_chcpl_lock_expires_type', '_chcpl_lock_expires' );
				foreach ( $list['meta'] as $k => $v ) {
					if ( ! in_array( $k, $allowed_list_meta, true ) ) {
						continue;
					}
					update_post_meta( $new_list_id, $k, $v );
				}
			}
		}
	}

	// Import services
	if ( ! empty( $data['services'] ) && is_array( $data['services'] ) ) {
		foreach ( $data['services'] as $service ) {
			$title = ( $title_prefix ? $title_prefix : '' ) . ( isset( $service['post_title'] ) ? $service['post_title'] : 'Service' );
			$status = $import_as_draft ? 'draft' : ( isset( $service['post_status'] ) ? $service['post_status'] : 'publish' );
			$menu_order = isset( $service['menu_order'] ) ? (int) $service['menu_order'] : 0;
			$old_list_id = isset( $service['list_id'] ) ? (int) $service['list_id'] : 0;
			$new_list_id = isset( $list_id_map[ $old_list_id ] ) ? (int) $list_id_map[ $old_list_id ] : 0;

			$new_service_id = wp_insert_post( array(
				'post_type' => 'price_service',
				'post_title' => $title,
				'post_status' => $status,
				'menu_order' => $menu_order,
			), true );
			if ( is_wp_error( $new_service_id ) ) {
				continue;
			}

			// Meta
			if ( ! empty( $service['meta'] ) && is_array( $service['meta'] ) ) {
				$allowed_service_meta = array( '_chcpl_service_description', '_chcpl_service_price', '_chcpl_service_sur_devis', '_chcpl_service_image' );
				foreach ( $service['meta'] as $k => $v ) {
					if ( $k === '_chcpl_list_id' ) {
						update_post_meta( $new_service_id, '_chcpl_list_id', $new_list_id );
					} elseif ( in_array( $k, $allowed_service_meta, true ) ) {
						update_post_meta( $new_service_id, $k, $v );
					}
				}
			} else if ( $new_list_id > 0 ) {
				update_post_meta( $new_service_id, '_chcpl_list_id', $new_list_id );
			}

			// Categories by slug preferred, fallback by name
			$term_ids = array();
			if ( ! empty( $service['category_slugs'] ) && is_array( $service['category_slugs'] ) ) {
				foreach ( $service['category_slugs'] as $slug ) {
					if ( isset( $term_slug_map[ $slug ] ) ) {
						$term_ids[] = (int) $term_slug_map[ $slug ];
					}
				}
			}
			if ( empty( $term_ids ) && ! empty( $service['categories'] ) && is_array( $service['categories'] ) ) {
				foreach ( $service['categories'] as $name ) {
					$term = get_term_by( 'name', $name, 'price_category' );
					if ( $term && ! is_wp_error( $term ) ) {
						$term_ids[] = (int) $term->term_id;
					}
				}
			}
			if ( ! empty( $term_ids ) ) {
				wp_set_post_terms( $new_service_id, $term_ids, 'price_category', false );
			}
		}
	}

	return true;
}


