<?php

namespace App\Models;

# use Illuminate\Database\Eloquent\Model;

class Note extends Model
{
    protected $table = "note";

    public function client()
    {
        return $this->hasOne(Client::class, 'id', 'client_id');
    }

    public function hcpPro()
    {
        return $this->hasOne(Pro::class, 'id', 'hcp_pro_id');
    }

    public function hcpCompanyPro()
    {
        return $this->hasOne(CompanyPro::class, 'id', 'hcp_company_pro_id');
    }

    public function noteTemplate()
    {
        return $this->hasOne(NoteTemplate::class, 'id', 'note_template_id');
    }

    public function createdSession()
    {
        return $this->hasOne(AppSession::class, 'id', 'created_by_session_id');
    }

    public function allyPro()
    {
        return $this->hasOne(Pro::class, 'id', 'ally_pro_id');
    }

    public function followUpAppointment()
    {
        return $this->hasOne(Appointment::class, 'id', 'follow_up_appointment_id');
    }

    public function cmSetupClaim()
    {
        return $this->hasOne(Claim::class, 'id', 'cm_setup_claim_id')
            ->where('status', '<>', 'CANCELLED');
    }

    public function naGenericBill()
    {
        return $this->hasOne(Bill::class, 'id', 'na_generic_bill_id')->where('is_cancelled', false)->where('is_cancelled_by_administrator', false);
    }

    // Signed/Billed/Verified/Processed/Cancelled
    public function overallStatus()
    {
        $status = 'New';
        if ($this->is_cancelled) $status = 'Cancelled';
        else {
            if ($this->is_billing_marked_done) $status = 'Billed';
            else if ($this->is_signed_by_hcp) $status = 'Signed';
        }
        return $status;
    }

    public function bills()
    {
        return $this->hasMany(Bill::class, 'note_id', 'id')
            ->where('bill_service_type', '<>', 'GENERIC')
            ->orderBy('id', 'asc');
    }

    public function addendums()
    {
        return $this->hasMany(NoteAddendum::class, 'note_id', 'id')->where('is_removed', false);
    }

    public function sections()
    {
        return $this->hasMany(Section::class, 'note_id', 'id')
            ->where('is_active', true)
            ->orderBy('position_index', 'asc');
    }

    public function segments()
    {
        return $this->hasMany(Segment::class, 'note_id', 'id')
            ->where('id', '!=', $this->core_segment_id) // dont include core-segment
            //->where('is_active', true)
            ->orderBy('position_index', 'asc');
    }

    public function segmentsLeft()
    {
        return $this->hasMany(Segment::class, 'note_id', 'id')
            ->whereRaw("(left_or_right IS NULL OR left_or_right = 'LEFT')")
            ->where('id', '!=', $this->core_segment_id) // dont include core-segment
            //->where('is_active', true)
            ->orderBy('position_index', 'asc');
    }

    public function segmentsRight()
    {
        return $this->hasMany(Segment::class, 'note_id', 'id')
            ->where('left_or_right', 'RIGHT')
            ->where('id', '!=', $this->core_segment_id) // dont include core-segment
            //->where('is_active', true)
            ->orderBy('position_index', 'asc');
    }

    public function coreSegment()
    {
        return $this->hasOne(Segment::class, 'id', 'core_segment_id');
    }

    public function getSegmentByInternalName($_name) {
        $segmentTemplate = SegmentTemplate::where('internal_name', $_name)->first();
        if(!!$segmentTemplate) {
            return Segment::where('note_id', $this->id)
                ->where('id', '!=', $this->core_segment_id) // dont include core-segment
                ->where('segment_template_id', $segmentTemplate->id)
                ->first();
        }
        return null;
    }

    public function reasons()
    {
        $reasons = [];
        for ($i = 1; $i <= 4; $i++) {
            if($this->{'note_reason_icd' . $i}) {
                $reason = new \stdClass();
                $reason->code = $this->{'note_reason_icd' . $i};
                $reason->description = $this->{'note_reason_icd' . $i . 'description'};
                $reasons[] = $reason;
            }
        }
        return $reasons;
    }

    public function reasonsLog() {
        return $this->hasMany(NoteReasons::class, 'note_id', 'id')->orderBy('created_at', 'DESC');
    }

    public function claims()
    {
        return $this->hasMany(Claim::class, 'note_id', 'id')->orderBy('created_at', 'DESC');
    }

    public function receivedPayments()
    {
        return $this->hasMany(ReceivedPayment::class, 'note_id', 'id')->orderBy('created_at', 'DESC');
    }

    public function summary()
    {
        $parts = [];
        foreach ($this->sections as $section) {
            $parts[] = $section->summary_html;
        }
        $parts = array_map(function($_part) {
             return '<div class="note-section-summary">' . $_part . '</div>';
        }, $parts);
        return implode("", $parts);
    }

    public function hcpCompany()
    {
        return $this->hasOne(Company::class, 'id', 'hcp_company_id');
    }

    public function hcpCompanyProPayer()
    {
        return $this->hasOne(CompanyProPayer::class, 'id', 'hcp_company_pro_payer_id');
    }

    public function hcpCompanyLocation()
    {
        return $this->hasOne(CompanyLocation::class, 'id', 'hcp_company_location_id');
    }

    public function flaggedForSupervisingPhysicianReviewBySession(){
        return $this->hasOne(AppSession::class, 'id', 'flagged_for_supervising_physician_review_by_session_id');
    }
    public function stampedBySupervisingPhysicianBySession(){
        return $this->hasOne(AppSession::class, 'id', 'stamped_by_by_supervising_physician_by_session_id');
    }
    

    public function currentNotePickupForProcessing() {
        return $this->hasOne(NotePickupForProcessing::class, 'id', 'current_note_pickup_for_processing_id');
    }

    public function visitTemplate()
    {
        return $this->hasOne(VisitTemplate::class, 'id', 'visit_template_id');
    }

    public function hasTreatmentServicesBillByHCP()
    {
        $bills = Bill::where('note_id', $this->id)
            ->where('bill_service_type', '<>', 'GENERIC')
            ->where('code', 'Treatment Services')
            ->where('is_cancelled', false)
            ->count();
        return !!$bills;
    }

    public function segmentsWithPendingSummarySuggestion() {
        return $this->hasMany(Segment::class, 'note_id', 'id')
            ->where('id', '!=', $this->core_segment_id) // dont include core-segment
            ->where('is_active', true)
            ->whereHas('proposedSegmentSummarySuggestion', function($sugQuery) {
                return $sugQuery->where('status', '=', 'PENDING');
            })
            ->orderBy('position_index', 'asc');
    }

    public function hasUnacknowledgedCancelledBillsByPro(Pro $pro) {
        return Bill::where('note_id', $this->id)
            ->where('hcp_pro_id', $pro->id)
            ->where('bill_service_type', '<>', 'GENERIC')
            ->where('is_cancelled', true)
            ->where('is_cancelled_by_administrator', true)
            ->where('is_cancellation_acknowledged', false)
            ->count();
    }

    public function hasClaims() {
        return Claim::where('note_id', $this->id)
            ->where('status', '!=', 'CANCELLED')
            ->count();
    }

    public function isProPhysicianSupervisor($proID){
        $companyProIds = CompanyPro::where('pro_id', $proID)->pluck('id')->toArray();
        $noteCompanyProId = $this->hcpCompanyPro->supervising_physician_company_pro_id;
        if(!$noteCompanyProId) return false;
        return in_array($noteCompanyProId, $companyProIds);
    }

    public function cmSetupManagerSignatureStatusUpdatedBySession(){
        return $this->hasOne(AppSession::class, 'id', 'cm_setup_manager_signature_status_updated_by_session_id');
    }
}
