<?php

namespace App\Http\Controllers;

use App\Models\AppSession;
use App\Models\Page;
use App\Models\Point;
use App\Models\Pro;
use App\Models\SupplyOrder;
use App\Models\Ticket;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Http;

use App\Models\Note;
use App\Models\Client;
use App\Models\CompanyPro;
use App\Models\Section;
use App\Models\SectionTemplate;
use App\Models\Segment;
use App\Models\SegmentTemplate;
use Illuminate\Support\Facades\DB;

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;
                }
            }
        }

        // load supplyOrders created on note->effective_date for patient
        $supplyOrdersOnNote = SupplyOrder::where('client_id', $patient->id)
            ->where('is_cancelled', false)
            ->where('note_id', $note->id)
            ->get();

        // other open supplyOrders as of today
        $otherOpenSupplyOrders = SupplyOrder::where('client_id', $patient->id)
            ->where('is_cancelled', false)
            ->where('note_id', '<>', $note->id)
            ->get();

        $companyProIDs = DB::select('SELECT company_pro_id FROM company_pro_document WHERE related_client_id  = ?', [$patient->id]);

        $companyProIDInts = [];
        foreach($companyProIDs as $cpId){
            $companyProIDInts[] = $cpId->company_pro_id;
        }

        $companyPros = CompanyPro::whereIn('id', $companyProIDInts)->get();

        return view('app.patient.note.dashboard', compact('patient', 'note',
            'allSections',
            'companyPros',
            'supplyOrdersOnNote', 'otherOpenSupplyOrders'));
    }

    private function filterClientDocuments($documents){
        $clientDocs = [];
        foreach($documents as $doc){
            if(starts_with($doc['name'], 'client_')){
                array_push($clientDocs, $doc);
            }
        }
        return $clientDocs;
    }

    public function signConfirmation(Request $request, Client $patient, Note $note) {
        return view('app.patient.note.sign-confirmation', compact('patient', 'note'));
    }

    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'));
    }

    public function sectionView(Request $request, Client $patient, Note $note, Section $section, $form, Page $page = null) {
        return view("app.patient.page-sections." . $section->sectionTemplate->internal_name . "." . $form,
            compact('patient', 'note', 'section', 'page'));
    }

    public function print(Request $request, Client $patient, Note $note) {
        if($note->visitTemplate) {
            return view("app.patient.note.print.print", compact('patient', 'note'));
        }
        return view("app.patient.note.print.print-legacy", compact('patient', 'note'));
    }

    public function printV2(Request $request, Client $patient, Note $note) {
        if($note->visitTemplate) {
            return view("app.patient.note.print.print-v2", compact('patient', 'note'));
        }
        return view("app.patient.note.print.print-legacy", compact('patient', 'note'));
    }

    public function printV3(Request $request, Client $patient, Note $note) {
        if($note->visitTemplate) {
            return view("app.patient.note.print.print-v3", compact('patient', 'note'));
        }
        return view("app.patient.note.print.print-legacy", compact('patient', 'note'));
    }

    public function resolve(Request $request, Client $patient, Note $note) {
        return view("app.patient.note.resolve", compact('patient', 'note'));
    }

    public function getHtmlForSegment($segmentUid, $sessionKey){

        $summaryHtml = '';
        $editHtml = '';

        try {

            $performer = AppSession::where('session_key', $sessionKey)->first();
            if (!$performer || !$performer->is_active) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid session key'
                ]);
            }
            $pro = $performer->pro;

            $segment = Segment::where('uid', $segmentUid)->first();

            $recalculatedHtml = $segment->getRecalculatedHtml($performer, $sessionKey);

        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }

        return response()->json([
            'success'=>true,
            'summaryHtml' => $recalculatedHtml['summaryHtml'],
            'editHtml' => $recalculatedHtml['editHtml'],
        ]);
    }

    // JAVA ONLY
    // ... if hcpProId is passed, get from request
    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'))) {

                // for canvas section where we have pro mapped data, use hcpProId
                $hcpPro = null;
                if(\request()->input('hcpProUid')) {
                    $hcpPro = Pro::where('uid', \request()->input('hcpProUid'))->first();
                }

                $note = null;
                if(\request()->input('noteUid')) {
                    $note = Note::where('uid', \request()->input('noteUid'))->first();
                }

                // 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
        ];
    }

    // edit hpi (structured)
    public function editHPI(Note $note, Point $point) {
        return view('app.patient.note.edit-hpi', compact('note', 'point'));
    }

    public function hpiLog(Note $note, Point $point) {
        return view('app.patient.note.hpi-log', compact('note', 'point'));
    }

    // review log
    public function reviewLog(Point $point) {
        return view('app.patient.note.review-log', compact('point'));
    }

    // plan log
    public function planLog(Point $point) {
        return view('app.patient.note.plan-log', compact('point'));
    }

    // print/pdf
    public function downloadAsPdf(Request $request, Note $note) {
        $patient = $note->client;
        if($request->input('html')) {
            return view('app.patient.note.pdf', compact('note', 'patient'));
        }
        else {
            $pdf = \PDF::loadView('app.patient.note.pdf', compact('note', 'patient'));
            return $pdf->stream($note->created_at .'_' . 'note.pdf');
        }
    }

    public function generateCC(Request $request, Note $note) {
        $client = $note->client;
        return view('app.patient.segment-templates.chief_complaint.generate', compact('note', 'client'));
    }

    public function segmentSummary(Request $request, Segment $segment) {
        return '<div class="mrv-content border-top px-3 pt-2 mt-3">' . @$segment->summary_html . '</div>';
    }

    public function mrvSummary(Request $request, Note $note) {
        return view('app.patient.segment-templates.medrisk_vigilence.summary', [
            'note' => $note,
            'patient' => $note->client,
            'segment' => $note->coreSegment
        ]);
    }

    public function chartSegmentView(Request $request, Client $patient, $segmentInternalName, $view) {
        return view("app.patient.segment-templates.{$segmentInternalName}.{$view}", [
            'patient' => $patient,
            'note' => $patient->coreNote,
            'segmentInternalName' => $segmentInternalName,
            'closeOnSave' => true
        ]);
    }

    public function noteSegmentView(Request $request, Client $patient, Note $note, Segment $segment, $segmentInternalName, $view) {
        return view("app.patient.segment-templates.{$segmentInternalName}.{$view}", [
            'patient' => $patient,
            'note' => $note,
            'segment' => $segment,
            'segmentInternalName' => $segmentInternalName
        ]);
    }

    public function noteSegmentViewByName(Request $request, Note $note, $segmentInternalName, $view) {
        return view("app.patient.segment-templates.{$segmentInternalName}.{$view}", [
            'patient' => $note->client,
            'note' => $note,
            'segment' => $note->coreSegment,
            'segmentInternalName' => $segmentInternalName
        ]);
    }

    public function moduleView(Request $request, Note $note, $segmentInternalName, $view) {
        return view("app.patient.modules.{$segmentInternalName}.{$view}", [
            'patient' => $note->client,
            'note' => $note,
            'segment' => $note->coreSegment,
            'segmentInternalName' => $segmentInternalName
        ]);
    }

    public function rhsSidebar(Request $request, Client $patient, Note $note) {
        return view('app.patient.note.rhs-sidebar', compact('patient', 'note'));
    }

    public function medicationsCenter(Request $request, Client $patient, Note $note) {
        $points = $this->getPointsForWizard('MEDICATION', $patient, $note);
        list($medications, $counts) = $this->groupByState($points);
        return view('app.patient.medications-center', compact('patient', 'note', 'medications', 'counts'));
    }

    public function medicationsAddMultiPreexisting(Request $request, Note $note) {
        return view('app.patient.medications-add-multi-preexisting', compact('note'));
    }

    public function medicationsReconcile(Request $request, Client $patient, Note $note) {
        return view('app.patient.medications-reconcile', compact('patient', 'note'));
    }

    public function problemsQuickAdd(Request $request, Client $patient, Note $note) {
        return view('app.patient.problems-quick-add', compact('patient', 'note'));
    }

    public function problemsCenter(Request $request, Client $patient, Note $note) {
        $points = $this->getPointsForWizard('PROBLEM', $patient, $note);
        list($problems, $counts) = $this->groupByState($points);
        return view('app.patient.problems-center', compact('patient', 'note', 'problems', 'counts'));
    }

    public function goalsCenter(Request $request, Client $patient, Note $note) {
        $points = $this->getPointsForWizard('GOAL', $patient, $note, 'goal');
        list($goals, $counts) = $this->groupByState($points);
        return view('app.patient.goals-center', compact('patient', 'note', 'goals', 'counts'));
    }

    public function allergiesCenter(Request $request, Client $patient, Note $note) {
        $points = $this->getPointsForWizard('ALLERGY', $patient, $note);
        list($allergies, $counts) = $this->groupByState($points);
        return view('app.patient.allergies-center', compact('patient', 'note', 'allergies', 'counts'));
    }

    public function careteamCenter(Request $request, Client $patient, Note $note) {
        $points = $this->getPointsForWizard('CARE_TEAM_MEMBER', $patient, $note);
        list($careTeamMembers, $counts) = $this->groupByState($points);
        return view('app.patient.careteam-center', compact('patient', 'note', 'careTeamMembers', 'counts'));
    }

    private function getPointsForWizard($_category, $_patient, $_note, $_sortKey = 'name') {
        $query = "
SELECT p.id,
       p.uid,
       p.data,
       p.is_removed,
       p.is_removed_due_to_entry_error,
       p.added_in_note_id,
       p.addition_reason_category,
       p.removed_in_note_id,
       p.removal_reason_category,
       p.added_in_note_uid as added_note_uid,
       p.added_in_note_effective_date as added_on,
       p.removed_in_note_uid as removed_note_uid,
       p.removed_in_note_effective_dateest as removed_on,
       np.uid as note_point_uid,
       p.last_child_review_point_id,
       p.last_child_review_point_scoped_note_id,
       p.last_child_plan_point_id,
       p.last_child_plan_point_scoped_note_id,
       p.last_child_review_effective_date,
       p.last_child_plan_effective_date,
       p.last_child_review_data,
       p.last_child_plan_data,
       (p.last_child_review_creator_pro_first_name || ' ' || p.last_child_review_creator_pro_last_name) as last_child_review_creator,
       (p.last_child_plan_creator_pro_first_name || ' ' || p.last_child_plan_creator_pro_last_name) as last_child_plan_creator,
       p.last_child_review_point_scoped_note_uid as last_child_review_note_uid,
       p.last_child_plan_point_scoped_note_uid as last_child_plan_note_uid
FROM point p
    left join note_point np on p.id = np.point_id and np.note_id = {$_note->id} and np.is_active = TRUE
WHERE p.client_id = {$_patient->id} AND p.category = '{$_category}'
    ORDER BY ((p.data)::json->'{$_sortKey}')::text
";

        return DB::select($query);
    }

    private function groupByState($points) {

        $pointsByType = [
            "ACTIVE" => [],
            "HISTORIC" => [],
            "ENTRY_ERROR" => [],
        ];

        foreach ($points as $point) {
            if ($point->data) {
                $point->data = json_decode($point->data);
            }

            if(!$point->is_removed) {
                $point->state = "ACTIVE";
                $pointsByType["ACTIVE"][] = $point;
            }
            elseif($point->is_removed) {
                if(!$point->is_removed_due_to_entry_error) {
                    $point->state = "HISTORIC";
                    $pointsByType["HISTORIC"][] = $point;
                }
                else {
                    $point->state = "ENTRY_ERROR";
                    $pointsByType["ENTRY_ERROR"][] = $point;
                }
            }
        }

        return [
            array_merge($pointsByType["ACTIVE"], $pointsByType["HISTORIC"], $pointsByType["ENTRY_ERROR"]),
            [
                "ACTIVE" => count($pointsByType["ACTIVE"]),
                "HISTORIC" => count($pointsByType["HISTORIC"]),
                "ENTRY_ERROR" => count($pointsByType["ENTRY_ERROR"]),
            ]
        ];

    }

    public function supplementsCenter(Request $request, Client $patient, Note $note) {
        return view('app.patient.supplements-center', compact('patient', 'note'));
    }

    public function supplementsReconcile(Request $request, Client $patient, Note $note) {
        return view('app.patient.supplements-reconcile', compact('patient', 'note'));
    }

    public function nutritionCenter(Request $request, Client $patient, Note $note) {
        return view('app.patient.nutrition-center', compact('patient', 'note'));
    }

    public function exerciseCenter(Request $request, Client $patient, Note $note) {
        return view('app.patient.exercise-center', compact('patient', 'note'));
    }

    public function behaviorCenter(Request $request, Client $patient, Note $note) {
        return view('app.patient.behavior-center', compact('patient', 'note'));
    }

    public function ccmAgreement(Request $request, Note $note) {
        return view('app.patient.note.ccm-agreement', compact('note'));
    }

    public function rpmAgreement(Request $request, Note $note) {
        return view('app.patient.note.rpm-agreement', compact('note'));
    }

    // 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;
    }

}
