<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Http;

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if (!session()->has('authenticated') || session()->get('authenticated') !== true) {
                $slug = session('customer', '');
                return redirect("/$slug");
            }
            return $next($request);
        });
    }

    public function dashboard()
    {
        $data = json_encode([
            'customer' => session('customer')
        ]);
        $currentEHR = session('currentEHR') && session('currentEHR') == 'googlehealth' ? 'ehr-default' : session('currentEHR');
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => env('API_URL').$currentEHR.'/practitioner',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer '.session('accessToken'),
                'Content-Type: application/json',
                'Content-Length: '. strlen($data)
            ),
        ));
        $response = curl_exec($curl);
        $httpStatusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if($httpStatusCode == 401){
            $slug = session()->has('customer') ? session()->get('customer') : "";
            return redirect("/$slug");
        }
        curl_close($curl);
        $responseData = json_decode($response, true);
        if ((isset($responseData['data']) && $responseData['data']) || $httpStatusCode === 403) {
            session([
                'PractitionerId' => isset($responseData['data']['gh_practitioner_id']) && $responseData['data']['gh_practitioner_id'] != "" ? $responseData['data']['gh_practitioner_id'] : $responseData['data']['PractitionerId'],
                'PractitionerName' => $responseData['data']['prefix'].' '.$responseData['data']['fullName'],
                'suffix' => $responseData['data']['suffix'],
                'features' => isset($responseData['data']['features']) && is_array($responseData['data']['features']) ? $responseData['data']['features'] : [],
                'jwt_token' => $responseData['data']['jwt_token'] ?? "",
                'currentEHR'=> isset($responseData['data']['gh_practitioner_id']) && $responseData['data']['gh_practitioner_id'] != "" && $responseData['data']['gh_practitioner_id'] != null ? 'googlehealth' : session('currentEHR')
            ]);
            if(isset($responseData['data']['notes']) && count($responseData['data']['notes']) > 0){
                session(['notes' => $responseData['data']['notes']]);    
            }else{
                session(['notes' => ['SOAPNOTE'=>'Soap Summary']]);
            }
            return view('dashboard', compact('httpStatusCode'));
        } else {
            $httpStatusCode = 403;
            return view('dashboard', compact('httpStatusCode'));
        }
    }

    public function scribe()
    {
        if(in_array('SCRIBE', session('features', []))){
            $currentEHR = session()->has('currentEHR') && session()->get('GHPractitionerId') ? 'googlehealth' : session()->get('currentEHR');
            if($currentEHR == 'epic'){
                return view('epic');
            }elseif($currentEHR == 'googlehealth'){
                session(['currentEHR'=>'googlehealth']);
                return view('scribe');
            }else{
                return view('scribe');
            }
        }else{
            return redirect()->route('dashboard');
        }
    }

    /**
     * Download the PDF file.
     */
    public function downloadPDF(Request $request)
    {
        $content = $request->input('content');
        if (empty($content)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Content is required.'
            ], 400);
        }
        
        if($request->has('notetype') && $request->get('notetype') == 'INVENTORYNOTES'){
            $apiendPoint = env('API_URL').'inventory';
            $data = [
                'appointmentId' => $request->input('appointmentId'),
                'inventoryData' => $request->input('inventoryData')
            ];
            // Make the POST request using Laravel's HTTP client
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . session('accessToken') .', Medx '. session('jwt_token'),
            ])->asForm()->post($apiendPoint, $data);
            // Check if the request was successful
            if ($response->successful()) {
                \Log::info('data inserted successful.');
            } else {
                // Handle error or failure
                \Log::info('File not found or downloaded from origin '.$response);
            }
        }
        $html = view('pdf.pdf-preview', compact('content'))->render();
        $pdf = Pdf::loadHTML($html);
        return response($pdf->output(), 200)
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'attachment; filename="note.pdf"');
    }
}
