<?php

namespace WarrantyCart\Admin\Product;

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

/**
 * Admin Product Import Class
 *
 * Handles CSV import functionality for warranty products.
 */
class Import {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'admin_post_warranty_import_csv', array( $this, 'handle_csv_import' ) );
	}

	/**
	 * Handle CSV import
	 *
	 * Processes the CSV import request from the admin interface.
	 */
	public function handle_csv_import(): void {
		if ( ! isset( $_POST['warranty_import_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['warranty_import_nonce'] ) ), 'warranty_import_csv' ) ) {
			warranty_cart()->log( 'CSV import security check failed - invalid nonce', 'warning' );
			wp_die( esc_html__( 'Security check failed.', 'warranty-cart' ) );
		}

		if ( ! current_user_can( 'import_warranty_products' ) ) {
			warranty_cart()->log( 'CSV import access denied - insufficient permissions for user: ' . get_current_user_id(), 'warning' );
			wp_die( esc_html__( 'Insufficient permissions.', 'warranty-cart' ) );
		}

		// Validate and sanitize file upload
		if ( empty( $_FILES['csv_file']['tmp_name'] ) ) {
			wp_safe_redirect( add_query_arg( 'import_error', 'no_file', wp_get_referer() ) );
			exit;
		}

		// Use WordPress file validation functions
		$file_upload = wp_handle_upload(
			$_FILES['csv_file'],
			array(
				'test_form'            => false,
				'upload_error_handler' => function ( $file, $message ) {
					warranty_cart()->log( 'File upload error: ' . $message, 'error' );
					wp_safe_redirect( add_query_arg( 'import_error', 'upload_failed', wp_get_referer() ) );
					exit;
				},
			)
		);

		if ( isset( $file_upload['error'] ) ) {
			warranty_cart()->log( 'File upload error: ' . $file_upload['error'], 'error' );
			wp_safe_redirect( add_query_arg( 'import_error', 'upload_failed', wp_get_referer() ) );
			exit;
		}

		$file_path = $file_upload['file'];
		$category  = sanitize_text_field( wp_unslash( $_POST['category'] ?? 'warranties' ) );

		// Additional validation for CSV files
		$mime_type      = wp_get_image_mime( $file_path ); // This works for any file type
		$allowed_mimes  = array( 'text/csv', 'application/csv', 'text/plain' );
		$file_extension = strtolower( pathinfo( $file_upload['url'], PATHINFO_EXTENSION ) );

		if ( ! in_array( $mime_type, $allowed_mimes, true ) && 'csv' !== $file_extension ) {
			// Clean up uploaded file
			wp_delete_file( $file_path );
			wp_safe_redirect( add_query_arg( 'import_error', 'invalid_file', wp_get_referer() ) );
			exit;
		}

		$imported = $this->process_csv_import( $file_path, $category );

		// Clean up uploaded file after processing
		wp_delete_file( $file_path );

		wp_safe_redirect( add_query_arg( array( 'imported' => $imported ), wp_get_referer() ) );
		exit;
	}

	/**
	 * Process CSV import
	 *
	 * @param string $file_path CSV file path.
	 * @param string $category  Product category.
	 *
	 * @return int Number of imported products.
	 */
	public function process_csv_import( string $file_path, string $category ): int {
		$imported = 0;
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
		$handle = fopen( $file_path, 'r' );

		if ( false === $handle ) {
			return 0;
		}

		// Get header row
		$header = fgetcsv( $handle );
		if ( ! $header ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
			fclose( $handle );

			return 0;
		}

		// Process each row
		$row = fgetcsv( $handle );
		while ( false !== $row ) {
			if ( count( $row ) < 3 ) {
				$row = fgetcsv( $handle );
				continue; // Skip incomplete rows
			}

			$data = array_combine( $header, $row );
			if ( ! $data || empty( $data['name'] ) || empty( $data['price'] ) ) {
				$row = fgetcsv( $handle );
				continue;
			}

			if ( $this->create_warranty_product( $data, $category ) ) {
				++$imported;
				warranty_cart()->log( "Successfully imported warranty product: {$data['name']}", 'info' );
			} else {
				warranty_cart()->log( "Failed to import warranty product: {$data['name']}", 'warning' );
			}
			$row = fgetcsv( $handle );
		}

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
		fclose( $handle );

		return $imported;
	}

	/**
	 * Validate CSV headers.
	 *
	 * @param array $headers CSV header row.
	 * @return bool Whether headers are valid.
	 */
	public function validate_csv_headers( array $headers ): bool {
		$required = array( 'name', 'description', 'price', 'type' );
		foreach ( $required as $field ) {
			if ( ! in_array( $field, $headers, true ) ) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Validate a single CSV data row.
	 *
	 * @param array $data Associative array of row data.
	 * @return bool Whether the row is valid.
	 */
	public function validate_csv_data( array $data ): bool {
		return ! empty( $data['name'] );
	}

	/**
	 * Create a warranty product from CSV row data.
	 *
	 * @param array  $data     Associative product data (name, description, price, type).
	 * @param string $category Product category slug.
	 * @return int Created product ID, or 0 on failure.
	 */
	public function create_product_from_csv( array $data, string $category ): int {
		$product = new \WC_Product_Simple();
		$product->set_name( sanitize_text_field( $data['name'] ) );
		$product->set_description( sanitize_textarea_field( $data['description'] ?? '' ) );
		$product->set_regular_price( floatval( $data['price'] ) );
		$product->set_virtual( true );
		$product->set_catalog_visibility( 'hidden' );

		$product_id = $product->save();
		if ( ! $product_id ) {
			return 0;
		}

		wp_set_object_terms( $product_id, $category, 'product_cat' );

		$type = isset( $data['type'] ) && 'main_warranty' === $data['type'] ? 'main_warranty' : 'additional_service';
		$product->update_meta_data( '_warranty_product_type', $type );
		$product->save();

		return $product_id;
	}

	/**
	 * Create warranty product from CSV data
	 *
	 * @param array  $data     Product data.
	 * @param string $category Product category.
	 *
	 * @return bool Success status.
	 */
	private function create_warranty_product( array $data, string $category ): bool {
		$product = new \WC_Product_Simple();

		$product->set_name( sanitize_text_field( $data['name'] ) );
		$product->set_description( sanitize_textarea_field( $data['description'] ?? '' ) );
		$product->set_regular_price( floatval( $data['price'] ) );
		$product->set_virtual( true );
		$product->set_catalog_visibility( 'hidden' );

		if ( ! empty( $data['sku'] ) ) {
			$product->set_sku( sanitize_text_field( $data['sku'] ) );
		}

		$product_id = $product->save();

		if ( $product_id ) {
			// Set category
			wp_set_object_terms( $product_id, $category, 'product_cat' );

			// Set warranty type
			$is_main      = isset( $data['is_main_warranty'] ) && 'yes' === strtolower( $data['is_main_warranty'] );
			$product_type = $is_main ? 'main_warranty' : 'additional_service';
			$product->update_meta_data( '_warranty_product_type', $product_type );
			$product->save();

			return true;
		}

		return false;
	}
}
