<?php
/**
 * File Path: includes/import/csv/class-mbs-child-importer-csv-parse.php
 *
 * CSV Importer – Parse Child Class
 *
 * Handles file validation, header parsing, and preview row collection
 * that was previously inside the monolithic class-mbs-importer-csv.php.
 *
 * Delegates validation to MBS_Child_Importer_CSV_Helpers.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

/**
 * Child class responsible for parsing CSV headers and collecting preview rows
 * for the column-mapping UI in the Import/Export tab.
 */
class MBS_Child_Importer_CSV_Parse { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Parse headers from an uploaded CSV file and return detected columns
	 * plus a first-row preview for the column-mapping UI in Tab 5.
	 *
	 * @param string $file_path Absolute path to the uploaded temporary file.
	 * @return array{
	 *   success: bool,
	 *   columns: string[],
	 *   preview: array[],
	 *   error: string
	 * }
	 */
	public static function parse_headers( string $file_path ): array {
		$validation = MBS_Child_Importer_CSV_Helpers::validate_file( $file_path );
		if ( true !== $validation ) {
			return array( 'success' => false, 'columns' => array(), 'preview' => array(), 'error' => $validation );
		}

		// Auto-detect delimiter before opening with fgetcsv so the correct
		// separator is used throughout.
		$delimiter = MBS_Child_Importer_CSV_Helpers::detect_delimiter( $file_path );

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
		$handle = fopen( $file_path, 'r' );
		if ( false === $handle ) {
			return array( 'success' => false, 'columns' => array(), 'preview' => array(), 'error' => 'Could not open file.' );
		}

		$raw_headers = fgetcsv( $handle, 0, $delimiter );
		if ( false === $raw_headers ) {
			fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- WP_Filesystem migration deferred to PC-FILESYS sprint; PHP native file ops are safe here (temp files in get_temp_dir(), never inside wp-content)
			return array( 'success' => false, 'columns' => array(), 'preview' => array(), 'error' => 'File appears empty or is not a valid CSV.' );
		}


		// Strip UTF-8 BOM from the first header field — fgetcsv() does not remove it.
		if ( ! empty( $raw_headers[0] ) && str_starts_with( $raw_headers[0], "\xEF\xBB\xBF" ) ) {
			$raw_headers[0] = substr( $raw_headers[0], 3 );
		}

		$headers = array_map( 'strtolower', array_map( 'trim', $raw_headers ) );

		// Collect up to 3 preview rows for the mapping UI.
		$preview = array();
		$count   = 0;
		while ( ( $row = fgetcsv( $handle, 0, $delimiter ) ) !== false && $count < 3 ) {
			$preview[] = array_combine( $headers, array_pad( $row, count( $headers ), '' ) );
			$count++;
		}

		fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- WP_Filesystem migration deferred to PC-FILESYS sprint; PHP native file ops are safe here (temp files in get_temp_dir(), never inside wp-content)

		return array(
			'success' => true,
			'columns' => $headers,
			'preview' => $preview,
			'error'   => '',
		);
	}
}
