<?php

namespace WooCommerce\Plugin\AddonPayments\Entities;

class CardToken {
	public $id_token;
	public $customer_id;
	public $accountId;
	public $paymentMethod;
	public $name;
	public $cardType;
	public $cardNumber;
	public $cardToken;
	public $rawData;
	public $createdAt;
	public $lastUsed;

	public function save() {
		global $wpdb;
		$dbPrefix       = $wpdb->prefix;
		$this->id_token = $wpdb->insert(
			"{$dbPrefix}epg_card_token",
			array(
				'customer_id'   => $this->customer_id,
				'accountId'     => $this->accountId,
				'paymentMethod' => $this->paymentMethod,
				'name'          => $this->name,
				'cardType'      => $this->cardType,
				'cardNumber'    => $this->cardNumber,
				'cardToken'     => $this->cardToken,
				'rawData'       => $this->rawData,
				'createdAt'     => $this->createdAt,
				'lastUsed'      => $this->lastUsed,
			)
		);

		return $this->id_token;
	}

	public static function getByCustomer( $customerId ) {
		global $wpdb;
		$dbPrefix = $wpdb->prefix;

		$sql = "SELECT
                `t`.`id_token`,
                `t`.`customer_id`,
                `t`.`accountId`,
                `t`.`paymentMethod`,
                `t`.`name`,
                `t`.`cardType`,
                `t`.`cardNumber`,
                `t`.`cardToken`,
                `t`.`rawData`,
                `t`.`createdAt`,
                `t`.`lastUsed`
            FROM `{$dbPrefix}epg_card_token` t
            WHERE `t`.`customer_id` = {$customerId}";

		return $wpdb->get_results( $sql, ARRAY_A );
	}

	public static function deleteByAccountId( string $accountId ): bool {
		global $wpdb;
		$dbPrefix = $wpdb->prefix;

		return $wpdb->delete( $dbPrefix . 'epg_card_token', array( 'accountId' => $accountId ) );
	}

	public static function tokenExists( $token ) {
		global $wpdb;
		$dbPrefix = $wpdb->prefix;

		$exists = $wpdb->get_var(
			"SELECT `id_token`
                FROM `{$dbPrefix}epg_card_token`
                WHERE `cardToken` = '$token'"
		);

		return $exists;
	}

}
