<?php
namespace App\Http\Controllers;

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

class EligibilityController 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 index()
    {
        if(in_array('EXPLANATIONOFBENEFIT', session('features', []))){
            $practitioner = session('PractitionerId');
            if(session()->has($practitioner) === false){
                session([$practitioner => ['procedure_code', 'date_of_service', 'description', 'units', 'amount_billed', 'amount_paid', 'deductible', 'copay', 'out_of_pocket', 'remark_code', 'remark_explanation']]);
            }
            return view('eob');
        }else{
            return redirect()->route('dashboard');
        }
    }

    public function checkEligibility()
    {
        if(in_array('ELIGIBILITY', session('features', []))){
            $data = json_encode(['patientId'=>'daf74a6c-6092-4c9f-8a93-fcec6498f587', 'memberId'=>'120268315301', 'practitionerId'=>session('PractitionerId'), 'customer' => session('customer')]);
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => env('API_URL').'dentalxchange/check-eligibility',
                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') .', Medx '. session('jwt_token'),
                    '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['success']) && $responseData['success']) {
                $locations = $responseData['data']['locations'];
                return view('eligibility', compact('locations'));
                
                $old = $responseData['data']['old'];
                $latest = $responseData['data']['latest'];
                $difference = $responseData['data']['difference'];
                $differencePosition = $responseData['data']['differencePosition'];
                $getResponse = isset($responseData['data']['getResponse']['response']) ? $responseData['data']['getResponse']['response'] : [];
                
            } else {
                return redirect()->route('dashboard');
            }
        }else{
            return redirect()->route('dashboard');
        }
    }

    public function updateSession(Request $request) {
        $request->validate([
            'fields' => 'required|array',
            'fields.*' => 'required|string',
        ]);
        $practitioner = session('PractitionerId');
        session([$practitioner => $request->get('fields')]);
        return response()->json(['session' => session($practitioner)]);
    }

    private function objectToArray($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }
        return is_array($data) ? array_map([$this, 'objectToArray'], $data) : $data;
    }
    
    /**
     * Download the PDF file.
     */
    public function downloadPDF(Request $request)
    {
        try {
            $request->validate([
                'response' => 'required',
                'parseResponse' => 'required',
            ]);
            $images = [
                "how_to_reg_icon" => asset('public/assets/img/how_to_reg_icon.svg'),
                "medical_services_icon" => asset('public/assets/img/medical_services_icon.svg'),
                "confirmation_number_icon" => asset('public/assets/img/confirmation_number_icon.svg'),
                "date_range_icon" => asset('public/assets/img/date_range_icon.svg')
            ];
            $responseJson = json_decode($request->get('response'));
            $response = $this->objectToArray($responseJson);
            $parseResponseJson = json_decode($request->get('parseResponse'));
            $parseResponse = [];
            if (is_array($parseResponseJson) || is_object($parseResponseJson)) {
                $parseResponse = array_map(function ($object) {
                    return is_object($object) ? get_object_vars($object) : $object;
                }, (array) $parseResponseJson);   
            }
            $html = view('pdf.eligibility', compact('response', 'parseResponse', 'images'))->render();
            $pdf = Pdf::loadHTML($html)->setPaper('A4', env('PAGEMODE'));
            return response($pdf->output(), 200)
                ->header('Content-Type', 'application/pdf')
                ->header('Content-Disposition', 'attachment; filename="eligibility.pdf"');
        } catch (\Exception $e) {
            return response()->json(['message' => 'Something went wrong. Please try again later.'], 500);
        }
    }
}
