<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class GetDataApiController extends Controller
{
    const URL   = 'https://siakadu.unesa.ac.id/api/apiunggun';
    const URLS  = 'https://siakadu.unesa.ac.id/api/dashboard';

    //
    public static function getDosen()
    {
        $client = new Client();

        $apiRequest = $client->request('POST', GetDataApiController::URLS, [
            'form_params' =>
            [
                'kondisi' => 'dosen_aktif',
            ]
        ]);

        return json_decode($apiRequest->getBody()->getContents(), true);
    }

    public static function getAccount($nim)
    {
        // $client = new Client();

        // $apiRequest = $client->request('POST', GetDataApiController::URL, [
        //     'form_params' =>
        //     [
        //         'username'  => $nim,
        //         'kondisi'   => 'cekhakakses'
        //     ]
        // ]);

        // $gcon = utf8_encode($apiRequest->getBody()->getContents());
        // $data = unserialize($gcon);

        // return $data;

        try {
            $client = new Client();
    
            $apiRequest = $client->request('POST', GetDataApiController::URL, [
                'form_params' => [
                    'username' => $nim,
                    'kondisi'  => 'cekhakakses'
                ]
            ]);
    
            $response = $apiRequest->getBody()->getContents();
    
            // Coba unserialize langsung tanpa utf8_encode
            $data = @unserialize($response);
    
            if ($data !== false) {
                return $data;
            }
    
            // Kalau unserialize gagal, coba cek apakah data berupa JSON
            $json = json_decode($response, true);
            if ($json !== null) {
                return $json;
            }
    
            // Log jika data tidak bisa di-unserialize dan bukan JSON
            Log::error("Gagal memproses response API untuk NIM: $nim\nResponse:\n$response");
    
            return null;
        } catch (\Exception $e) {
            // Log exception jika gagal request
            Log::error("Exception saat memanggil API untuk NIM: $nim\n" . $e->getMessage());
            return null;
        }
    }

}
