<?php

namespace Sibs\Models;

use Db;
use Sibs\DB\Seeds\Version_2_1_0\SibsCardTokensSeed_2_1_0;
use Sibs\SibsException;

class SibsCardTokens extends SibsModels
{
    /**
     * Sibs Customer ID.
     *
     * @var int
     */
    public $id_customer;

    /**
     * SIBS Token Name.
     *
     * @var string
     */
    public $token_name;

    /**
     * SIBS Token Type.
     *
     * @var string
     */
    public $token_type;

    /**
     * SIBS Token Value.
     *
     * @var string
     */
    public $value;

    /**
     * Masked Pan.
     *
     * @var string
     */
    public $masked_pan;

    /**
     * Expire Date.
     *
     * @var string
     */
    public $expire_date;

    /**
     * Expire Date Example.
     *
     * @var string
     */
    public $expire_date_example;

    /**
     * Definition.
     *
     * @var array
     */
    public static $definition = [
        'table'     => 'sibs_card_tokens',
        'primary'   => 'id',
        'multilang' => false,
        'fields'    => [
            'id_customer'         => ['type' => self::TYPE_INT, 'validate' => 'isNullOrUnsignedId', 'size' => 10],
            'token_name'          => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 100],
            'token_type'          => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 32],
            'value'               => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 100],
            'masked_pan'          => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 32],
            'expire_date'         => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 32],
            'expire_date_example' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 6],
        ],
    ];

    /**
     * Get Static Table Name.
     *
     * @return bool
     */
    public static function getStaticTableName(): string
    {
        return _DB_PREFIX_ . self::$definition['table'];
    }

    /**
     * Get Static Config Name.
     *
     * @return bool
     */
    public static function getStaticConfigName(): string
    {
        return 'CREATE_SIBS_CARD_TOKENS_TABLE';
    }

    /**
     * Create Model.
     *
     * @return bool
     */
    public static function create(): bool
    {
        $table         = self::getStaticTableName();
        $customerTable = _DB_PREFIX_ . 'customer';

        $sql = "CREATE TABLE IF NOT EXISTS `{$table}`(
            `id` INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
            `id_customer` INT(10) UNSIGNED NOT NULL,
            `token_name` VARCHAR(100) NOT NULL,
            `token_type` VARCHAR(32) NOT NULL,
            `value` VARCHAR(100) NOT NULL,
            `masked_pan` VARCHAR(32) NOT NULL,
            `expire_date` VARCHAR(32) NOT NULL,
            `expire_date_example` VARCHAR(6) NOT NULL,
            FOREIGN KEY (`id_customer`) REFERENCES `$customerTable`(`id_customer`),
            UNIQUE KEY `id_token_unique_key` (`id_customer`, `token_name`, `token_type`, `masked_pan`, `expire_date`)
        ) ";

        return Db::getInstance()->Execute($sql);
    }

    /**
     * Seed Model.
     *
     * @return bool
     */
    public static function seed(): bool
    {
        $self = new self();

        return
            SibsCardTokensSeed_2_1_0::seed($self);
    }

    /**
     * Get Card Tokens By Customer.
     *
     * @param int $customerId
     * @return array
     */
    public static function getCardTokensByCustomer($customerId)
    {
        $table = self::getStaticTableName();

        $sql = "SELECT `token_type`, `value`
            FROM `{$table}`
            WHERE `id_customer` = '$customerId' AND `token_type` = 'Card' ";

        return Db::getInstance()->ExecuteS($sql);
    }

    /**
     * Save Tokens.
     *
     * @param int $customerID
     * @param array $token
     * @return bool
     */
    public static function saveToken($customerID, $token)
    {
        $id_customer       = $customerID;
        $tokenName         = isset($token['tokenName']) ? $token['tokenName'] : '';
        $tokenType         = isset($token['tokenType']) ? $token['tokenType'] : '';
        $value             = isset($token['value']) ? $token['value'] : '';
        $maskedPAN         = isset($token['maskedPAN']) ? $token['maskedPAN'] : '';
        $expireDate        = isset($token['expireDate']) ? $token['expireDate'] : '';
        $expireDateExample = 'PL';

        $table = self::getStaticTableName();

        $sql = "INSERT INTO `{$table}` (
            `id_customer`, `token_name`, `token_type`,
            `value`, `masked_pan`, `expire_date`,
            `expire_date_example`
        ) VALUES (
            '$id_customer', '$tokenName', '$tokenType',
            '$value', '$maskedPAN', '$expireDate',
            '$expireDateExample'
        ) ON DUPLICATE KEY UPDATE
        `token_name` = IF('$tokenName' <> '', '$tokenName', `token_name`),
        `token_type` = IF('$tokenType' <> '', '$tokenType', `token_type`),
        `value` = IF('$value' <> '', '$value', `value`),
        `masked_pan` = IF('$maskedPAN' <> '', '$maskedPAN', `masked_pan`),
        `expire_date` = IF('$expireDate' <> '', '$expireDate', `expire_date`),
        `expire_date_example` = IF('$expireDateExample' <> '', '$expireDateExample', `expire_date_example`) ";

        $result = Db::getInstance()->execute($sql);

        if (! $result) {
            throw new SibsException('ERROR_SAVE_TOKEN');
        }

        return $result;
    }
}
