<?php
/**
 * Import/Export functionality for locations (CSV).
 *
 * @package SEOvaultSEO\LocalSEO
 */

namespace SEOvaultSEO\LocalSEO;

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

class ImportExport {

	public static function init() {
		add_action( 'admin_post_seovault_local_export', array( __CLASS__, 'handle_export' ) );
		add_action( 'admin_post_seovault_local_import', array( __CLASS__, 'handle_import' ) );
	}

	public static function render_import_export_section() {
		?>
		<h3><?php esc_html_e( 'Export Locations', 'seovault-ai' ); ?></h3>
		<p><?php esc_html_e( 'Export all locations to a CSV file.', 'seovault-ai' ); ?></p>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="seovault_local_export">
			<?php wp_nonce_field( 'seovault_local_export' ); ?>
			<?php submit_button( __( 'Export CSV', 'seovault-ai' ), 'secondary' ); ?>
		</form>

		<hr>

		<h3><?php esc_html_e( 'Import Locations', 'seovault-ai' ); ?></h3>
		<p><?php esc_html_e( 'Import locations from a CSV file. The file must have a header row with column names matching the field keys.', 'seovault-ai' ); ?></p>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
			<input type="hidden" name="action" value="seovault_local_import">
			<?php wp_nonce_field( 'seovault_local_import' ); ?>
			<table class="form-table">
				<tr>
					<th scope="row"><label for="import_file"><?php esc_html_e( 'CSV File', 'seovault-ai' ); ?></label></th>
					<td><input type="file" name="import_file" id="import_file" accept=".csv"></td>
				</tr>
			</table>
			<?php submit_button( __( 'Import CSV', 'seovault-ai' ), 'primary' ); ?>
		</form>
		<?php
	}

	public static function handle_export() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized.', 'seovault-ai' ) );
		}

		check_admin_referer( 'seovault_local_export' );

		$pt    = PostType::get_post_type();
		$query = new \WP_Query(
			array(
				'post_type'      => $pt,
				'post_status'    => 'any',
				'posts_per_page' => -1,
			)
		);

		$field_keys = array_keys( LocationMeta::get_fields() );
		$days       = OpeningHours::get_days();

		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename=seovault-locations-' . gmdate( 'Y-m-d' ) . '.csv' );

		// phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Streaming CSV via php://output; fputcsv() requires a native handle.
		$out = fopen( 'php://output', 'w' );

		$headers = array_merge( array( 'post_title', 'post_status' ), $field_keys );
		foreach ( $days as $day ) {
			$headers[] = 'opening_hours_' . $day . '_from';
			$headers[] = 'opening_hours_' . $day . '_to';
			$headers[] = 'opening_hours_' . $day . '_second_from';
			$headers[] = 'opening_hours_' . $day . '_second_to';
			$headers[] = 'opening_hours_' . $day . '_24h';
		}
		fputcsv( $out, $headers );

		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) {
				$query->the_post();
				$post_id = get_the_ID();
				$meta    = LocationMeta::get_all( $post_id );

				$row = array( get_the_title( $post_id ), get_post_status( $post_id ) );
				foreach ( $field_keys as $key ) {
					$row[] = $meta[ $key ];
				}
				foreach ( $days as $day ) {
					$h     = $meta['opening_hours'][ $day ] ?? array();
					$row[] = $h['_from'] ?? '';
					$row[] = $h['_to'] ?? '';
					$row[] = $h['_second_from'] ?? '';
					$row[] = $h['_second_to'] ?? '';
					$row[] = $h['_24h'] ?? '';
				}
				fputcsv( $out, $row );
			}
			wp_reset_postdata();
		}

		fclose( $out );
		// phpcs:enable WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.WP.AlternativeFunctions.file_system_operations_fclose
		exit;
	}

	public static function handle_import() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized.', 'seovault-ai' ) );
		}

		check_admin_referer( 'seovault_local_import' );

		$tmp_name = isset( $_FILES['import_file']['tmp_name'] )
			? sanitize_text_field( wp_unslash( $_FILES['import_file']['tmp_name'] ) )
			: '';
		if ( '' === $tmp_name || ! is_uploaded_file( $tmp_name ) ) {
			wp_safe_redirect( admin_url( 'admin.php?page=seovault-ai-general&tab=vtab-local-seo&import_error=no_file' ) );
			exit;
		}

		// phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Reading uploaded CSV with fgetcsv(); WP_Filesystem is not suitable for row parsing.
		$fh = fopen( $tmp_name, 'r' );

		if ( ! $fh ) {
			wp_safe_redirect( admin_url( 'admin.php?page=seovault-ai-general&tab=vtab-local-seo&import_error=cannot_read' ) );
			exit;
		}

		$headers    = fgetcsv( $fh );
		$imported   = 0;
		$pt         = PostType::get_post_type();
		$field_keys = array_keys( LocationMeta::get_fields() );
		$days       = OpeningHours::get_days();

		while ( ( $row = fgetcsv( $fh ) ) !== false ) {
			if ( count( $row ) < 2 ) {
				continue;
			}

			$data = array_combine( $headers, $row );
			if ( false === $data ) {
				continue;
			}

			$post_title  = $data['post_title'] ?? '';
			$post_status = $data['post_status'] ?? 'publish';

			if ( '' === trim( $post_title ) ) {
				continue;
			}

			$post_id = wp_insert_post(
				array(
					'post_title'  => sanitize_text_field( $post_title ),
					'post_type'   => $pt,
					'post_status' => in_array( $post_status, array( 'publish', 'draft', 'pending', 'private' ), true ) ? $post_status : 'publish',
				)
			);

			if ( is_wp_error( $post_id ) || 0 === $post_id ) {
				continue;
			}

			$meta_data = array();
			foreach ( $field_keys as $key ) {
				if ( isset( $data[ $key ] ) ) {
					$meta_data[ $key ] = $data[ $key ];
				}
			}

			$hours_data = array();
			foreach ( $days as $day ) {
				$hours_data[ $day ] = array(
					'_from'        => $data[ 'opening_hours_' . $day . '_from' ] ?? '',
					'_to'          => $data[ 'opening_hours_' . $day . '_to' ] ?? '',
					'_second_from' => $data[ 'opening_hours_' . $day . '_second_from' ] ?? '',
					'_second_to'   => $data[ 'opening_hours_' . $day . '_second_to' ] ?? '',
					'_24h'         => $data[ 'opening_hours_' . $day . '_24h' ] ?? '',
				);
			}
			$meta_data['opening_hours'] = $hours_data;

			LocationMeta::set_all( $post_id, $meta_data );
			++$imported;
		}

		fclose( $fh );
		// phpcs:enable WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.WP.AlternativeFunctions.file_system_operations_fclose

		wp_safe_redirect( admin_url( 'admin.php?page=seovault-ai-general&tab=vtab-local-seo&imported=' . $imported ) );
		exit;
	}

	public static function generate_csv_row( $post_id ) {
		$meta       = LocationMeta::get_all( $post_id );
		$field_keys = array_keys( LocationMeta::get_fields() );
		$days       = OpeningHours::get_days();

		$row = array( get_the_title( $post_id ), get_post_status( $post_id ) );
		foreach ( $field_keys as $key ) {
			$row[] = $meta[ $key ];
		}
		foreach ( $days as $day ) {
			$h     = $meta['opening_hours'][ $day ] ?? array();
			$row[] = $h['_from'] ?? '';
			$row[] = $h['_to'] ?? '';
			$row[] = $h['_second_from'] ?? '';
			$row[] = $h['_second_to'] ?? '';
			$row[] = $h['_24h'] ?? '';
		}

		return $row;
	}
}
