

<?php

// header("Access-Control-Allow-Origin: https://test.thomasbouckson.fr");
// header("Access-Control-Allow-Headers: Content-Type, Authorization");
// header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
// header("Access-Control-Allow-Credentials: true");
// header("Access-Control-Allow-Origin: *");

?>




<?php
$clientID = 'Ov23liPjdVld6EyBfNUw';
$clientSecret = '93e40b70a477ae3708cad23e7911ec1ea675658e';
$redirectUri = 'https://' . $_SERVER['HTTP_HOST'] . '/auth-callback.php';

$code = $_GET['code'] ?? null;
$token = null;
$scope = null;

if ($code) {
    $postData = http_build_query([
        'client_id' => $clientID,
        'client_secret' => $clientSecret,
        'code' => $code,
        'redirect_uri' => $redirectUri,
    ]);

    $opts = [
        'http' => [
            'method' => 'POST',
            'header' =>
                "Content-Type: application/x-www-form-urlencoded\r\n" .
                "Accept: application/json\r\n",
            'content' => $postData,
        ],
    ];

    $context = stream_context_create($opts);
    $result = file_get_contents('https://github.com/login/oauth/access_token', false, $context);
    $data = json_decode($result, true);

    $token = $data['access_token'] ?? null;
    $scope = $data['scope'] ?? null;

    // Optionnel : log de debug
    // file_put_contents('debug.log', print_r([
    //     'code' => $code,
    //     'token' => $token,
    //     'scope' => $scope,
    //     'raw_response' => $data,
    // ], true), FILE_APPEND);
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Authentification GitHub</title>


    <button onclick="window.opener.postMessage({ token: '<?php echo $token; ?>' }, '*'); window.close();">
          Envoyer manuellement le token
        </button>

</head>
<body>
<script>
(function () {
    const token = <?php echo json_encode($token); ?>;
    const scope = <?php echo json_encode($scope); ?>;


const receiveMessage = (message) => {
  const content = {
    token: token,
    provider: 'github',
  }
  const status = 'success';
  
  window.opener.postMessage(
    `authorization:github:${status}:${JSON.stringify(content)}`, 
    message.origin
  );
  window.removeEventListener("message", receiveMessage, false);
}
window.addEventListener("message", receiveMessage, false);
window.opener.postMessage("authorizing:github", "*");



    if (token && window.opener) {
        // window.opener.postMessage({ token: token }, "*");
        // console.log("Token reçu :", token);

        receiveMessage();
        // window.close();


        // localStorage.setItem('netlify-cms-user', JSON.stringify({
        //   token: token,
        //   backendName: "github"
        // }));
    } else {
        document.body.innerHTML = "<p>Échec de l'authentification GitHub. Vérifie les logs serveur.</p>";
    }
})();




</script>
</body>
</html>
