<?php

namespace Application\Service\Extension\MiniAppWs;

use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Laminas;

class App
{
    public int $itemId = 0;

    public int $menuId = 0;

    public const MODULE_CS = 57;

    public function push(array $user = [])
    {
        foreach ($user as $userId) {
            if ($userId) {
                $key = $this->getMiniAppMenuCacheKey();
                $this->redis()->setBit($key, $userId, 1);
            }
        }
        $this->publish($user);
    }

    public function remove(array $user = [])
    {
        foreach ($user as $userId) {
            if ($userId) {
                $key = $this->getMiniAppMenuCacheKey();
                $this->redis()->setBit($key, $userId, 0);
            }
        }
        $this->publish($user);
    }

    private function redis()
    {
        return Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
    }

    private function getMiniAppMenuCacheKey(): string
    {
        if (!$this->itemId || !$this->menuId) {
            throw new InvalidArgumentException("中心id 或 菜单id 有误。");
        }
        return "menu:{$this->itemId}:{$this->menuId}";
    }

    private function publish($userId)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://{$_SERVER['HTTP_HOST']}:9502",
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => false,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => 'data=%7B%22action%22%3A%22publish%22%2C%20%22to%22%3A%22' . urlencode(implode(',', $userId)) . "%22%2C%22item_id%22%3A%22{$this->itemId}%22%7D",
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
    }

}