<?php

namespace App\Http\Controllers;

use App\Models\Appointment;
use App\Models\BDTDevice;
use App\Models\Bill;
use App\Models\CareMonth;
use App\Models\Client;
use App\Models\ClientBDTDevice;
use App\Models\ClientInfoLine;
use App\Models\ClientProAccess;
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\Note;
use App\Models\NoteTemplate;
use App\Models\Pro;
use App\Models\Product;
use App\Models\ProProAccess;
use App\Models\ProTeam;
use App\Models\ProTransaction;
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 Illuminate\Support\Facades\Http;
use PDF;

class DnaController extends Controller
{

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

        //Also include the ones given access to:
        $proAccessClientIDs = ClientProAccess::where('pro_id', $this->performer->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.dna.patients', compact('patients', 'filters'));
    }

    public function encounters(Request $request)
    {
        $filters = $request->all();
        $notes = Note::query();
        $notes = $notes->where('ally_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.dna.encounters', compact('notes', 'filters'));
    }

    public function notes(Request $request)
    {
        $data = [];
        return view('app.dna.notes', $data);
    }

    public function appointments(Request $request)
    {
        $filters = $request->all();
        $appointments = Appointment::select('appointment.*')
                        ->join('client', 'client.id', '=', 'appointment.client_id')
                        ->where('client.default_na_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.dna.appointments', compact('appointments', 'filters'));
    }

    public function careMonths(Request $request){
        $filters = $request->all();
        $careMonths = CareMonth::select('care_month.*')
                        ->join('client', 'client.id', '=', 'care_month.client_id')
                        ->where('client.default_na_pro_id', $this->performer->pro->id);
        $this->filterMultiQuery($request, $careMonths, 'raw_date', 'date_category', 'date_value_1', 'date_value_2');
        $this->filterSimpleQuery($request, $careMonths, 'status', 'status');
        $careMonths = $careMonths->orderBy('created_at', 'DESC')->paginate(20);
        return view('app.dna.care-months', compact('careMonths', 'filters'));
    }

    public function financialTransactions(Request $request){
        $filters = $request->all();
        $financialTransactions = ProTransaction::select('pro_transaction.*')
                                ->join('bill', 'bill.id', '=', 'pro_transaction.bill_id')
                                ->where('bill.generic_pro_id', $this->performer->pro->id);
        $financialTransactions = $financialTransactions->orderBy('created_at', 'DESC')->paginate(20);
        return view('app.dna.financial-transactions', compact('financialTransactions', 'filters'));
    }
    public function myBills(Request $request){
        $performerProID = $this->performer->pro->id;
        $filters = $request->all();
        $bills = Bill::where(function($q) use ($performerProID){
            return $q->where('na_pro_id', '=', $performerProID )->orWhere('generic_pro_id', '=', $performerProID);
        });
        $this->filterMultiQuery($request, $bills, 'effective_date', 'date_category', 'date_value_1', 'date_value_2');
        $this->filterMultiQuery($request, $bills, 'na_expected_payment_amount', 'amount_category', 'amount_value_1', 'amount_value_2');
        
        $status = $request->get('status');
        if($status){
            if($status === 'VERIFIED') $bills = $bills->where('is_verified', true);
            if($status === 'ACTIVE') $bills = $bills->where('is_cancelled', false);
            if($status === 'CANCELLED') $bills = $bills->where('is_cancelled', true);
            if($status === 'SUBMITTED') $bills = $bills->where('is_submitted', true);
        }
        
        $bills = $bills->orderBy('effective_date', 'DESC')->paginate(20);
        return view('app.dna.my-bills', compact('bills', 'filters'));
    }

    public function myClinicalTeams(Request $request){
        $filters = $request->all();
        $teams = ProTeam::where('assistant_pro_id', $this->performer->pro->id);        
        $teams = $teams->orderBy('created_at', 'DESC')->paginate(20);
        return view('app.dna.my-clinical-teams', compact('teams', 'filters'));
    }

    public function bills(Request $request)
    {
        $data = [];
        return view('app.dna.bills', $data);
    }

    public function erx_and_orders(Request $request)
    {
        $data = [];
        return view('app.dna.erx_and_orders', $data);
    }

    public function reports(Request $request)
    {
        $data = [];
        return view('app.dna.reports', $data);
    }

    public function supply_orders(Request $request)
    {
        $data = [];
        return view('app.dna.supply_orders', $data);
    }

    public function new_patients_awaiting_visit(Request $request){
        $data = [];
        return view('app.dna.new_patients_awaiting_visit', $data);
    }
    public function notes_pending_signature(Request $request){
        $data = [];
        return view('app.dna.notes_pending_signature', $data);
    }
    public function notes_pending_billing(Request $request){
        $data = [];
        return view('app.dna.notes_pending_billing', $data);
    }
    public function reports_pending_signature(Request $request){
        $data = [];
        return view('app.dna.reports_pending_signature', $data);
    }
    public function patients_without_appointments(Request $request){
        $data = [];
        return view('app.dna.patients_without_appointments', $data);
    }
    public function patients_overdue_for_visit(Request $request){
        $data = [];
        return view('app.dna.patients_overdue_for_visit', $data);
    }
    public function cancelled_appointments_pending_review(Request $request){
        $data = [];
        return view('app.dna.cancelled_appointments_pending_review', $data);
    }
    public function cancelled_bills_pending_review(Request $request){
        $data = [];
        return view('app.dna.cancelled_bills_pending_review', $data);
    }
    public function cancelled_supply_orders_pending_review(Request $request){
        $data = [];
        return view('app.dna.cancelled_supply_orders_pending_review', $data);
    }
    public function erx_and_orders_pending_signature(Request $request){
        $data = [];
        return view('app.dna.erx_and_orders_pending_signature', $data);
    }
    public function supply_orders_pending_signature(Request $request){
        $data = [];
        return view('app.dna.supply_orders_pending_signature', $data);
    }

    //From the new spec 
    public function myPatients(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->patientsRecordsAsDna();
        return view('app.dna.dashboard.patients', compact('records'));
    }
    
    public function patientsAwaitingMcpVisit(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->patientsAwaitingMcpVisitRecordsAsDna();
        return view('app.dna.dashboard.patients_awaiting_mcp_visit', compact('records'));
    }
    
    public function patientsWithoutAppointment(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->patientsWithoutAppointmentRecordsAsDna();
        return view('app.dna.dashboard.patients_without_appointment', compact('records'));
    }
    
    public function encountersPendingMyReview(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->encountersPendingMyReviewRecordsAsDna();
        return view('app.dna.dashboard.encounters_pending_my_review', compact('records'));
    }
    
    public function encountersInProgress(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->encountersInProgressRecordsAsDna();
        return view('app.dna.dashboard.encounters_in_progress', compact('records'));
    }
    
    public function appointmentsPendingConfirmation(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->appointmentsPendingConfirmationRecordsAsDna();
        return view('app.dna.dashboard.appointments_pending_confirmation', compact('records'));
    }
    
    public function cancelledAppointmentsPendingAck(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->cancelledAppointmentsPendingAckRecordsAsDna();
        return view('app.dna.dashboard.cancelled_appointments_pending_ack', compact('records'));
    }
    
    public function reportsPendingAck(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->reportsPendingAckRecordsAsDna();
        return view('app.dna.dashboard.reports_pending_ack', compact('records'));
    }
    
    public function supplyOrdersPendingMyAck(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->supplyOrdersPendingMyAckRecordsAsDna();
        return view('app.dna.dashboard.supply_orders_pending_my_ack', compact('records'));
    }
    
    public function supplyOrdersPendingHcpApproval(Request $request){
        $pro = $this->performer->pro; 
        $records = $pro->supplyOrdersPendingHcpApprovalRecordsAsDna();
        return view('app.dna.dashboard.supply_orders_pending_hcp_approval', compact('records'));
    }

    public function teamDashboard(ProTeam $team){
        $slug = $team->slug ?? $team->uid;
        $url = config('app.stagfe6_url') . '/flyers/json-list?slug=' . $slug;

        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );        
        $response = @file_get_contents($url, false, stream_context_create($arrContextOptions));
        $response = @json_decode($response);
        $flyerTemplates = [];
        if(isset($response->data)){
            $flyerTemplates = $response->data;
        }
        return view('app.dna.teams.dashboard', compact('team','flyerTemplates'));
    }
    

}
