<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;

class NdrtOfficer extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'first_name',
        'middle_name',
        'surname',
        'id_type',
        'id_number',
        'gender',
        'date_of_birth',
        'physical_address',
        'location_type',
        'branch_id',
        'unit',
        'photo_path',
        'phone_1',
        'phone_2',
        'email',
        'emergency_contact_name',
        'emergency_contact_relation',
        'emergency_contact_phone_1',
        'emergency_contact_phone_2',
        'emergency_contact_address',
        'blood_group',
        'languages_spoken',
        'health_conditions',
        'has_disability',
        'disability_details',
        'education_level',
        'area_of_study',
        'work_experience',
        'competencies',
        'training_sector',
        'facilitator_rating',
        'available_for_deployment',
        'deployment_count',
        'deployment_months',
    ];

    protected $casts = [
        'date_of_birth' => 'date',
        'languages_spoken' => 'array',
        'work_experience' => 'array',
        'competencies' => 'array',
        'has_disability' => 'boolean',
        'available_for_deployment' => 'boolean',
        'facilitator_rating' => 'decimal:2',
        'deployment_months' => 'array',
    ];

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

    public function trainings()
    {
        return $this->belongsToMany(Training::class, 'ndrt_officer_training')
                    ->withPivot('attended')
                    ->withTimestamps();
    }

    /**
     * Trainings linked via JSON participants column on trainings table.
     */
    public function trainingsByParticipants()
    {
        return Training::whereJsonContains('participants', (string) $this->id)->get();
    }

    public function deployments()
    {
        return $this->hasMany(Deployment::class);
    }

    // Accessors
    public function getFullNameAttribute()
    {
        return trim("{$this->first_name} {$this->middle_name} {$this->surname}");
    }

    public function getAgeAttribute()
    {
        return Carbon::parse($this->date_of_birth)->age;
    }

    public function getActiveDeploymentsAttribute()
    {
        return $this->deployments()->where('status', 'Active')->count();
    }

    public function getCompletedDeploymentsAttribute()
    {
        return $this->deployments()->where('status', 'Completed')->count();
    }
}