<?php

namespace RadiusTheme\RadiusBooking\ExportImport\Exporters;

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

use RadiusTheme\RadiusBooking\ExportImport\Contracts\ExporterInterface;
use RadiusTheme\RadiusBooking\Models\User;
use RadiusTheme\RadiusBooking\Models\UserProfile;

/**
 * Class CustomerExporter
 *
 * Exports customers (users with type=customer) and their profiles.
 *
 * @package RadiusTheme\RadiusBooking\ExportImport\Exporters
 */
class CustomerExporter implements ExporterInterface {

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

	/**
	 * {@inheritDoc}
	 */
	public function count(): int {
		return User::where( 'user_type', 'customer' )->count();
	}

	/**
	 * {@inheritDoc}
	 */
	public function export( int $offset = 0, int $limit = 500 ): array {
		$rows    = User::where( 'user_type', 'customer' )->offset( $offset )->limit( $limit )->get();
		$records = array();

		foreach ( $rows as $row ) {
			$user = User::hydrate( $row );
			$data = $user->toArray();

			// Remove sensitive data.
			unset( $data['password'], $data['token'] );

			// Attach profile.
			$profile_row = UserProfile::where( 'user_id', (int) $data['id'] )->first();
			if ( $profile_row ) {
				$profile         = UserProfile::hydrate( $profile_row );
				$profile_data    = $profile->toArray();
				unset( $profile_data['id'] );
				$data['profile'] = $profile_data;
			}

			$records[] = $data;
		}

		return $records;
	}

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