<?php

namespace App\Http\Controllers\OpenErm;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Controller;

class PatientController extends Controller
{
    private $baseUrl = 'https://erm.codelfi.com';
    private $clientId = 'L31xI_99M2_atm565sWplF6XVTLliDID6u7ZQwF6Y7U';
    private $clientSecret = 'yu2Mo4550dtl5Fi_HrdGKHjRPTXcfUZLvKeLY5_za0Qi5tIts3HY6PTKt9dfFANX7y8GaLLFJn6WMOAjh0OeCg';
    private $username = 'VNS-admin-34';
    private $password = '2Uj3Y3fKDgVgLbf';

    public function getPatientList(Request $request)
    {
        $accessToken = $this->getAccessToken();

        $searchParams = [];

        if ($request->has('fname')) {
            $searchParams['fname'] = $request->input('fname');
        }

        if ($request->has('lname')) {
            $searchParams['lname'] = $request->input('lname');
        }

        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $accessToken,
        ])->get($this->baseUrl . '/apis/default/api/patient', $searchParams);

        return $response->json();
    }
    public function getPatientById($puuid)
    {
        $accessToken = $this->getAccessToken();

        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $accessToken,
        ])->get($this->baseUrl . '/apis/default/api/patient/' . $puuid);

        return $response->json();
    }
    public function registerPatient(Request $request)
    {
        $accessToken = $this->getAccessToken();

        $patientData = $request->validate([
            'title' => 'required|string',
            'fname' => 'required|string',
            'mname' => 'nullable|string',
            'lname' => 'required|string',
            'street' => 'required|string',
            'postal_code' => 'required|string',
            'city' => 'required|string',
            'state' => 'required|string',
            'country_code' => 'required|string',
            'phone_contact' => 'required|string',
            'DOB' => 'required|date',
            'sex' => 'required|string',
            'race' => 'nullable|string',
            'ethnicity' => 'nullable|string',
        ]);

        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $accessToken,
        ])->post($this->baseUrl . '/apis/default/api/patient', $patientData);

        return $response->json();
    }

    private function getAccessToken()
    {
        if (Cache::has('access_token')) {
            return Cache::get('access_token');
        }

        $response = Http::asForm()->withHeaders([
            'Authorization' => 'Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
        ])->post($this->baseUrl . '/oauth2/default/token', [
            'grant_type' => 'password',
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'user_role' => 'users',
            'username' => $this->username,
            'password' => $this->password,
            'scope' => 'openid offline_access api:oemr user/patient.read user/patient.write',
        ]);

        $tokenData = $response->json();

        if (isset($tokenData['access_token'])) {
            Cache::put('access_token', $tokenData['access_token'], now()->addSeconds($tokenData['expires_in'] - 60));
            Cache::put('refresh_token', $tokenData['refresh_token'], now()->addDays(30));
        }

        return $tokenData['access_token'] ?? null;
    }

    private function refreshAccessToken()
    {
        $refreshToken = Cache::get('refresh_token');

        if (!$refreshToken) {
            return $this->getAccessToken();
        }

        $response = Http::asForm()->withHeaders([
            'Authorization' => 'Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
        ])->post($this->baseUrl . '/oauth2/default/token', [
            'grant_type' => 'refresh_token',
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'refresh_token' => $refreshToken,
        ]);

        $tokenData = $response->json();

        if (isset($tokenData['access_token'])) {
            Cache::put('access_token', $tokenData['access_token'], now()->addSeconds($tokenData['expires_in'] - 60));
            if (isset($tokenData['refresh_token'])) {
                Cache::put('refresh_token', $tokenData['refresh_token'], now()->addDays(30));
            }
            return $tokenData['access_token'];
        }

        return $this->getAccessToken();
    }
}
