<?php
/**
 * CSV Importer for Redirects
 *
 * @package SEOvaultSEO\RedirectManager
 */

namespace SEOvaultSEO\RedirectManager;

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

/**
 * Imports redirects from a CSV file.
 */
class CsvImporter {

	/**
	 * Load redirects from a CSV file.
	 *
	 * @param string $csv_file Path to the CSV file.
	 * @return Redirect[] Array of redirect objects.
	 */
	public function load( $csv_file ) {
		if ( ! file_exists( $csv_file ) || ! is_readable( $csv_file ) ) {
			return array();
		}

		// phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Native fgetcsv() parsing; WP_Filesystem does not provide row-based CSV reads.
		$handle = fopen( $csv_file, 'r' );

		if ( ! $handle ) {
			return array();
		}

		$redirects = array();
		$line_num  = 0;

		while ( ( $item = fgetcsv( $handle, 10000, ',', '"', '' ) ) !== false ) {
			++$line_num;

			// Skip header row.
			if ( 1 === $line_num && $this->is_header_row( $item ) ) {
				continue;
			}

			if ( ! $this->validate_row( $item ) ) {
				continue;
			}

			$redirects[] = new Redirect(
				$item[0],
				$item[1],
				(int) $item[2],
				$item[3]
			);
		}

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

		return $redirects;
	}

	/**
	 * Check if a CSV row is the header row.
	 *
	 * @param array $item Parsed CSV row.
	 * @return bool
	 */
	protected function is_header_row( $item ) {
		if ( ! is_array( $item ) || 4 !== count( $item ) ) {
			return false;
		}

		// Check if the first column is "Origin" (case-insensitive).
		return 0 === strcasecmp( trim( $item[0] ), 'Origin' );
	}

	/**
	 * Validate a parsed CSV row.
	 *
	 * Must have exactly 4 values: origin, target, type, format.
	 * Type must be a valid redirect type. Format must be a valid format.
	 *
	 * @param array|false $item Parsed CSV row.
	 * @return bool
	 */
	protected function validate_row( $item ) {
		if ( ! is_array( $item ) || 4 !== count( $item ) ) {
			return false;
		}

		if ( '' === trim( $item[0] ) ) {
			return false;
		}

		if ( ! Redirect::is_valid_type( $item[2] ) ) {
			return false;
		}

		if ( ! Redirect::is_valid_format( $item[3] ) ) {
			return false;
		}

		return true;
	}
}
