<?php

namespace App\Http\Controllers;

use App\Models\Pro;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;

use App\Models\Note;
use App\Models\Client;
use App\Models\Section;
use App\Models\SectionTemplate;

class NoteController extends Controller
{

    public function dashboard(Request $request, Client $patient, Note $note)
    {
        $pros = $this->pros;
        $noteSections = $note->sections;
        $allSections = SectionTemplate::where('is_active', true)->get();
        foreach ($allSections as $section) {
            $section->used = false;
            foreach ($noteSections as $noteSection) {
                if ($noteSection->sectionTemplate->id === $section->id) {
                    $section->used = true;
                    $section->section_uid = $noteSection->uid;
                    break;
                }
            }
        }
        return view('app.patient.note.dashboard', compact('patient', 'note', 'pros', 'allSections'));
    }

    public function renderNote($noteUid, Request $request)
    {

        $note = Note::where('uid', $noteUid)->first();
        $client = Client::where('id', $note->client_id)->first();

        return view('client/note', compact('note', 'client'));
    }

    // JAVA ONLY
    public function getDefaultValueForSection($patientID, $sectionTemplateID)
    {
        $contentData = [];
        $summaryHtml = '';
        $patient = Client::where('id', $patientID)->first();
        $sectionTemplate = SectionTemplate::where('id', $sectionTemplateID)->first();

        if ($sectionTemplate->is_canvas) {
            if (file_exists(resource_path('views/app/patient/canvas-sections/' . $sectionTemplate->internal_name . '/default.php'))) {
                // default should simply assign to $contentData
                include(resource_path('views/app/patient/canvas-sections/' . $sectionTemplate->internal_name . '/default.php'));

                ob_start();
                include(resource_path('views/app/patient/canvas-sections/' . $sectionTemplate->internal_name . '/summary.php'));
                $summaryHtml = ob_get_contents();
                ob_end_clean();
            }
        } else {
            if (file_exists(storage_path('sections/' . $sectionTemplate->internal_name . '/default.php'))) {
                // default should simply assign to $contentData and $summaryHtml as needed
                include(storage_path('sections/' . $sectionTemplate->internal_name . '/default.php'));
            }
        }
        return [
            'contentData' => $contentData,
            'summaryHtml' => $summaryHtml
        ];
    }

    public function processFormSubmit(Request $request)
    {

        $guestAccessCode = $request->get('guest_access_code');
        if($guestAccessCode){
            //its from guest
            $sectionForToken = Section::where('guest_access_code', $guestAccessCode)->first();
            abort_if(!$sectionForToken, 401, 'Unauthorized');
        }else{
            //its not from guest so require performer
            abort_if(!$this->performer, 401, 'Unauthorized');
            abort_if(!$this->performer->is_active, 401, 'Unauthorized');
        }

        // TODO require
        $section_uid =  $request->get('section_uid');

        $section = Section::where('uid', $section_uid)->first();
        $note = Note::where('id', $section->note_id)->first();
        $client = null;
        if($note){
            $client = Client::where('id', $note->client_id)->first();
        }else{
            $client = Client::where('id', $section->client_id)->first();
        }

        $patient = $client;
        $sectionTemplate = SectionTemplate::where('id', $section->section_template_id)->first();

        $newContentData = [];
        $newSummaryHtml = "";

        $sectionInternalName = $sectionTemplate->internal_name;
        if ($sectionTemplate->is_canvas) {

            $response = null;
            $data = [
                'uid' => $client->uid,
                'key' => $sectionTemplate->internal_name,
                'data' => $request->get('data')
            ];

            $response = $this->calljava($request, '/client/updateCanvasData', $data, $guestAccessCode);
            //TODO: handle $response->success == false

            if($note){
                $client = Client::where('id', $note->client_id)->first();
            }else{
                $client = Client::where('id', $section->client_id)->first();
            }

            $patient = $client;
            if (file_exists(resource_path("views/app/patient/canvas-sections/{$sectionInternalName}/processor.php"))) {
                include(resource_path("views/app/patient/canvas-sections/{$sectionInternalName}/processor.php"));
            } else {
                $newContentData = json_decode($request->get('data'), true);
            }

            ob_start();
            include(resource_path("views/app/patient/canvas-sections/{$sectionInternalName}/summary.php"));
            $newSummaryHtml = ob_get_contents();
            ob_end_clean();
            // TODO call Java to update the canvas
        } elseif (file_exists(storage_path('sections/' . $sectionTemplate->internal_name . '/form.blade.php'))) {

            include(storage_path('sections/' . $sectionTemplate->internal_name . '/processor.php'));

            ob_start();
            include(storage_path('sections/' . $sectionTemplate->internal_name . '/summary.php'));
            $newSummaryHtml = ob_get_contents();
            ob_end_clean();
        } else {

            $newContentData = json_decode($request->get('data'), true);
            if (isset($newContentData['value'])) {
                $newSummaryHtml = $newContentData['value'];
            }
        }

        $response = null;
        $data = [
            'uid' => $section->uid,
            'contentData' => json_encode($newContentData),
            'summaryHtml' => $newSummaryHtml
        ];
        $response = $this->calljava($request, '/section/update', $data, $guestAccessCode);
        return [
            'success' => $response['success'],
            'newSummaryHtml' => $newSummaryHtml
        ];
    }

    // TODO move to utility
    private function callJava($request, $endPoint, $data, $guestAccessCode = null)
    {
        $url =  config('stag.backendUrl') . $endPoint;
        $response = Http::asForm()
            ->withHeaders([
                'sessionKey' => $request->cookie('sessionKey'),
                'guestAccessCode' => $guestAccessCode
            ])
            ->post($url, $data)
            ->json();
        return $response;
    }

}
