<?php

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

use Illuminate\Support\Facades\DB;


class LinenotifyController extends Controller
{
    public function __construct(Request $r){checklogin();}
    public function index(Request $r)
    {
        $view['maaa'] = "";
        $view['uid'] = uid();
        return view('endobook.linenotify.index',$view);
    }

    public function show($id,Request $r){

        if(isset($r->code)){
            $client_id              = 'R4tfsLdYWPpp7zw7xHqP7Q';
            $client_secret          = 'B2Et3L0P30jRXKYdrPHdbDW7ZfCZInsWpQAXx93IPu7';
            $api_url                = 'https://notify-bot.line.me/oauth/token';
            $callback_url           = 'http://medicaendo.com/linenotify/callback';
            $fields['grant_type']   = 'authorization_code';
            $fields['code']         = $r->code;
            $fields['redirect_uri'] = $callback_url;
            $fields['client_id']    = $client_id;
            $fields['client_secret']= $client_secret;
            try {
                $res    = connectwebPOST($api_url,$fields);
                $json   = json_decode($res);
                $line   = DB::table('users')->where('id',$r->state)->first();
                if($line->user_linenotify!=""){
                    $val['user_linenotify']=$json->access_token;
                    DB::table('users')->where('id',$r->state)->update($val);
                }else{
                    $val['user_linenotify']=$json->access_token;
                    DB::table('users')->where('id',$r->state)->update($val);
                }
            } catch(\Throwable $e) {
                throw new Exception($e->getMessage());
            }
            $view['mmm'] = "";
            return view('endobook.linenotify.show',$view);
        }

        if($id=="test"){
            sendnoti(uget("user_linenotify"),'คุณมีเคสส่องกล้องวันที่ 0000 procedure P0001');
        }
    }
}
