<?php

namespace App\Http\Controllers;

use App\Models\Appointment;
use App\Models\BDTDevice;
use App\Models\CareMonth;
use App\Models\Client;
use App\Models\ClientBDTDevice;
use App\Models\ClientInfoLine;
use App\Models\Facility;
use App\Models\Handout;
use App\Models\NoteTemplate;
use App\Models\Pro;
use App\Models\ProProAccess;
use App\Models\SectionTemplate;
use App\Models\Ticket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class PatientController extends Controller
{
    public function dashboard(Request $request, Client $patient )
    {
        $mcpPros = Pro::where('is_enrolled_as_mcp', true)->get();
        $facilities = []; // Facility::where('is_active', true)->get();
        $devices = BDTDevice::where('is_active', true)->orderBy('imei', 'asc')->get();
        $devices = $devices->filter(function ($record) {
            $matching = ClientBDTDevice
                ::where('device_id', $record->id)
                ->where('is_active', true)
                ->get();
            return count($matching) === 0;
        });
        $dxInfoLines = ClientInfoLine::where('client_id', $patient->id)
            ->where('category', 'dx')
            ->where('is_removed', false)
            ->orderBy('content_text', 'asc')
            ->get();
        return view('app.patient.dashboard',
            compact('patient', 'facilities', 'devices', 'dxInfoLines'));
    }

    public function actionItems(Request $request, Client $patient )
    {
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items', compact('patient', 'facilities'));
    }

    public function actionItemsErx(Request $request, Client $patient, $filter = 'open')
    {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-erx', compact('patient', 'facilities', 'filter', 'allPros'));
    }

    public function actionItemsLab(Request $request, Client $patient, $filter = 'open')
    {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-lab', compact('patient', 'facilities', 'filter', 'allPros'));
    }

    public function actionItemsImaging(Request $request, Client $patient, $filter = 'open')
    {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-imaging', compact('patient', 'facilities', 'filter', 'allPros'));
    }

    public function actionItemsEquipment(Request $request, Client $patient, $filter = 'open')
    {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-equipment', compact('patient', 'facilities', 'filter', 'allPros'));
    }

    public function actionItemsOther(Request $request, Client $patient, $filter = 'open')
    {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-other', compact('patient', 'facilities', 'filter', 'allPros'));
    }

    public function actionItemsErxSingle(Request $request, Client $patient, Ticket $ticket) {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-erx-single', compact('patient', 'facilities', 'allPros', 'ticket'));
    }
    public function actionItemsLabSingle(Request $request, Client $patient, Ticket $ticket) {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-lab-single', compact('patient', 'facilities', 'allPros', 'ticket'));
    }
    public function actionItemsImagingSingle(Request $request, Client $patient, Ticket $ticket) {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-imaging-single', compact('patient', 'facilities', 'allPros', 'ticket'));
    }
    public function actionItemsEquipmentSingle(Request $request, Client $patient, Ticket $ticket) {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-equipment-single', compact('patient', 'facilities', 'allPros', 'ticket'));
    }
    public function actionItemsOtherSingle(Request $request, Client $patient, Ticket $ticket) {
        $allPros = Pro::all();
        $facilities = []; // Facility::where('is_active', true)->get();
        return view('app.patient.action-items-other-single', compact('patient', 'facilities', 'allPros', 'ticket'));
    }

    public function intake(Request $request, Client $patient )
    {
        $files = File::allFiles(resource_path('views/app/intake-templates'));
        $templates = [];
        foreach ($files as $file) {
            $templates[] = str_replace(".blade.php", "", $file->getFilename());
        }
        return view('app.patient.intake', compact('patient', 'templates'));
    }

    public function carePlan(Request $request, Client $patient )
    {
        return view('app.patient.care-plan', compact('patient'));
    }

    public function medications(Request $request, Client $patient )
    {
        $infoLines = ClientInfoLine::where('client_id', $patient->id)
            ->where('category', 'rx')
            ->where('is_removed', false)
            ->orderBy('content_text', 'asc')
            ->get();
        return view('app.patient.medications', compact('patient', 'infoLines'));
    }

    public function dxAndFocusAreas(Request $request, Client $patient )
    {
        $dxInfoLines = ClientInfoLine::where('client_id', $patient->id)
            ->where('category', 'dx')
            ->where('is_removed', false)
            ->orderBy('content_text', 'asc')
            ->get();
        return view('app.patient.dx-and-focus-areas', compact('patient', 'dxInfoLines'));
    }

    public function careTeam(Request $request, Client $patient )
    {
        $infoLines = ClientInfoLine::where('client_id', $patient->id)
            ->where('category', 'care_team')
            ->where('is_removed', false)
            ->get();
        return view('app.patient.care-team', compact('patient', 'infoLines'));
    }

    public function devices(Request $request, Client $patient )
    {
        $devices = BDTDevice::where('is_active', true)->get();
        $devices = $devices->filter(function ($record) {
            $matching = ClientBDTDevice
                ::where('device_id', $record->id)
                ->where('is_active', true)
                ->get();
            return count($matching) === 0;
        });
        return view('app.patient.devices', compact('patient', 'devices'));
    }

    public function measurements(Request $request, Client $patient )
    {
        return view('app.patient.measurements', compact('patient'));
    }

    public function labsAndStudies(Request $request, Client $patient )
    {
        return view('app.patient.labs-and-studies', compact('patient'));
    }

    public function history(Request $request, Client $patient )
    {
        $infoLines = ClientInfoLine::where('client_id', $patient->id)
            ->where('category', 'LIKE', 'history_%')
            ->where('is_removed', false)
            ->get();
        return view('app.patient.history', compact('patient', 'infoLines'));
    }

    public function memos(Request $request, Client $patient )
    {
        return view('app.patient.memos', compact('patient'));
    }

    public function sms(Request $request, Client $patient )
    {
        return view('app.patient.sms', compact('patient'));
    }

    public function smsNumbers(Request $request, Client $patient )
    {
        return view('app.patient.sms-numbers', compact('patient'));
    }

    public function immunizations(Request $request, Client $patient )
    {
        return view('app.patient.immunizations', compact('patient'));
    }

    public function allergies(Request $request, Client $patient )
    {
        $infoLines = ClientInfoLine::where('client_id', $patient->id)
            ->where('category', 'allergy')
            ->where('is_removed', false)
            ->get();
        return view('app.patient.allergies', compact('patient', 'infoLines'));
    }

    public function notes(Request $request, Client $patient, $filter = 'active')
    {
        $pros = $this->pros;
        return view('app.patient.notes', compact('patient','pros', 'filter'));
    }

    public function sections(Request $request, Client $patient )
    {
        $pros = $this->pros;
        $sections = $patient->sections;

        $allSections = SectionTemplate::where('is_active', true)->get();
        foreach ($allSections as $section) {
            $section->used = false;
            foreach ($sections as $section) {
                if ($section->sectionTemplate->id === $section->id) {
                    $section->used = true;
                    $section->section_uid = $section->uid;
                    break;
                }
            }
        }
        return view('app.patient.sections', compact('patient', 'pros', 'allSections'));
    }

    public function handouts(Request $request, Client $patient )
    {
        $handouts = Handout::where('is_active', true)->get();
        return view('app.patient.handouts', compact('patient', 'handouts'));
    }

    public function settings(Request $request, Client $patient )
    {
        return view('app.patient.settings', compact('patient'));
    }

    public function pros(Request $request, Client $patient )
    {
        return view('app.patient.pros', compact('patient'));
    }

    public function account(Request $request, Client $patient )
    {
        return view('app.patient.account', compact('patient'));
    }

    public function careChecklist(Request $request, Client $patient )
    {
        return view('app.patient.care-checklist', compact('patient'));
    }

    public function documents(Request $request, Client $patient )
    {
        return view('app.patient.documents', compact('patient'));
    }

    public function incomingReports(Request $request, Client $patient )
    {
        return view('app.patient.incoming-reports', compact('patient'));
    }

    public function education(Request $request, Client $patient )
    {
        return view('app.patient.education', compact('patient'));
    }

    public function messaging(Request $request, Client $patient )
    {
        return view('app.patient.messaging', compact('patient'));
    }

    public function duplicate(Request $request, Client $patient )
    {
        return view('app.patient.duplicate', compact('patient'));
    }

    public function careMonths(Request $request, Client $patient )
    {
        $careMonths = CareMonth::where('client_id', $patient->id)->orderBy('start_date', 'desc')->get();
        return view('app.patient.care-months', compact('patient', 'careMonths'));
    }

    public function presence(Request $request, Client $patient )
    {
        return json_encode([
            "online" => $patient->is_online
        ]);
    }

    public function embedSection(Request $request, Client $patient, $section, $selectable) {
        return view('app.patient.partials.' . $section, compact('patient', 'selectable'));
    }

    public function calendar(Request $request, Client $patient, Appointment $currentAppointment) {

        $pros =  Pro::all();
        if($this->pro && $this->pro->pro_type != 'ADMIN'){
            $accessiblePros = ProProAccess::where('owner_pro_id', $this->pro->id);
            $accessibleProIds = [];
            foreach($accessiblePros as $accessiblePro){
                $accessibleProIds[] = $accessiblePro->id;
            }
            $accessibleProIds[] = $this->pro->id;
            $pros = Pro::whereIn('id', $accessibleProIds)->get();
        }

        return view('app.patient.appointment-calendar', compact('pros', 'patient', 'currentAppointment'));
    }

    public function programs(Request $request, Client $patient, $filter = '') {
        $pros = $this->pros;
        return view('app.patient.programs', compact('patient', 'pros', 'filter'));
    }

    public function flowsheets(Request $request, Client $patient, $filter = '') {
        $pros = $this->pros;
        return view('app.patient.flowsheets', compact('patient', 'pros', 'filter'));
    }

    public function vitalsGraph(Request $request, Client $patient, $filter = '') {
        $pros = $this->pros;
        return view('app.patient.vitals-graph', compact('patient', 'pros', 'filter'));
    }

    public function tickets(Request $request, Client $patient) {
        $pros = $this->pros;
        $allPros = Pro::all();
        return view('app.patient.tickets', compact('patient', 'pros', 'allPros'));
    }

    public function appointments(Request $request, Client $patient, $forPro = 'all', $status = 'all') {
        $pros = $this->pros;
        $appointments = $patient->appointmentsForProByStatus('all', 'ALL');
        $appointmentProIDs = $appointments->map(function($_item) {
            return $_item->pro_id;
        });
        $appointmentPros = Pro::whereIn('id', $appointmentProIDs)->get();
        $appointments = $patient->appointmentsForProByStatus($forPro, strtoupper($status));
        return view('app.patient.appointments',
            compact('patient', 'pros', 'appointments', 'appointmentPros', 'forPro', 'status'));
    }

    public function getTicket(Request $request, Ticket $ticket) {
        $ticket->data = json_decode($ticket->data);
//        $ticket->created_at = friendly_date_time($ticket->created_at);
        $ticket->assignedPro;
        $ticket->managerPro;
        $ticket->orderingPro;
        $ticket->initiatingPro;
        return json_encode($ticket);
    }

    public function mcpRequests(Request $request, Client $patient) {
        return view('app.patient.mcp-requests', compact('patient'));
    }

    public function eligibleRefreshes(Request $request, Client $patient) {
        return view('app.patient.eligible-refreshes', compact('patient'));
    }
}
