<?php

class Account {
	static function trySync($db, $userName, $password = NULL) {
		$sync = $db->getValue(
			'SELECT COUNT(*) > 0 FROM account.userSync WHERE name = #',
			[$userName]
		);

		if ($sync)
			self::sync($db, $userName, $password);
	}

	static function sync($db, $userName, $password = NULL) {
		$bcryptPassword = password_hash($password, PASSWORD_BCRYPT);

		$userId = $db->getValue(
			'SELECT id FROM account.user WHERE `name` = #',
			[$userName]
		);
		$db->query(
			'UPDATE account.user SET
				bcryptPassword = #
				WHERE id = #',
			[$bcryptPassword, $userId]
		);

		$hasAccount = $db->getValue(
			'SELECT COUNT(*) > 0
				FROM account.user u
					JOIN account.account a ON u.id = a.id
				WHERE u.name = #',
			[$userName]
		);
		if (!$hasAccount)
			$db->query('DELETE FROM account.userSync WHERE name = #',
				[$userName]
			);
	}
}
