<?php

class JwtData extends \Phalcon\Mvc\Model
{
    const STATUS_ACTIVE = 0;
    const STATUS_REVOKED = 1;
    const TYPE_USER = 'USER';
    const TYPE_ADMIN = 'ADMIN';
    const PLATFORM_WEB = 'WEB';
    const PLATFORM_ANDROID = 'ANDROID';
    const PLATFORM_IOS = 'IOS';

    /**
     *
     * @var integer
     */
    public $id;

    /**
     *
     * @var integer
     */
    public $user_id;

    /**
     *
     * @var integer
     */
    public $tenant_id;

    /**
     *
     * @var string
     */
    public $token;

    /**
     *
     * @var string
     */
    public $refresh_token;

    /**
     *
     * @var integer
     */
    public $refresh_token_exp;

    /**
     *
     * @var string
     */
    public $client;

    /**
     *
     * @var integer
     */
    public $status;

    /**
     *
     * @var string
     */
    public $created_at;

    /**
     *
     * @var string
     */
    public $updated_at;

    /**
     *
     * @var string
     */
    public $deleted_at;

    /**
     *
     * @var string
     */
    public $ip_address;

    /**
     *
     * @var string
     */
    public $login_type;

    /**
     *
     * @var string
     */
    public $platform;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->setSchema("jaga");
        $this->setSource("jwt_data");
        $this->belongsTo('user_id', '\UmUser', 'um_id', ['alias' => 'UmUser']);
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'jwt_data';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return JwtData[]|JwtData|\Phalcon\Mvc\Model\ResultSetInterface
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return JwtData|\Phalcon\Mvc\Model\ResultInterface
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    public static function retrieveIpAddress($server) {
        try {
            if( array_key_exists('HTTP_X_FORWARDED_FOR', $server) && !empty($server['HTTP_X_FORWARDED_FOR']) ) {
                if (strpos($server['HTTP_X_FORWARDED_FOR'], ',')>0) {
                    $addr = explode(",",$server['HTTP_X_FORWARDED_FOR']);
                    $ip = trim($addr[0]);
                } else {
                    $ip = $server['HTTP_X_FORWARDED_FOR'];
                }
            }
            else {
                $ip = $server['REMOTE_ADDR'];
            }
        } catch (\Exception $e) {
            $ip = null;
        }
        return $ip;
    }
}
