<?php
session_start();
error_reporting(0);
header('Content-type: application/json');
date_default_timezone_set("Asia/Bangkok");
include 'config/database.php';

if(isset($_GET['code']) AND isset($_GET['state'])){	
	$code = $_GET['code'];
	$state = $_GET['state'];
  //DECODE // SN 16.01.63 AP
  $param = json_decode(decode($state ,APP));
  $_SESSION['groupId'] = $param->groupId;
  $state = $param->key;
  //DECODE // EN 16.01.63 AP 

  update_notify_bot($state); // ++ 1
  $Secret = get_notify_find($state);
	$result =  get_data($code,$state,$Secret);
	$res = json_decode($result);
  $name = get_gname($res->access_token);
  insert_notify_temp($name,$code,$res->access_token); // N 16.01.63 AP
  $_SESSION['group_name'] = $name;
  $_SESSION['code'] = $code;
  $_SESSION['state'] = $state;
  $_SESSION['access_token'] = $res->access_token;

  //after Insert All field
  insert_notify_all($param->groupId,$name,$res->access_token,$code,$state);

  header('location: show.php');

  //testToken($res->access_token);


print_r($param);
}else{
	echo json_encode(['status'=> '404']);
}



function get_data($code,$client_id,$client_secret) {
  header('Content-type: text/html; charset=UTF-8');
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch, CURLOPT_URL, 'https://notify-bot.line.me/oauth/token');
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_COOKIEJAR, 'cache.txt');
  curl_setopt($ch, CURLOPT_COOKIEFILE, "cache.txt");
  curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=authorization_code&code='.$code.'&redirect_uri=http://at-mybot.me:8000/callback.php&client_id='.$client_id.'&client_secret='.$client_secret);
  $data =   utf8_decode(curl_exec($ch));
  curl_close($ch);
  return $data;
}



function get_gname($token){
  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_URL => "https://notify-api.line.me/api/status",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
      "Accept: */*",
      "Accept-Encoding: gzip, deflate",
      "Authorization: Bearer ".$token,
      "Cache-Control: no-cache",
      "Connection: keep-alive",
      "Host: notify-api.line.me",
      "Postman-Token: d888d933-f319-47bd-b2a6-581f96148a77,8d52a79d-43fa-431c-b878-8c1d71959d11",
      "User-Agent: PostmanRuntime/7.20.1",
      "cache-control: no-cache"
    ),
  ));
  $response = curl_exec($curl);
  $res = json_decode($response);
  $err = curl_error($curl);
  curl_close($curl);
  return $res->target;
}


function testToken($token){
  $URL = 'https://notify-api.line.me/api/notify';
  $MESSAGE = 'BOT Ready';
  $query = http_build_query(['message' => $MESSAGE], '', '&');
  $header = [
      'http' => [
          'method' => 'POST',
          'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL
              . 'Authorization: Bearer ' . $token . PHP_EOL
              . 'Content-Length: ' . strlen($query) . PHP_EOL,
          'content' => $query
      ]
  ];
  $context = stream_context_create($header);
  $output = file_get_contents($URL, false, $context);
  $result = json_decode($output);
  print_r($result);
}