


<?php
    $parts = parse_url("https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."");
    parse_str($parts['query'], $query);
    $code = $query['code'];
    // var_dump(getToken($code));
    $token = getToken($code);
    // $refresh_token = getToken($code)[1];
    // var_dump($token);
    $headers = [
        'Authorization: Bearer '.$token[0],
        'Content-Type: application/json'
    ];
    

    $fcmUrl = 'https://graph.microsoft.com/v1.0/me';
    $cRequest = curl_init();
    curl_setopt($cRequest, CURLOPT_URL, $fcmUrl);
    curl_setopt($cRequest, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($cRequest, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($cRequest, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($cRequest);
    $obj = json_decode($result);
    $email = $obj->mail;
    curl_close($cRequest);

    $pdo = new PDO('mysql:host=localhost;dbname=dev-intranet;charset=utf8', "dev-user", "AcdinemGeor5qua"); 
    $GLOBALS["pdo_conn"] = $pdo;
    // echo $token."</br>".$email."</br>".$refresh_token;

    $noPublish = "CALL insertTokenMicrosoftKey('$token[0]', '$email', '$token[1]')";

    $stmt = $pdo->prepare($noPublish);
    $stmt->execute();

    $count = $stmt->fetchColumn();

    ?>
    <script>
        setTimeout(() => {
            window.close();
        }, 1000);
        
    </script>'
<?php



    function getToken($code){
        $array = array();
        $headers = [
            'Content-Type: application/x-www-form-urlencoded'
        ];
        $fcmUrl = 'https://login.microsoftonline.com/organizations/oauth2/v2.0/token';
        $cRequest = curl_init();
        curl_setopt($cRequest, CURLOPT_URL, $fcmUrl);
        curl_setopt($cRequest, CURLOPT_POST, true);
        curl_setopt($cRequest, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($cRequest, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($cRequest, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($cRequest, CURLOPT_POSTFIELDS, http_build_query(array(
            'client_id' => '998f5db8-f544-4dda-a10a-79eda88a5437',
            'scope' => 'openid User.ReadWrite Calendars.ReadWrite Presence.ReadWrite',
            'code' => $code,
            'redirect_uri' => 'https://dev-intranet.breadcrumb-online.de/module/api/testGraph.php',
            'grant_type' => 'authorization_code',
            'client_secret' => 'S6Z8Q~zae4D8k0mpbCtgAQrAUV5we.FxcR6LHav-'

        )));
        $result = curl_exec($cRequest);
        $obj_token = json_decode($result);
        $token_get = $obj_token->access_token;
        echo $result;
        $refresh_token = $obj_token->refresh_token;
        array_push($array, $token_get);
        array_push($array, $refresh_token);
        curl_close($cRequest);
        return $array;

    }

        
    ?>