<?php

namespace App\Http\Controllers;

use App\Models\WeChat;
use Illuminate\Http\Request;
use Yo;

class WeChatController extends Controller
{
  public function auth($app_id)
  {
    $code = request()->get('code');
    $state = request()->get('state');
    $we_chat = WeChat::where('app_id', $app_id)->where('type', 1)->first();
    if (!$we_chat) return Yo::error_echo(100001, ['公众号']);
    $url = $state . "code=$code";
    Yo::echo(['url' => $url]);
    header("Location: $url");
    exit();
  }

  public function gzh_login($we_chat, $code)
  {
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='
      . $we_chat->app_id . '&secret='
      . $we_chat->app_secret . '&code='
      . $code . '&grant_type=authorization_code';
    $info = file_get_contents($url);
    return json_decode($info, true);
  }

  public function mp_login($we_chat, $code)
  {
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='
      . $we_chat->app_id
      . '&secret=' . $we_chat->app_secret
      . '&js_code=' . $code . '&grant_type=authorization_code';
    $info = file_get_contents($url);
    $json = json_decode($info);
    return get_object_vars($json);
  }

  public function login($code, $app_id)
  {
    $we_chat = WeChat::where('app_id', $app_id)->first();
    $login = false;
    if (!$we_chat) return false;
    switch ($we_chat->type) {
      case 1:
        $login = $this->gzh_login($we_chat, $code);
        break;
      case 2:
        $login = $this->mp_login($we_chat, $code);
        break;
    }
    return ['login' => !!$login];
  }

  public function login_test(Request $request)
  {
    $code = $request->post('code');
    $app_id = $request->post('app_id');
    return Yo::echo([
      'info' => $this->login($code, $app_id)
    ]);
  }
}
