<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Helpers\BranchHelper;

class ProbationCase extends Model
{
    protected $table = 'probation_cases';

    protected $fillable = [
        'branch_id',
        'prisoner_id',
        'serial_number',
        'case_type',
        'referral_source',
        'referral_court_name',
        'court_case_number',
        'referral_report_types',
        'national_id',
        'passport_no',
        'language_spoken',
        'is_child',
        'is_violent_extremist',
        'is_suspected_violent_extremist',
        'is_child_sexual_offence',
        'is_special_needs',
        'assigned_officer_id',
        'status',
        'intensity',
        'opened_at',
        'closed_at',
        'created_by',
    ];

    protected $casts = [
        'is_child' => 'boolean',
        'is_violent_extremist' => 'boolean',
        'is_suspected_violent_extremist' => 'boolean',
        'is_child_sexual_offence' => 'boolean',
        'is_special_needs' => 'boolean',
        'opened_at' => 'date',
        'closed_at' => 'date',
    ];

    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

    public function prisoner()
    {
        return $this->belongsTo(Prisoner::class);
    }

    public function officer()
    {
        return $this->belongsTo(User::class, 'assigned_officer_id');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function allocations()
    {
        return $this->hasMany(CaseAllocation::class, 'case_id');
    }

    public function socialInquiry()
    {
        return $this->hasOne(SocialInquiry::class, 'case_id');
    }

    public function assessments()
    {
        return $this->hasMany(NeedsAssessment::class, 'case_id');
    }

    public function conferences()
    {
        return $this->hasMany(CaseConference::class, 'case_id');
    }

    public function reports()
    {
        return $this->hasMany(CaseReport::class, 'case_id');
    }

    public function courtOutcomes()
    {
        return $this->hasMany(CourtOutcome::class, 'case_id');
    }

    public function supervisionOrders()
    {
        return $this->hasMany(SupervisionOrder::class, 'case_id');
    }

    public function breaches()
    {
        return $this->hasMany(SupervisionBreach::class, 'case_id');
    }

    public function interventions()
    {
        return $this->hasMany(CaseIntervention::class, 'case_id');
    }

    public function empowerments()
    {
        return $this->hasMany(Empowerment::class, 'case_id');
    }

    public function completion()
    {
        return $this->hasOne(CaseCompletion::class, 'case_id');
    }

    public function documents()
    {
        return $this->hasMany(CaseDocument::class, 'case_id');
    }

    public function cso()
    {
        return $this->hasOne(CommunityServiceOrder::class, 'case_id');
    }

    public function getReferralReportTypesArrayAttribute()
    {
        return $this->referral_report_types
            ? explode(',', $this->referral_report_types)
            : [];
    }

    public function scopeForCurrentBranch($query)
    {
        $branchId = BranchHelper::getCurrentBranchId();

        if ($branchId && !BranchHelper::isSuperAdmin()) {
            return $query->where('branch_id', $branchId);
        }

        return $query;
    }

    public function scopeType($query, $type)
    {
        return $query->where('case_type', $type);
    }

    public function scopeStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    public function getStatusBadgeClass()
    {
        return match ($this->status) {
            'completed', 'closed'        => 'bg-success',
            'breached'                   => 'bg-danger',
            'under_supervision'          => 'bg-primary',
            'awaiting_court', 'reported' => 'bg-info',
            'transferred', 'delegated'   => 'bg-secondary',
            default                      => 'bg-warning',
        };
    }

    public static function generateSerial($caseType)
    {
        $prefix = [
            'social_inquiry'    => 'SI',
            'probation_order'   => 'PB',
            'community_service' => 'CSO',
            'aftercare_borstal' => 'AC',
            'power_of_mercy'    => 'POM',
            'special_category'  => 'SC',
            'adr'               => 'ADR',
            'probation_hostel'  => 'PH',
            'halfway_house'     => 'HW',
        ][$caseType] ?? 'CASE';

        $seq = self::where('case_type', $caseType)
            ->whereYear('created_at', now()->year)
            ->count() + 1;

        return sprintf('%s/%d/%06d', $prefix, now()->year, $seq);
    }
}