<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SendMsg extends Controller
{
    //


    /**
     * 发送文本消息
     * @param  object  $object
     * @return string
     */
    public static function text($object)
    {
        $template = '<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%d</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
                    </xml>';
        $result = sprintf($template, $object->FromUserName, $object->ToUserName, $object->CreateTime, $object->Content);
        return $result;
    }


    public static function image($object)
    {
        $template = '<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%d</CreateTime>
                    <MsgType><![CDATA[image]]></MsgType>
                    <Image><MediaId><![CDATA[%s]]></MediaId></Image>
                    </xml>';
        $result = sprintf($template, $object->FromUserName, $object->ToUserName, $object->CreateTime, $object->MediaId);
        return $result;
    }


    public static function news($object, array $array)
    {
        $template = '<item>
                    <Title><![CDATA[%s]]></Title>
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                    </item>';
        $item = null;
        foreach ($array as $value) {
            $item .= sprintf($template, @$value['Title'], @$value['Description'], @$value['PicUrl'], @$value['Url']);
        }
        $template = '<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%d</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>%d</ArticleCount>
                <Articles>%s</Articles>
                </xml>';
        $result = sprintf(
            $template,
            $object->FromUserName,
            $object->ToUserName,
            $object->CreateTime,
            count($array),
            $item
        );
        return $result;
    }
}
