<?php
/**
 * Grieg Export Users CLI
 *
 * @package Nisje
 */

declare( strict_types=1 );

namespace Dekode\Nisje\Commands;

use WP_CLI;
use Exception;
use StdClass;
use WP_Post;

if ( class_exists( 'WP_CLI' ) ) {
	/**
	 * Grieg functionality
	 */
	class Grieg_Export_Users {
		/**
		 * Populate data
		 */
		public function export() {
			$users = get_users( [
				'number' => 9999,
			] );

			WP_CLI::line( 'Number of users: ' . count( $users ) );

			WP_CLI::line( 'COUNTER,ID,EMAIL,NAME,ALTNAME,EMPLOYEE NUMBER,WORKPLACE,DEPARTMENT,MAIN GROUP,LOCATION,COMPANY,COMPANY2,SKILLS,ROLE, MEMBER TYPE' );

			$counter = 1;

			foreach ( $users as $user ) {
				$user_meta = get_user_meta( $user->ID );

				$alt_name = '';
				if ( isset( $user_meta['field_1'] ) ) {
					$alt_name = implode( ',', $user_meta['field_1'] );
				}

				$emp_number = '';
				if ( isset( $user_meta['employee_number'] ) ) {
					$emp_number = implode( ',', $user_meta['employee_number'] );
				}

				$workplace = '';
				if ( isset( $user_meta['workplace'] ) ) {
					$workplace = implode( ',', $user_meta['workplace'] );
				}

				$department = '';
				if ( isset( $user_meta['department'] ) ) {
					$department = implode( ',', $user_meta['department'] );
				}

				$main_group = '';
				if ( isset( $user_meta['main_group'] ) ) {
					$main_group = absint( implode( ',', $user_meta['main_group'] ) );
					$main_group = bp_get_group_name( groups_get_group( $main_group ) );
				}

				$location = '';
				if ( isset( $user_meta['location'] ) ) {
					$location = implode( ',', $user_meta['location'] );
				}

				$company = '';
				if ( isset( $user_meta['company'] ) ) {
					$company = implode( ',', $user_meta['company'] );
				}

				$company2 = '';
				if ( isset( $user_meta['field_2'] ) ) {
					$company2 = implode( ',', $user_meta['field_2'] );
				}

				$skills = '';
				if ( isset( $user_meta['skills'] ) ) {
					$skills = implode( ',', $user_meta['skills'] );
				}

				$role = '';
				if ( isset( $user_meta['grieg_capabilities'] ) ) {
					$role_arr = unserialize( implode( ',', $user_meta['grieg_capabilities'] ) ); // phpcs:ignore
					if ( is_array( $role_arr ) ) {
						$role = array_keys( $role_arr )[0];
					}
				}

				$member_type = bp_get_member_type( $user->ID );

				WP_CLI::line( $counter . ',' . $user->ID . ',"' . $user->data->user_email . '","' . $user->data->display_name . '","' . $alt_name . '","' . $emp_number . '","' . $workplace . '","' . $department . '","' . $main_group . '","' . $location . '","' . $company . '","' . $company2 . '","' . $skills . '","' . $role . '","' . $member_type . '"' );

				$counter++;
			}
		}
	}

	$grieg_export_users = new Grieg_Export_Users();

	WP_CLI::add_command( 'grieg-users', $grieg_export_users );
}
