<?php


namespace Fliegerlogin\Db;

use Fliegerlogin\DbSchema\DbSchema;
use Fliegerlogin\DbSchema\Users as UsersSchema;
use Fliegerlogin\Options;
use Fliegerlogin\VereinsfliegerApi\Model\IUserDto;


class Users extends AbstractDb {

	/**
	 * @param int $uid
	 * @return object|null
	 */
	public static function getUserByVereinsfliegerId(int $uid) {
		return $GLOBALS['wpdb']->get_row($GLOBALS['wpdb']->prepare(
			'SELECT * FROM `' . UsersSchema::getTableName() . '` WHERE `' . UsersSchema::getColumnVfUserId() . '` = %d LIMIT 1',
			$uid
		));
	}

	/**
	 * @param string $email
	 * @return object|null
	 */
	public static function getUserByEmail(string $email) {
		return $GLOBALS['wpdb']->get_row($GLOBALS['wpdb']->prepare(
			'SELECT * FROM `' . UsersSchema::getTableName() . '` WHERE `user_email` = %s LIMIT 1',
			$email
		));
	}

	/**
	 * Checks if a given user is linked to a Vereinsflieger account
	 * @param \WP_User $user The user to be checked
	 * @return bool
	 */
	public static function isVereinsfliegerUser(\WP_User $user): bool {
		return $user->data->{UsersSchema::getColumnVfUserId()} !== null;
	}

	/**
	 * Roles that may administer the site are never handed out automatically.
	 *
	 * The role for new members is an admin setting, and a mistake there would
	 * otherwise turn every Vereinsflieger member into an administrator.
	 */
	private static function safeDefaultRole(): string {
		$role = (string) Options::getDefaultRole();
		$roleObject = get_role($role);

		if (!$roleObject || $roleObject->has_cap('manage_options') || $roleObject->has_cap('edit_users')) {
			return 'subscriber';
		}

		return $role;
	}

	/**
	 * Whether this account can administer the site or its users.
	 *
	 * Takes an id, not a \WP_User. The lookups above hand back raw rows from
	 * $wpdb, and this method used to demand a \WP_User - which threw a
	 * TypeError on the one path that mattered, the login of a member whose
	 * account was found by email address.
	 */
	public static function hasElevatedCapabilities(int $userId): bool {
		if ($userId <= 0) {
			return false;
		}

		return user_can($userId, 'manage_options')
			|| user_can($userId, 'edit_users')
			|| user_can($userId, 'promote_users');
	}

	public static function addVereinsfliegerUser(IUserDto $user) {
		$userLogin = DbSchema::getTablePrefix() . $user->getUid();
		$displayName = $user->getFirstname() . ' ' . $user->getLastname();
		$userId = wp_insert_user([
			'user_pass' => wp_generate_password(64, true, true),
			'user_login' => $userLogin,
			'user_nicename' => $userLogin,
			'user_url' => '',
			'user_email' => $user->getEmail(),
			'nickname' => $displayName,
			'user_registered' => gmdate('Y-m-d H:i:s'),
			'role' => self::safeDefaultRole()
		]);

		if (is_a($userId, \WP_Error::class)) {
			return null;
		}

		$GLOBALS['wpdb']->update(
			UsersSchema::getTableName(),
			[ UsersSchema::getColumnVfUserId() => $user->getUid() ],
			[ 'ID' => $userId ]
		);

		return $userId;
	}

	public static function updateMetaData(int $userId, $wpUser, IUserDto $user) {
		wp_update_user([
			'ID' => $userId,
			'user_email' => $user->getEmail(),
			'display_name' => $user->getFirstname() . ' ' . $user->getLastname()
		]);

		update_user_meta($userId, 'first_name', $user->getFirstname());
		update_user_meta($userId, 'last_name', $user->getLastname());
		$GLOBALS['wpdb']->update(
			UsersSchema::getTableName(),
			[ UsersSchema::getColumnVfUserId() => $user->getUid() ],
			[ 'ID' => $userId ]
		);
	}

}
