<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace app\middleware;

use addons\webman\model\AppVersion;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

/**
 * 站点验证中间件
 * Class SiteAuthMiddleware
 * @package app\middleware
 */
class AppVersionMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // 更新比较时，查询的是版本标识，大于传入的版本标识时，返回新版本的数据
        $versionKey = $request->header('app-version-key');
        $systemKey = $request->header('system-key');
        // 传入检测的系统
        if (empty($versionKey) || empty($systemKey)) {
            return jsonFailResponse('缺少版本号或版本标识');
        }
        $data = AppVersion::query()
            ->where('app_version_key', '>', $versionKey)
            ->where(['status' => 1])
            ->where('status', 1)
            ->where('force_update', 1)
            ->where('system_key', $systemKey)
            ->where('department_id', request()->department_id)
            ->whereDate('regular_update', '<', date("Y-m-d H:i:s", time()))
            ->select(['id', 'system_key', 'app_version', 'app_version_key', 'apk_url', 'hot_update_url', 'force_update', 'hot_update', 'regular_update', 'update_content', 'notes'])
            ->orderBy('id', 'desc')
            ->first();
        if (!empty($data)) {
            return jsonFailResponse('有新版本', [
                'data' => $data
            ], 406);
        }

        return $handler($request);
    }
}
