<?php

namespace App\Repositories\Auth;

use GuzzleHttp\Client as GuzzleHttpClient;

class SsoRepository
{
    /**
     * Check auth from sso.
     *
     * @param  varchar  $sessionId
     * @return \Illuminate\Http\Response
     */
    public function sso($sessionId)
    {
        // Get Token
        try {
            $clientauthscsso = new GuzzleHttpClient();
            $apiRequestauthscsso = $clientauthscsso->request('GET', 'https://sso.unesa.ac.id/check-secret-token/' . $sessionId);
            $cektoken = json_decode($apiRequestauthscsso->getBody()->getContents());
        } catch (\Exception $apiRequestauthscsso) {
            $error = 'Token Tidak Ditemukan';
            return $error;
        }

        // Check Validation Token
        try {
            $clientauthtknsso = new GuzzleHttpClient();
            $apiRequestauthtknsso = $clientauthtknsso->request('GET', 'https://sso.unesa.ac.id/check-token/' . $cektoken);
            $checkakses = json_decode($apiRequestauthtknsso->getBody()->getContents());
        } catch (\Exception $apiRequestauthtknsso) {
            $error = 'Token Tidak Valid';
            return $error;
        }

        // Get Account
        try {
            $clientbiodata = new GuzzleHttpClient();
            $apiRequestbiodata = $clientbiodata->request('GET', 'https://sso.unesa.ac.id/userid/' . $checkakses->email);
            $aksessso = json_decode($apiRequestbiodata->getBody()->getContents());
        } catch (\Exception $apiRequestbiodata) {
            $error = "Data Tidak Ditemukan";
            return $error;
        }

        return $aksessso;
    }

    /**
     * Get account from siakadu.
     *
     * @param  varchar  $nim
     * @return \Illuminate\Http\Response
     */
    public function getAccount($nim)
    {
        $url = "https://siakadu.unesa.ac.id/api/apiunggun";
        $data = array('username' => $nim, 'kondisi' => "cekhakakses");
        $x = kirim_data($url, 'post', $data);
        $user = unserialize($x['isi']);

        return $user;
    }
}
