<?php

namespace app\server;

use app\common\Error;
use app\model\Admins as AdminsModel;
use app\model\Orders as OrdersModel;
use support\Log;
use support\Redis;

class Orders {
    /**
     * @params []OrdersModel $order
     * @return array
     */
    public static function reminderOrders(OrdersModel ...$orders) 
    {
        $admin_ids = [];
        $sns = [];

        foreach ($orders as $order) {
            $admin_ids[] = $order->admin_id;
            $sns[] = $order->sn;
        }

        $admins = AdminsModel::whereIn('id', $admin_ids)->select()->column('mobile', 'id');

        if (empty($admins)) {
            return array_fill_keys($sns, Error::undefined('admin check error'));
        }

        $ttl    = 86400;
        $result = [];

        foreach($orders as $order) {
            $admin_mobile = $admins[$order->admin_id] ?? '';

            if (empty($order->mobile) || empty($admin_mobile)) {
                $result[$order->sn] = Error::undefined('client mobile or admin mobile invalid');
                continue;
            }

            if (Blacks::CExists($order->mobile)) {
                $result[$order->sn] = Error::ERR_SMS_BLACKS;
                Log::info(__METHOD__ . " blacks", [$order->mobile, $order->sn]);
                continue;
            }

            $key = sprintf("CRM:%s:%s_%s", 'reminderOrders', $order->sn, $order->mobile);
            $ok  = Redis::set($key, time(), 'EX', $ttl, 'NX');

            if (!$ok) {
                $result[$order->sn] = Error::undefined('reminder cooldown');
                continue;
            }

            $res = SMS::juhe_sms_send($order->mobile, SMS::JUHE_TMP_REMINDER_ORDER, ['title' => $order->product_name, 'mobile' => $admin_mobile]);
            $err_code = $res['error_code'] ?? 0;

            if ($err_code != 0) {
                Log::error(__METHOD__ . " send error", [$res, $order->mobile, $order->sn]);
                $result[$order->sn] = Error::ERR_SMS_SEND_FAIL;
                continue;
            }

            $result[$order->sn] = [];
        }
        
        return count($orders) > 1 ? $result : reset($result);
    }
}