<?php 

use App\Models\Page;

$page = Page::where('client_id', $patient->id)->where('category', 'CANVAS')->where('key', 'cc_hpi')->first();
$nextFuPage = Page::where('client_id', $patient->id)->where('category', 'CANVAS')->where('key', 'next_fu')->first();


/** @var \App\Models\Pro $hcpPro */
/** @var \App\Models\Pro $pro */
/** @var \App\Models\Note $note */

if(!@$hcpPro) {
    if(@$note) {
        $hcpPro = $note->hcpPro;
    }
    else {
        $hcpPro = $pro; // should never get here
    }
}


$contentData = [];

if($page){
    $contentData = json_decode($page->data, true);
        
    if(!isset($contentData[$hcpPro->id])) {
        $contentData[$hcpPro->id] = [
            'current_cc' => []
        ];
    }

    if($nextFuPage){
        if (isset($canvasData["next_fu"]) && isset($canvasData["next_fu"][$hcpPro->id])) {
            $nextFuData = json_decode($page->data, true);
            $nextFU = $nextFuData[$hcpPro->id];
            if(isset($nextFU['next_cc']) && isset($nextFU['next_cc']['list']) && count($nextFU['next_cc']['list'])) {
                $prefillData = array_map(function($_x) {
                    if(!isset($_x['icd'])) $_x['icd'] = '';
                    if(!isset($_x['memo'])) $_x['memo'] = '';
                    $_x['hpi'] = [
                        'free_text' => ''
                    ];
                    return $_x;
                }, $nextFU['next_cc']['list']);
                $contentData[$hcpPro->id]['current_cch'] = [
                    'list' => $prefillData
                ];
            }
        }
    }
    $contentData = $contentData[$hcpPro->id];
    
}else{
    if ($patient->canvas_data) {
        $canvasData = json_decode($patient->canvas_data, true);
    
        if(!isset($canvasData["cc_hpi"])) $canvasData["cc_hpi"] = [];


        if(!isset($canvasData["cc_hpi"][$hcpPro->id])) {
            $canvasData["cc_hpi"][$hcpPro->id] = [
                'current_cc' => []
            ];
        }

        if (isset($canvasData["next_fu"]) && isset($canvasData["next_fu"][$hcpPro->id])) {
    
            $nextFU = $canvasData["next_fu"][$hcpPro->id];
            if(isset($nextFU['next_cc']) && isset($nextFU['next_cc']['list']) && count($nextFU['next_cc']['list'])) {
                $prefillData = array_map(function($_x) {
                    if(!isset($_x['icd'])) $_x['icd'] = '';
                    if(!isset($_x['memo'])) $_x['memo'] = '';
                    $_x['hpi'] = [
                        'free_text' => ''
                    ];
                    return $_x;
                }, $nextFU['next_cc']['list']);
                $contentData[$hcpPro->id]['current_cch'] = [
                    'list' => $prefillData
                ];
            }
        }

        $contentData = $canvasData['cc_hpi'][$hcpPro->id];
        
    }
}

if(!isset($contentData['current_cc'])){
    $contentData['current_cc'] = [];
}


