<?php

namespace MOWCPS\Common\Services\Import_Supplier;

use MOWCPS\Common\Handlers\Rest_API\Supplier_Handler;
use MOWCPS\Common\Models\Supplier_Model;
use MOWCPS\Common\Services\Logging\Supplier_Logger;
use MOWCPS\Common\Suppliers\Import_Supplier as Supplier_Import;

/**
 * Class Import_Supplier
 *
 * Handles import of suppliers
 */
class Import_Supplier {
	/**
	 * Handler instance
	 *
	 * @var Supplier_Handler
	 */
	private $handler;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->handler = new Supplier_Handler();
	}

	/**
	 * Import supplier
	 *
	 * @param array $data Supplier data.
	 * @param bool  $overwrite_if_exist Whether to overwrite existing suppliers if they exist.
	 * @return array Import results.
	 */
	public function import_supplier( $data, $overwrite_if_exist ) {
		$total         = count( $data );
		$results       = array();
		$created_count = 0;
		$failed_count  = 0;

		// Get all existing suppliers from the database (with id, name, and uuid for duplicate checking, logging, and deletion).
		$existing_suppliers = Supplier_Model::get_all( array( 'columns' => array( 'id', 'name', 'uuid' ) ) );
		$existing_names     = array();
		$suppliers_by_name  = array();
		if ( ! is_wp_error( $existing_suppliers ) && is_array( $existing_suppliers ) ) {
			foreach ( $existing_suppliers as $supplier ) {
				if ( isset( $supplier['name'] ) ) {
					$existing_names[]                       = $supplier['name'];
					$suppliers_by_name[ $supplier['name'] ] = $supplier;
				}
			}
		}

		foreach ( $data as $index => $supplier_item ) {
			$name = is_array( $supplier_item ) && isset( $supplier_item['name'] ) ? $supplier_item['name'] : '';

			if ( ! empty( $name ) && in_array( $name, $existing_names, true ) ) {
				if ( $overwrite_if_exist ) {
					$existing_supplier = isset( $suppliers_by_name[ $name ] ) ? $suppliers_by_name[ $name ] : null;

					if ( $existing_supplier && isset( $existing_supplier['uuid'] ) ) {
						// Delete the existing supplier using Supplier_Handler.
						$delete_result = $this->handler->delete( $existing_supplier['uuid'] );

						if ( is_wp_error( $delete_result ) ) {
							if ( isset( $existing_supplier['id'] ) ) {
								Supplier_Logger::debug(
									$existing_supplier['id'],
									sprintf( 'Bulk import: Failed to delete existing supplier "%s" (index: %d) for overwrite. Error: %s', $name, $index, $delete_result->get_error_message() )
								);
							}

							++$failed_count;
							$results[] = array(
								'index'   => $index,
								'name'    => $name,
								'status'  => 'error',
								'message' => sprintf( 'Failed to delete existing supplier "%s" for overwrite: %s', $name, $delete_result->get_error_message() ),
							);
							continue;
						}

						if ( isset( $existing_supplier['id'] ) ) {
							Supplier_Logger::debug(
								$existing_supplier['id'],
								sprintf( 'Bulk import: Deleted existing supplier "%s" (index: %d) for overwrite.', $name, $index )
							);
						}

						$name_index = array_search( $name, $existing_names, true );
						if ( false !== $name_index ) {
							unset( $existing_names[ $name_index ] );
						}
						unset( $suppliers_by_name[ $name ] );
					} else {
						++$failed_count;
						$results[] = array(
							'index'   => $index,
							'name'    => $name,
							'status'  => 'error',
							'message' => sprintf( 'Cannot overwrite supplier "%s": UUID not found.', $name ),
						);
						continue;
					}
				} else {
					$error_message = sprintf( 'Supplier "%s" already exists and cannot be created.', $name );

					if ( isset( $suppliers_by_name[ $name ] ) && isset( $suppliers_by_name[ $name ]['id'] ) ) {
						Supplier_Logger::debug(
							$suppliers_by_name[ $name ]['id'],
							sprintf( 'Bulk import: Attempted to import duplicate supplier "%s" (index: %d). Error: %s', $name, $index, $error_message )
						);
					}

					++$failed_count;
					$results[] = array(
						'index'   => $index,
						'name'    => $name,
						'status'  => 'error',
						'message' => $error_message,
					);
					continue;
				}
			}

			$import_class = new Supplier_Import();
			$response     = $import_class->import_each_supplier( $supplier_item );

			if ( is_wp_error( $response ) ) {
				++$failed_count;
				$results[] = array(
					'index'   => $index,
					'name'    => $name,
					'status'  => 'error',
					'message' => $response->get_error_message(),
				);
				continue;
			}

			if ( $response instanceof WP_REST_Response ) {
				$response_data = $response->get_data();
			} else {
				$response_data = $response;
			}

			$supplier_data = $response_data;
			if ( isset( $response_data['data'] ) && is_array( $response_data['data'] ) ) {
				$supplier_data = $response_data['data'];
			}

			$supplier_uuid_result = isset( $supplier_data['uuid'] ) ? $supplier_data['uuid'] : null;

			$supplier_id_result = null;
			if ( $supplier_uuid_result ) {
				$supplier_model = Supplier_Model::get_by_uuid( $supplier_uuid_result );
				if ( $supplier_model && isset( $supplier_model['id'] ) ) {
					$supplier_id_result = $supplier_model['id'];
				}
			}

			++$created_count;
			$results[] = array(
				'index'  => $index,
				'name'   => $name,
				'status' => 'success',
				'id'     => $supplier_id_result,
				'uuid'   => $supplier_uuid_result,
			);
		}

		$payload = array(
			'total'         => $total,
			'created_count' => $created_count,
			'failed_count'  => $failed_count,
			'results'       => $results,
		);

		return $payload;
	}
}
