<?php

namespace Models;

class Wallet
{
	public function __construct(
		public int $user_id,
		public int $silver,
		public int $stargem
	) {}

	public static function find(int $user_id): Wallet|false
	{
		$r = live_db()->query('SELECT * FROM wallets WHERE user_id = ?', [$user_id]);
		if ($r === false) throw new \Exception('Failed to query wallet. (W::f)'); // badly formed query
		$w = $r->fetchArray(SQLITE3_ASSOC);
		if ($w === false) return false; // no wallet found
		return new Wallet($user_id, $w['silver'], $w['stargem']);
	}

	public static function create(int $user_id, int $silver = -1, int $starGems = -1): \SQLite3Result|false
	{
		return live_db()->query(
			"INSERT INTO wallets (user_id, silver, stargem) VALUES (:u, :s, :sg)",
			[
				':u' => $user_id,
				':s' => $silver === -1 ? env('start_silver', 10) : $silver,
				':sg' => $starGems === -1 ? env('start_star_gems', 0) : $starGems
			]
		);
	}

	/**
	 * Add a certain amount of currency to the user's wallet.
	 */
	public function give(\Currency $c, int $amt): \SQLite3Result|false
	{
		$cs = $c->string(true);
		$new = $this->{$cs} + $amt;
		return live_db()->query("UPDATE wallets SET $cs = ? WHERE user_id = ?", [$new, $this->user_id]);
	}

	/**
	 * Remove a certain amount of currency from the user's wallet.
	 */
	public function take(\Currency $c, int $amt): \SQLite3Result|false
	{
		$cs = $c->string(true);
		$new = $this->{$cs} - $amt;
		return live_db()->query("UPDATE wallets SET $cs = ? WHERE user_id = ?", [$new < 0 ? 0 : $new, $this->user_id]);
	}
}
