<?php

declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

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

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

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

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

	public function ifReferralUsed(int $user_id, int $usedby): array
	{
		$result = $this->find()
			->where([
				'ReferralUsed.referral_owner' => $user_id,
				'ReferralUsed.used_by' => $usedby
			])
			->first();

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

	public function countReferralUsedByOthers(int $user_id): int
	{
		return $this->find()
			->where(['ReferralUsed.referral_owner' => $user_id])
			->count();
	}

	public function ifUserHasUsedReferral(int $user_id): array
	{
		$result = $this->find()
			->where([
				'ReferralUsed.used_by' => $user_id,
				'ReferralUsed.purchase' => 0
			])
			->first();

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

	public function countReferralUsed(int $user_id, string $datetime): array
	{
		$result = $this->find()
			->select([
				'total_amount' => $this->find()->func()->sum('ReferralUsed.amount'),
				'total_count' => $this->find()->func()->count('ReferralUsed.id')
			])
			->where([
				'ReferralUsed.referral_owner' => $user_id,
				'ReferralUsed.created >' => $datetime
			])
			->first();

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