<?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\Erx;
use App\Models\Facility;
use App\Models\Handout;
use App\Models\IncomingReport;
use App\Models\MBClaim;
use App\Models\MBPayer;
use App\Models\Measurement;
use App\Models\Note;
use App\Models\NoteTemplate;
use App\Models\Pro;
use App\Models\Product;
use App\Models\ProProAccess;
use App\Models\SectionTemplate;
use App\Models\Shipment;
use App\Models\SupplyOrder;
use App\Models\Ticket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use App\Models\Bill;
use App\Models\ClientSMS;
use App\Models\AccountInvite;
use App\Models\ClientMemo;
use App\Models\ClientProAccess;
use Illuminate\Support\Facades\Http;
use PDF;

class McpController extends Controller
{

    public function patients(Request $request)
    {
        $pro = $this->performer->pro;
        $filters = $request->all();
        $patients = Client::whereNull('shadow_pro_id');
        
        //TODO: implement in admin controller 
        if($pro->pro_type != 'ADMIN'){
            $patients->where('mcp_pro_id', $pro->id);
        }

        //Also include the ones given access to:
        $proAccessClientIDs = ClientProAccess::where('pro_id', $pro->id)->pluck('client_id')->toArray();
        $patients = $patients->orWhereIn('id', $proAccessClientIDs);
        

        // filters
        /*
        array:18 [▼
          "age_category" => "LESS_THAN"
          "age_value_1" => "34"
          "age_value_2" => null
          "sex" => "M"
          "bmi_category" => "BETWEEN"
          "bmi_value_1" => "20"
          "bmi_value_2" => "25"
          "last_visit_category" => "LESS_THAN"
          "last_visit_value_1" => "2021-10-14"
          "last_visit_value_2" => null
          "next_appointment_category" => "LESS_THAN"
          "next_appointment_value_1" => "2021-10-15"
          "status" => "ACTIVE"
          "last_weighed_in_category" => "EXACTLY"
          "last_weighed_in_value_1" => "2021-10-07"
          "last_bp_category" => "BETWEEN"
          "last_bp_value_1" => "2021-10-01"
          "last_bp_value_2" => "2021-10-31"
        ]
        */

        if ($request->input('name')) {
            $name = trim($request->input('name'));
            if ($name) {
                $patients = $patients->where(function ($q) use ($name) {
                    $q->where('name_first', 'ILIKE', '%' . $name . '%')
                        ->orWhere('name_last', 'ILIKE', '%' . $name . '%');
                });
            }
        }

        if ($request->input('home_address_state')) {

            if($request->input('home_address_state') == 'NONE'){
                $patients = $patients->whereNull('mailing_address_state');
            }else if($request->input('home_address_state') == 'NOT_MD'){
                $patients = $patients->where('mailing_address_state', '<>' , 'MD');
            }else{
                $patients = $patients->where('mailing_address_state', '=' , $request->input('home_address_state'));
            }
        }

        $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2', false);
        $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
        $this->filterMultiQuery($request, $patients, 'usual_bmi_max', 'bmi_category', 'bmi_value_1', 'bmi_value_2', false);
        $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
        $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
        $this->filterMultiQuery($request, $patients, 'most_recent_completed_mcp_note_date', 'last_visit_category', 'last_visit_value_1', 'last_visit_value_2');

        $status = $request->input('status');
        if($status){
            if($status === 'ACTIVE'){
                $patients->where('is_active', true)->where(function($q) use ($status){
                    return $q->where('client_engagement_status_category', $status)
                        ->orWhereNull('client_engagement_status_category');
                });
            }elseif($status === 'NONE'){
                $patients->whereNull('client_engagement_status_category');
            }else {
                $patients->where('client_engagement_status_category', $status);
            }

        }

        $initiative = $request->input('initiative');
        if($initiative){
            $wildCardedInitiative = '%'.$initiative.'%';
            $patients->where('initiative', 'ilike', $wildCardedInitiative);
        }

        $include_test_records = $request->input('include_test_records');
        if(!$include_test_records){
            $patients = $patients->where(function ($q) {
                $q->whereNull('client_engagement_status_category')
                    ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
            });
        }

        if ($request->input('next_appointment_category')) {
            if($request->input('next_appointment_category') == 'NONE'){
                $patients = $patients->whereNull('next_mcp_appointment_id');
            }else{
                $self = $this;
                $patients = $patients->whereHas('nextMcpAppointment', function($pQry) use ($request, $self){
                    return $self->filterMultiQuery($request, $pQry, 'raw_date', 'next_appointment_category', 'next_appointment_value_1', 'next_appointment_value_2');
                });
            }
        }


        if ($request->input('chart_number')) {
            $patients = $patients->where('chart_number', 'ILIKE' , '%'.$request->input('chart_number').'%');
        }

        $sortBy = $request->input('sort_by') ?: 'name_first';
        $sortDir = $request->input('sort_dir') ?: 'ASC';

        $patients = $patients->orderByRaw("$sortBy $sortDir NULLS LAST");

        $patients = $patients->orderBy('created_at', 'DESC')->paginate(50);
        return view('app.mcp.patients', compact('patients', 'filters'));
    }

    public function notes(Request $request)
    {
        $filters = $request->all();
        $notes = Note::query();
        $notes = $notes->where('hcp_pro_id', $this->performer->pro->id);
        $this->filterMultiQuery($request, $notes, 'effective_time', 'date_category', 'date_value_1', 'date_value_2');
        $this->filterSimpleQuery($request, $notes, 'new_or_fu_or_na', 'new_or_fu_or_na');
        $notes = $notes->orderBy('created_at', 'DESC')->paginate(20);


        return view('app.mcp.notes', compact('notes','filters'));
    }

    public function appointments(Request $request)
    {
        $filters = $request->all();
        $appointments = Appointment::where('pro_id', $this->performer->pro->id);
        $this->filterMultiQuery($request, $appointments, 'raw_date', 'date_category', 'date_value_1', 'date_value_2');
        $this->filterSimpleQuery($request, $appointments, 'status', 'status');
        $appointments = $appointments->orderBy('end_time', 'DESC')->paginate(20);
        return view('app.mcp.appointments', compact('appointments', 'filters'));
    }

    public function bills(Request $request)
    {
        $filters = $request->all();
        $bills = Bill::where('hcp_pro_id', $this->performer->pro->id);
        $this->filterMultiQuery($request, $bills, 'created_at', 'date_category', 'date_value_1', 'date_value_2');
        $status = $request->get('status');
        if($status){
            if($status == 'CANCELLED') $bills = $bills->where('is_cancelled', true);
            if($status == 'NOT_CANCELLED') $bills = $bills->where('is_cancelled', false);
        }
        $bills = $bills->orderBy('created_at', 'DESC')->paginate(20);
        return view('app.mcp.bills', compact('bills', 'filters'));
    }

    public function clients_bdt_devices(Request $request){
        $filters = $request->all();

        $devices = ClientBDTDevice::select('client_bdt_device.*')
        ->join('client', 'client.id', '=', 'client_bdt_device.client_id')
        ->where('client.mcp_pro_id', $this->performer->pro->id);

        $this->filterMultiQuery($request, $devices, 'client_bdt_device.created_at', 'date_category', 'date_value_1', 'date_value_2');
        $status = $request->get('status');
        if($status){
            if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
            if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
        }
        $devices = $devices->orderBy('created_at', 'DESC')->paginate(20);

        return view('app.mcp.clients_bdt_devices', compact('devices', 'filters'));
    }

    public function memos(Request $request){
        $filters = $request->all();

        $memos = ClientMemo::select('client_memo.*')
        ->join('client', 'client.id', '=', 'client_memo.client_id')
        ->where('client.mcp_pro_id', $this->performer->pro->id);

        $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
        $this->filterSimpleQuery($request, $memos, 'category', 'category');
        $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);

        return view('app.mcp.memos', compact('memos', 'filters'));
    }

    public function erx_and_orders(Request $request)
    {
        $filters = $request->all();
        $erxAndOrders = Erx::query();
        $erxAndOrders = $erxAndOrders->where('hcp_pro_id', $this->performer->pro->id);
        $this->filterMultiQuery($request, $erxAndOrders, 'created_at', 'date_category', 'date_value_1', 'date_value_2');
        $this->filterSimpleQuery($request, $erxAndOrders, 'pro_declared_status', 'status');

        $erxAndOrders = $erxAndOrders->orderBy('created_at', 'DESC')->paginate(20);
        return view('app.mcp.erx_and_orders', compact('erxAndOrders', 'filters'));
    }

    public function reports(Request $request)
    {
        $filters = $request->all();
        $reports = IncomingReport::where('hcp_pro_id', $this->performer->pro->id);
        $this->filterMultiQuery($request, $reports, 'report_date', 'date_category', 'date_value_1', 'date_value_2');
        $status = $request->get('status');
        if($status){
            if($status == 'SIGNED') $reports = $reports->where('has_hcp_pro_signed', true);
            if($status == 'NOT_SIGNED') $reports = $reports->where('has_hcp_pro_signed', false);
        }

        $reports = $reports->orderBy('created_at', 'DESC')->paginate(20);
        return view('app.mcp.reports', compact('reports', 'filters'));
    }

    public function supply_orders(Request $request)
    {
        $filters = $request->all();
        $supplyOrders = SupplyOrder::select('supply_order.*')->where('supply_order.signed_by_pro_id', $this->performer->pro->id);
        $this->filterMultiQuery($request, $supplyOrders, 'created_at', 'date_category', 'date_value_1', 'date_value_2');
        $status = $request->get('status');
        if($status){
            if($status == 'CLEARED_FOR_SHIPMENT'){
                $supplyOrders = $supplyOrders->where('is_cleared_for_shipment', true);
            }elseif($status == 'NOT_CLEARED_FOR_SHIPMENT'){
                $supplyOrders = $supplyOrders->where('is_cleared_for_shipment', false);
            }elseif($status == 'CANCELLED'){
                $supplyOrders = $supplyOrders->where('is_cancelled', true);
            }else{
             $supplyOrders = $supplyOrders->join('shipment', 'shipment.id', '=', 'supply_order.shipment_id')->where('shipment.status', $status);
            }

        }
        $supplyOrders = $supplyOrders->orderBy('created_at', 'DESC')->paginate(20);
        return view('app.mcp.supply_orders', compact('supplyOrders', 'filters'));
    }

    public function client_messages(Request $request)
    {
        $filters = $request->all();

        $clientMessages = ClientSMS::select('client_sms.*')
        ->join('client', 'client.id', '=', 'client_sms.client_id')
        ->where('client.mcp_pro_id', $this->performer->pro->id);

        $this->filterMultiQuery($request, $clientMessages, 'client_sms.created_at', 'date_category', 'date_value_1', 'date_value_2');
        $this->filterSimpleQuery($request, $clientMessages, 'sms_status', 'sms_status');

        $clientMessages = $clientMessages->orderBy('client_sms.created_at', 'DESC');
        $clientMessages = $clientMessages->paginate(20);
        return view('app.mcp.client_messages', compact('clientMessages', 'filters'));
    }

    public function patients_accounts_invites(Request $request){
        $filters = $request->all();

        $accountInvites = AccountInvite::select('account_invite.*')
                            ->join('client', 'client.id', '=', 'account_invite.for_client_id');
        $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);

        $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
        $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');

        $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);

        return view('app.mcp.patients-accounts-invites', compact('accountInvites', 'filters'));
    }

    public function new_patients_awaiting_visit(Request $request){
        $data = [
            'records' => Client::where('mcp_pro_id', $this->performer->pro->id)
                ->where('has_mcp_done_onboarding_visit', '!=', 'YES')
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.new_patients_awaiting_visit', $data);
    }
    public function notes_pending_signature(Request $request){
        $data = [
            'records' => Note::where('hcp_pro_id', $this->performer->pro->id)
                ->where('is_cancelled', '<>', true)
                ->where('is_signed_by_hcp', '<>', true)
                ->where('is_core_note', false)
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.notes_pending_signature', $data);
    }

    public function notes_pending_summary_suggestion(Request $request){
        $pro = $this->performer->pro;
        $data = [
            'records' => $pro->get_notes_pending_summary_suggestion_as_mcp()
        ];
        return view('app.mcp.notes_pending_summary_suggestion', $data);
    }

    public function notes_rejected_summary_suggestion(Request $request){
        $pro = $this->performer->pro;
        $data = [
            'records' => $pro->get_notes_rejected_summary_suggestion_as_mcp()
        ];
        return view('app.mcp.notes_rejected_summary_suggestion', $data);
    }

    public function notes_pending_billing(Request $request){
        $data = [
            'records' => Note::where('hcp_pro_id', $this->performer->pro->id)
                ->where('is_cancelled', '<>', true)
                ->where('is_signed_by_hcp', true)
                ->where('is_billing_marked_done', '<>', true)
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.notes_pending_billing', $data);
    }
    public function bills_pending_signature(Request $request){
        $data = [
            'records' => Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) {
                $query->where('hcp_pro_id', $this->performer->pro->id)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
            })
                ->orWhere(function ($query) {
                    $query->where('cm_pro_id', $this->performer->pro->id)->where('is_signed_by_cm', false)->where('is_cancelled', false);
                })->orWhere(function ($query) {
                    $query->where('rme_pro_id', $this->performer->pro->id)->where('is_signed_by_rme', false)->where('is_cancelled', false);
                })->orWhere(function ($query) {
                    $query->where('rmm_pro_id', $this->performer->pro->id)->where('is_signed_by_rmm', false)->where('is_cancelled', false);
                })->orWhere(function ($query) {
                    $query->where('generic_pro_id', $this->performer->pro->id)->where('is_signed_by_generic_pro', false)->where('is_cancelled', false);
                })
                ->orderBy('created_at', 'DESC')
                ->get()
        ];
        return view('app.mcp.bills_pending_signature', $data);
    }
    public function reports_pending_signature(Request $request){
        $data = [
            'records' => IncomingReport::where('hcp_pro_id', $this->performer->pro->id)
                ->where('has_hcp_pro_signed', '<>', true)
                ->where('is_entry_error', '<>', true)
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.reports_pending_signature', $data);
    }
    public function patients_without_appointments(Request $request){
        $patients = $this->performer->pro->get_patients_without_appointment_query()->paginate(20);
        return view('app.mcp.patients_without_appointments', compact('patients'));
    }
    public function patients_overdue_for_visit(Request $request){
        $patients = $this->performer->pro->get_patients_overdue_for_visit_query()->paginate(20);
        return view('app.mcp.patients_overdue_for_visit', compact('patients'));
    }
    public function cancelled_appointments_pending_review(Request $request){
        $data = [];
        return view('app.mcp.cancelled_appointments_pending_review', $data);
    }
    public function cancelled_bills_pending_review(Request $request){
        $data = [
            'records' => Bill::where('hcp_pro_id', $this->performer->pro->id)
                ->where('bill_service_type', 'NOTE')
                ->where('is_cancelled', true)
                ->where('is_cancellation_acknowledged', '<>', true)
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.cancelled_bills_pending_review', $data);
    }
    public function cancelled_supply_orders_pending_review(Request $request){
        $data = [
            'records' => SupplyOrder::where('signed_by_pro_id', $this->performer->pro->id)
                ->where('is_cancelled', true)
                ->where('is_cancellation_acknowledged', '<>', true)
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.cancelled_supply_orders_pending_review', $data);
    }
    public function erx_and_orders_pending_signature(Request $request){
        $data = [
            'records' => Erx::where('hcp_pro_id', $this->performer->pro->id)
                ->where('pro_declared_status', '<>', 'CANCELLED')
                ->where('has_hcp_pro_signed', '<>', true)
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.erx_and_orders_pending_signature', $data);
    }
    public function supply_orders_pending_signature(Request $request){
        $data = [
            'records' => SupplyOrder::where('created_by_pro_id', $this->performer->pro->id)
                ->whereNull('signed_by_pro_id')
                ->where('is_cancelled', '<>', true)
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.supply_orders_pending_signature', $data);
    }
    public function supply_orders_awaiting_shipment(Request $request){
        $data = [
            'records' => SupplyOrder::where('created_by_pro_id', $this->performer->pro->id)
                ->where('is_signed_by_pro', true)
                ->where('is_cleared_for_shipment', true)
                ->whereNull('shipment_id')
                ->orderBy('created_at')
                ->get()
        ];
        return view('app.mcp.supply_orders_awaiting_shipment', $data);
    }
    public function unsigned_incoming_reports(Request $request){
        $data = [
            'records' => IncomingReport::where('hcp_pro_id', $this->performer->pro->id)
                ->whereRaw('(has_hcp_pro_signed IS NULL OR has_hcp_pro_signed = FALSE)')
                ->orderBy('created_at', 'desc')
                ->get()
        ];
        return view('app.mcp.unsigned_incoming_reports', $data);
    }
    public function patients_awaiting_rpm_interaction(Request $request) {
        $cmStartDate = date('Y-m-01');
        $query = "
SELECT
    client.uid as client_uid,
    care_month.uid as care_month_uid,
    (client.name_first || ' ' || client.name_last) as client_name,
    client.age_in_years,
    client.sex,
    care_month.start_date,
    care_month.number_of_days_with_remote_measurements
FROM
    client join care_month on client.id = care_month.client_id
WHERE
    care_month.start_date = '{$cmStartDate}'
    AND care_month.is_client_enrolled_in_rm
    AND care_month.has_mcp_interacted_with_client_about_rm IS NOT TRUE
    AND care_month.mcp_pro_id = {$this->performer->pro->id}
    AND (client.client_engagement_status_category IS NULL OR client.client_engagement_status_category != 'DUMMY')
    AND client.name_first NOT ILIKE '%test%'
    AND client.name_last NOT ILIKE '%test%'
ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST
        ";
        $data = [
            'records' => DB::select($query)
        ];
        return view('app.mcp.patients_awaiting_rpm_interaction', $data);
    }
    public function measurements_pending_stamping(Request $request){
        $data = [
            'records' => CareMonth::where('mcp_pro_id', $this->performer->pro->id)
                ->where('rm_num_measurements_not_stamped_by_mcp', '>', 0)
                ->whereNotNull('rm_num_measurements_not_stamped_by_mcp')
                ->orderBy('created_at', 'DESC')
                ->paginate(15)
        ];
        return view('app.mcp.measurements_pending_stamping', $data);
    }

    public function measurements_pending_stamping_in_care_month(Request $request) {
        $patient = Client::where('uid', $request->input('patientUid'))->first();
        $careMonth = CareMonth::where('uid', $request->input('careMonthUid'))->first();
        return view('app.mcp.measurements_pending_stamping_in_care_month', compact('patient', 'careMonth'));
    }

    public function measurements_mass_stamping(Request $request){
        $careMonthsWithMeasurementsPendingStamping = CareMonth::select('id')
            ->where('mcp_pro_id', $this->performer->pro->id)
            ->where('rm_num_measurements_not_stamped_by_mcp', '>', 0)
            ->whereNotNull('rm_num_measurements_not_stamped_by_mcp')
            ->orderBy('created_at', 'DESC')
            ->get()
            ->map(function($_x) {
                return $_x->id;
            })
            ->toArray();

        $measurementsPendingStamping = Measurement::whereIn('care_month_id', $careMonthsWithMeasurementsPendingStamping)
            ->orderBy('created_at', 'DESC')
            ->whereNotNull('ts')
            ->whereNotIn('label', ['SBP', 'DBP'])
            ->where('is_cellular_zero', '<>', true)
            ->where('is_active', true)
            ->where('has_been_stamped_by_mcp', false)
            ->whereNotNull('client_bdt_measurement_id')
            ->paginate(500);
        return view('app.mcp.measurements_mass_stamping', compact('measurementsPendingStamping'));
    }

}
