<?php

namespace App\Models;

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

class Worker extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'email',
        'phone',
        'language',
        'password',
        'nationality',
        'country',
        'city',
        'area',
        'preferred_location',
        'live_in_out',
        'age',
        'gender',
        'salary',
        'availability',
        'experience',
        'religion',
        'bio',
        'category_id',
        'verified',
        'status',
        'api_token',
        'in_country',
        'visa_status',
        'preferred_job_type',
    ];

    protected $hidden = [
        'password',
        'api_token', // Hide from public serialization, returned only during auth endpoints specifically
    ];

    protected $casts = [
        'verified' => 'boolean',
        'in_country' => 'boolean',
        'salary' => 'decimal:2',
        'password' => 'hashed',
    ];

    protected $appends = [
        'passport_status',
        'visa_status',
        'emirates_id_status',
    ];

    public function getPassportStatusAttribute()
    {
        $passport = $this->documents->where('type', 'passport')->first();
        if (!$passport) {
            return 'Passport Pending';
        }
        return $this->verified ? 'Passport Verified' : 'Passport Pending';
    }

    public function getVisaStatusAttribute()
    {
        if ($this->attributes['visa_status'] ?? null) {
            return $this->attributes['visa_status'];
        }
        $visa = $this->documents->where('type', 'visa')->first();
        if (!$visa) {
            return 'Visa Pending';
        }
        if ($visa->expiry_date && \Carbon\Carbon::parse($visa->expiry_date)->isPast()) {
            return 'Cancelled Visa';
        }
        return 'Residence Visa';
    }

    public function getEmiratesIdStatusAttribute()
    {
        return $this->passport_status;
    }

    public function category()
    {
        return $this->belongsTo(WorkerCategory::class, 'category_id');
    }

    public function skills()
    {
        return $this->belongsToMany(Skill::class, 'worker_skills');
    }

    public function documents()
    {
        return $this->hasMany(WorkerDocument::class);
    }

    // Relationship for job offers received
    public function offers()
    {
        return $this->hasMany(JobOffer::class, 'worker_id');
    }

    public function reviews()
    {
        return $this->hasMany(Review::class);
    }

    public function profileViews()
    {
        return $this->hasMany(ProfileView::class);
    }
}
