<?php

namespace Velis\Api;

use Velis\App;
use Phalcon\Http\Request;

/**
 * Api client model
 * @author Damian Kurek <damian.kurek@velis.pl>
 */
class Client
{
    /**
     * @var Request
     */
    private $_request;

    /**
     * Constructor
     */
    public function __construct(Request $request)
    {
        $this->_request = $request;
    }

    /**
     * Checks if mobile version is current
     * @return boolean
     */
    public function checkMobileVersion()
    {
        if (!in_array($this->_request->getHeader('Platform'), ['Android', 'iOS'])) {
            return true;
        }

        $platform = strtolower($this->_request->getHeader('Platform'));
        $minimalVersion = static::formatVersion(App::$config->mobile->$platform->versionCode);
        $currentVersion = static::formatVersion(App::settings('Current' . $platform . 'VersionCode', null, 'Settings'));
        $userVersion =  static::formatVersion($this->_request->getHeader('Version-Code'));

        if ($userVersion < $minimalVersion) {
            return false;
        }

        if ($userVersion < $currentVersion) {
            $response = App::getService('response');
            $response->setHeader(
                'update-avaliable',
                'true'
            );
        }

        return true;
    }

    /**
     * Returns formated version number
     * @param string $version
     * @return string
     */
    public static function formatVersion($version)
    {
        $result = '';
        foreach (explode('.', $version) as $part) {
            $result .= str_pad($part, 2, "0", STR_PAD_LEFT);
        }
        return $result;
    }
}
