<?php
use Illuminate\Support\Facades\Redis;
use Modules\Cart\Models\Order;

if (!function_exists('formatString')) {
    function formatString($format, ...$args) {
        preg_match_all('/%s/i', $format, $matches);
        if (isset($matches[0]) && count($args) < count($matches[0])) {
            foreach ($args as $item) {
                $format = str_replace('%s', $item, $format);
            }
            return $format;
        }
        return sprintf($format, ...$args);
    }
}

if (!function_exists('getPaypalKey')) {
    function getPaypalKey() {
        $listAccount = config("cart::paypal.account");
        $key = "INDEX_PAYPAL_ACCOUNT_FRONTEND";
        $index = 0;
        if (Redis::exists($key)) {
            $index = Redis::get($key);
        }
        if ($index > count($listAccount) - 1) {
            $index = 0;
        }
        $isValid = false;
        $doTime = 0;
        $validAccount = [];
        while (!$isValid && $doTime <= count($listAccount) - 1) {
            $account = $listAccount[$index];
            if ($account["limit"] == -1) {
                $isValid = true;
                $validAccount = $account;
            } else if ($account["limit"] > 0) {
                $orderCount = Order::where("payment_account", $account["name"])->where("payment_status", "PAID")->count();
                if ($orderCount < $account["limit"]) {
                    $isValid = true;
                    $validAccount = $account;
                }
            }
            $index ++;
            if ($index > count($listAccount) - 1) {
                $index = 0;
            }
            $doTime ++;
        }
        if ($isValid) {
            Redis::set("INDEX_PAYPAL_ACCOUNT_FRONTEND", $index);
            unset($validAccount["secret"]);
            return $validAccount;
        }
        return false;
    }
}
