<?php

namespace App\Http\Controllers;

use App\Models\AccountInvite;
use App\Models\Appointment;
use App\Models\Bill;
use App\Models\Client;
use App\Models\ClientBDTDevice;
use App\Models\ClientMemo;
use App\Models\ClientProAccess;
use App\Models\ClientReviewRequest;
use App\Models\ClientSMS;
use App\Models\Erx;
use App\Models\IncomingReport;
use App\Models\Note;
use App\Models\SupplyOrder;
use Illuminate\Http\Request;
class RdController extends Controller
{

    public function dashboard(Request $request){
        $performer = $this->performer();
        $pro = $performer->pro;
        $performerProID = $performer->pro->id;

        $milliseconds = strtotime(date('Y-m-d')) . '000'; //required by the calendar
        return view('app.rd.dashboard', compact( 'milliseconds'));
    }

    public function patients(Request $request)
    {
        $filters = $request->all();
        $pro = $this->performer->pro;
        $patients = Client::where('rd_pro_id', $pro->id);

        $proAccessClientIDs = ClientProAccess::where('pro_id', $pro->id)->pluck('client_id')->toArray();
        $patients = $patients->orWhereIn('id', $proAccessClientIDs);


        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_completed_mcp_note_date', 'last_visit_category', 'last_visit_value_1', 'last_visit_value_2'); 
        $this->filterMultiQuery($request, $patients, 'next_mcp_appointment_date', 'next_appointment_category', 'next_appointment_value_1', 'next_appointment_value_2');

        switch($request->input('status')) {
            case 'ACTIVE':
                $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
                break;
            case 'AWAITING_VISIT':
                $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
                break;
            case 'INACTIVE':
                $patients->where('is_active', '<>', true);
                break;
        }
        $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(20);
        return view('app.rd.patients', compact('patients', 'filters'));
    }

    public function dashboardPatients(Request $request){
        $pro = $this->performer->pro;
        $patients = Client::where('rd_pro_id', $pro->id)->paginate(25);
        return view('app.rd.dashboard.patients', compact('patients'));
    }

    public function clientReviewRequests(Request $request){
        $hideTitle = $request->get('hideTitle');
        $performer = $this->performer();
        $pro = $performer->pro;
        $reviewRequests = ClientReviewRequest::where('pro_id', $pro->id)->where('is_active', true)->orderBy('created_at', 'DESC')->paginate(50);
        return view('app.rd.review-requests.list', compact('reviewRequests', 'hideTitle'));
    }

    public function patientsAwaitingMcpVisit(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->patientsAwaitingMcpVisitRecordsAsRd();
        return view('app.rd.dashboard.patients_awaiting_mcp_visit', compact('records'));
    }

    public function patientsWithoutAppointment(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->patientsWithoutAppointmentRecordsAsRd();
        return view('app.rd.dashboard.patients_without_appointment', compact('records'));
    }

    public function encountersPendingMyReview(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->encountersPendingMyReviewRecordsAsRd();
        return view('app.rd.dashboard.encounters_pending_my_review', compact('records'));
    }

    public function encountersInProgress(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->encountersInProgressRecordsAsRd();
        return view('app.rd.dashboard.encounters_in_progress', compact('records'));
    }

    public function appointmentsPendingConfirmation(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->appointmentsPendingConfirmationRecordsAsRd();
        return view('app.rd.dashboard.appointments_pending_confirmation', compact('records'));
    }

    public function cancelledAppointmentsPendingAck(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->cancelledAppointmentsPendingAckRecordsAsRd();
        return view('app.rd.dashboard.cancelled_appointments_pending_ack', compact('records'));
    }

    public function reportsPendingAck(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->reportsPendingAckRecordsAsRd();
        return view('app.rd.dashboard.reports_pending_ack', compact('records'));
    }

    public function supplyOrdersPendingMyAck(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->supplyOrdersPendingMyAckRecordsAsRd();
        return view('app.rd.dashboard.supply_orders_pending_my_ack', compact('records'));
    }

    public function supplyOrdersPendingHcpApproval(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->supplyOrdersPendingHcpApprovalRecordsAsRd();
        return view('app.rd.dashboard.supply_orders_pending_hcp_approval', compact('records'));
    }

    public function appointments(Request $request)
    {
        $pro = $this->performer->pro;
        $filters = $request->all();
        $appointments = Appointment::whereHas('client',function($qry)use($pro){
            return $qry->where('rd_pro_id', $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.rd.appointments', compact('appointments', 'filters'));
    }
    public function clientCcmRmStatus(Request $request){
        $pro = $this->performer()->pro;
        $filters = $request->all();
        $patients = Client::whereNull('shadow_pro_id')->where('rd_pro_id', $pro->id);
        
        if($pro->pro_type !== 'ADMIN') {
            if($pro->is_hcp){
               $patients = $patients->where('mcp_pro_id', $this->performer()->pro->id);
            }
            if($pro->is_considered_for_dna){
                $patients = $patients->where('default_na_pro_id', $this->performer()->pro->id);
             }


        }

        $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', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
        $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');

        switch($request->input('status')) {
            case 'ACTIVE':
                $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
                break;
            case 'AWAITING_VISIT':
                $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
                break;
            case 'INACTIVE':
                $patients->where('is_active', '<>', true);
                break;
        }


        if($request->input('is_eligible_for_cm')){
            $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
        }

        if($request->input('is_enrolled_in_cm')){
            $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
        }

        if($request->input('has_cm_setup_been_performed')){
            $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
        }

        if($request->input('is_eligible_for_rm')){
            $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
        }

        if($request->input('is_enrolled_in_rm')){  /*-- correct --*/
            $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm')); /*-- correct --*/
        }

        if($request->input('has_rm_setup_been_performed')){
            $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
        }

        $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
        return view('app.rd.client-ccm-rm-status', compact('patients', 'filters'));
    }
    public function rpmMatrix(Request $request)
    {
        $proID = $this->performer()->pro->id;
        $isAdmin = $this->performer()->pro->pro_type == 'ADMIN';
        $query = Client::whereNull('shadow_pro_id');
        $query->where('rd_pro_id', '=', $proID);
        $clients = $query->orderByRaw('most_recent_cellular_measurement_at desc nulls last')
            ->paginate(50);
        return view ('app.rd.rpm-matrix', compact('clients'));
    }

    public function notes(Request $request)
    {
        $pro = $this->performer->pro;
        $filters = $request->all();
        $notes = Note::query();
        $notes = $notes->whereHas('client', function($qry)use($pro){
            return $qry->where('rd_pro_id', $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.rd.notes', compact('notes','filters'));
    }

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

        $memos = ClientMemo::select('client_memo.*')
        ->join('client', 'client.id', '=', 'client_memo.client_id')
        ->where('client.rd_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.rd.memos', compact('memos', 'filters'));
    }

    public function bills(Request $request)
    {
        $pro = $this->performer->pro;
        $filters = $request->all();
        $bills = Bill::whereHas('client', function($qry)use($pro){
            return $qry->where('rd_pro_id', $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.rd.bills', compact('bills', 'filters'));
    }

    public function erxAndOrders(Request $request)
    {
        $pro = $this->performer->pro;
        $filters = $request->all();
        $erxAndOrders = Erx::query();
        $erxAndOrders = $erxAndOrders->whereHas('client', function($qry)use($pro){
            return $qry->where('rd_pro_id', $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.rd.erx_and_orders', compact('erxAndOrders', 'filters'));
    }

    public function reports(Request $request)
    {
        $pro = $this->performer->pro;
        $filters = $request->all();
        $reports = IncomingReport::whereHas('client',function($qry)use($pro){
            return $qry->where('rd_pro_id', $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.rd.reports', compact('reports', 'filters'));
    }

    public function supplyOrders(Request $request)
    {
        $pro = $this->performer->pro;
        $filters = $request->all();
        $supplyOrders = SupplyOrder::select('supply_order.*')->whereHas('client',function($qry)use($pro){
            return $qry->where('rd_pro_id', $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.rd.supply_orders', compact('supplyOrders', 'filters'));
    }

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

        $clientMessages = ClientSMS::select('client_sms.*')
        ->join('client', 'client.id', '=', 'client_sms.client_id')
        ->where('client.rd_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.rd.client_messages', compact('clientMessages', 'filters'));
    }

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

        $accountInvites = AccountInvite::select('account_invite.*')
                            ->join('client', 'client.id', '=', 'account_invite.for_client_id');
        $accountInvites = $accountInvites->where('client.rd_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.rd.patients-accounts-invites', compact('accountInvites', 'filters'));
    }

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

        $devices = ClientBDTDevice::select('client_bdt_device.*')
        ->join('client', 'client.id', '=', 'client_bdt_device.client_id')
        ->where('client.rd_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.rd.clients_bdt_devices', compact('devices', 'filters'));
    }
}
