<?php

namespace RadiusTheme\RadiusBooking\ExportImport\Importers;

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

use RadiusTheme\RadiusBooking\ExportImport\Contracts\ImporterInterface;
use RadiusTheme\RadiusBooking\ExportImport\IdMapper;
use RadiusTheme\RadiusBooking\Models\User;
use RadiusTheme\RadiusBooking\Models\UserProfile;

/**
 * Class CustomerImporter
 *
 * Imports customers with profiles and ID remapping.
 *
 * @package RadiusTheme\RadiusBooking\ExportImport\Importers
 */
class CustomerImporter implements ImporterInterface {

	/**
	 * {@inheritDoc}
	 */
	public function getModuleName(): string {
		return 'customer';
	}

	/**
	 * {@inheritDoc}
	 */
	public function import( array $records, IdMapper $id_mapper ): int {
		$imported = 0;

		foreach ( $records as $record ) {
			$old_id  = (int) ( $record['id'] ?? 0 );
			$profile = $record['profile'] ?? null;
			unset( $record['id'], $record['profile'] );
			unset( $record['created_at'], $record['updated_at'] );

			// Check for duplicate email.
			$existing = User::where( 'email', $record['email'] ?? '' )->first();
			if ( $existing ) {
				// Map old ID to existing user and skip creation.
				if ( $old_id ) {
					$id_mapper->addMapping( 'customer', $old_id, (int) $existing->id );
				}
				++$imported;
				continue;
			}

			// Generate random password for security.
			$record['password'] = wp_hash_password( wp_generate_password( 16 ) );

			$user = User::create( $record );

			if ( $user && $old_id ) {
				$new_id = (int) $user->id;
				$id_mapper->addMapping( 'customer', $old_id, $new_id );

				// Create profile.
				if ( $profile ) {
					unset( $profile['created_at'], $profile['updated_at'] );
					$profile['user_id']    = $new_id;
					$profile['wp_user_id'] = null; // Site-specific.
					$profile['image_id']   = null; // Site-specific.
					UserProfile::create( $profile );
				}

				++$imported;
			}
		}

		return $imported;
	}

	/**
	 * {@inheritDoc}
	 */
	public function getDependencies(): array {
		return array();
	}
}
