<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class CardsTable extends Table
{
	public function initialize(array $config): void
	{
		parent::initialize($config);
		$this->setTable('card');
		$this->setPrimaryKey('id');
	}

	public function getDetails(int $id): array
	{
		$result = $this->find()
			->where(['Card.id' => $id])
			->enableHydration(false)
			->first();
		return $result ?: [];
	}

	public function isUserStripeCustIDExist(int $id): array
	{
		$result = $this->find()
			->where(['Card.user_id' => $id])
			->enableHydration(false)
			->first();
		return $result ?: [];
	}

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

	public function getDefaultCard(int $user_id): int
	{
		return (int)$this->find()
			->where(['Card.user_id' => $user_id, 'Card.default' => 1])
			->count();
	}

	public function getDefaultCardDetails(int $user_id): array
	{
		$result = $this->find()
			->where(['Card.user_id' => $user_id, 'Card.default' => 1])
			->enableHydration(false)
			->first();
		return $result ?: [];
	}

	public function getCardDetailsAgainstCardID(int $card_id): array
	{
		$result = $this->find()
			->where(['Card.card_id' => $card_id])
			->enableHydration(false)
			->first();
		return $result ?: [];
	}

	public function getCardDetailsAgainstCardIDAndUserID(int $user_id, int $card_id): array
	{
		$result = $this->find()
			->where(['Card.id' => $card_id, 'Card.user_id' => $user_id])
			->enableHydration(false)
			->first();
		return $result ?: [];
	}

	public function ifExistCardAgainstUser(int $user_id, int $id): array
	{
		$result = $this->find()
			->where(['Card.user_id' => $user_id, 'Card.id' => $id])
			->enableHydration(false)
			->first();
		return $result ?: [];
	}

	public function setAllCardsUndefaultAgainstUser(int $user_id, int $card_id): void
	{
		$this->updateAll(
			['default' => 0],
			['user_id' => $user_id, 'card_id !=' => $card_id]
		);
	}

	public function getUserCards(int $user_id): array
	{
		return $this->find()
			->where(['Card.user_id' => $user_id])
			->order(['Card.id' => 'ASC'])
			->enableHydration(false)
			->toArray();
	}
}
