<?php
session_set_cookie_params([
    'lifetime' => $_POST['expires_in'],
    'path' => '/',
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict' // Helps mitigate CSRF attacks
]);

session_start();
session_regenerate_id(true);

header('Content-Type: application/json');

/*
$dbuser = 'root';
$dbpass = 'Skc.2023';
$pdo = new PDO('mysql:host=localhost;dbname=sso', $dbuser, $dbpass);
*/


if ( (isset($_SESSION['t']))  || (array_key_exists('access_token', $_POST)) )
{
   if ( @$_SESSION['t'] == "" ) {
      $_SESSION['t'] = $_POST['access_token'];
   }

   $t = $_SESSION['t'];
   $s = $_SESSION['state'];


   $ch = curl_init();
   curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '. $t, 'Content-type: application/json'));
   curl_setopt($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/me/");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $rez = json_decode(curl_exec($ch), 1);

   // error de autenticacion, usuario sin permiso, deshabilitado.
   if (array_key_exists ('error', $rez)) {
      echo json_encode($rez['error']);
      die();
   }

   $data = [
       'mail' => $rez['mail'],
       'displayName' => $rez['displayName'],
       'jobTitle' => $rez['jobTitle'],
       'access_token' => $t,
       'expires_in' => $_POST['expires_in']
       //'scope' => $_POST['scope'],
       //'state' => $_POST['state],
       //'session_state' => $_POST['session_state']
    ];

   /*
   $sql = "INSERT INTO login (mail, displayName, jobTitle, access_token, expires_in, scope, state, session_state, lastlogin, created_at) VALUES (:mail, :displayName, :jobTitle, :access_token, :expires_in, :scope, :state, :session_state, NOW(), NOW() )";
   if ( $pdo->prepare($sql)->execute($data) ) {
      echo json_encode($data);
   } else {
      echo json_encode(array("status" => "ERROR: BBDD"));
   }
   */

}
elseif (array_key_exists('error', $_POST))
{
   $data = $_POST;
}
else
{
   $data = [
      'error' => 'bad_request',
      'data' => null,
      'message' => null,
      'status' => 'error'
   ];
}

echo json_encode($data);
?>
