<?php

declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class DailyCheckinsTable extends Table
{
	public function initialize(array $config): void
	{
		parent::initialize($config);

		$this->setTable('daily_checkin');
		$this->setPrimaryKey('id');
	}

	public function getDetails(int $id): array
	{
		$record = $this->find()
			->where(['id' => $id])
			->first();

		return $record ? $record->toArray() : [];
	}

	public function countCoins(int $userId): array
	{
		$record = $this->find()
			->select(['total_coin' => $this->find()->func()->sum('coin')])
			->where(['user_id' => $userId])
			->first();

		return $record ? $record->toArray() : [];
	}

	public function ifExist(int $userId, string $date): array
	{
		$record = $this->find()
			->where([
				'DATE(created)' => $date,
				'user_id' => $userId
			])
			->first();

		return $record ? $record->toArray() : [];
	}

	public function getRecentCheckins(int $userId, string $date): array
	{
		return $this->find()
			->where([
				'DATE(created) >=' => $date,
				'user_id' => $userId
			])
			->toArray();
	}
}
