<?php

namespace App\Http\Controllers\Wechat;

use App\Exceptions\WeChatException;
use App\Http\Controllers\Controller;

class Server extends Controller
{

    /**
     * @return string
     */
    public function index()
    {
        try {
            if (isset($_GET['echostr'])) {
                return $_GET['echostr'];
            } else {
                $xml = file_get_contents('php://input');
                libxml_disable_entity_loader(true);
                $object = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
                $messageObj = new Message();
                if (
                    \DB::table('kddx_user_openid')->where([
                    'public_id' => $object->ToUserName,
                    'openid' => $object->FromUserName
                    ])->first()
                ) {
                    \DB::table('kddx_user_openid')->where([
                        'public_id' => $object->ToUserName,
                        'openid' => $object->FromUserName
                    ])->update(['logintime' => $object->CreateTime, 'subscribe' => 1]);
                } else {
                    \DB::table('kddx_user_openid')->insert([
                        'public_id' => $object->ToUserName,
                        'openid' => $object->FromUserName,
                        'logintime' => $object->CreateTime,
                        'subscribe' => 1
                    ]);
                }
                switch ($object->MsgType) {
                    case 'text':
                        return $messageObj->text($object);
                        break;
                    case 'image':
                        return $messageObj->image($object);
                        break;
                    case 'voice':
                        return $messageObj->voice($object);
                        break;
                    case 'video':
                        return $messageObj->video($object);
                        break;
                    case 'shortvideo':
                        return $messageObj->shortvideo($object);
                        break;
                    case 'event':
                        switch ($object->Event) {
                            case 'subscribe':
                                return Event::subscribe($object);
                                break;
                            case 'unsubscribe':
                                return Event::unsubscribe($object);
                                break;
                            case 'SCAN':
                                return Event::scan($object);
                                break;
                            case "CLICK":
                                return Event::click($object);
                        }
                }
            }
            return 'Success';
        } catch (\Exception $e) {
            throw new WeChatException();
        }
    }
}
