<?php

namespace App\Models;

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

class BabysitterSkill extends Model
{
    use HasFactory;

    protected $primaryKey = 'skill_id';

    protected $fillable = [
        'babysitter_id',
        'skill_type',
        'skill_name',
        'skill_level',
        'certificate_url',
        'issuing_organization',
        'issue_date',
        'expiry_date',
        'is_verified'
    ];

    protected $casts = [
        'issue_date' => 'date',
        'expiry_date' => 'date',
        'is_verified' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Get the babysitter profile associated with the skill.
     */
    public function babysitter()
    {
        return $this->belongsTo(BabysitterProfile::class, 'babysitter_id', 'profile_id');
    }

    /**
     * Scope a query to only include verified skills.
     */
    public function scopeVerified($query)
    {
        return $query->where('is_verified', true);
    }

    /**
     * Scope a query to only include skills of specific type.
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('skill_type', $type);
    }

    /**
     * Scope a query to only include certifications.
     */
    public function scopeCertifications($query)
    {
        return $query->where('skill_type', 'certification');
    }

    /**
     * Scope a query to only include languages.
     */
    public function scopeLanguages($query)
    {
        return $query->where('skill_type', 'language');
    }

    /**
     * Check if skill is a certification.
     */
    public function isCertification(): bool
    {
        return $this->skill_type === 'certification';
    }

    /**
     * Check if skill is a language.
     */
    public function isLanguage(): bool
    {
        return $this->skill_type === 'language';
    }

    /**
     * Check if certification is expired.
     */
    public function isExpired(): bool
    {
        if (!$this->expiry_date || !$this->isCertification()) {
            return false;
        }

        return $this->expiry_date->isPast();
    }

    /**
     * Mark skill as verified.
     */
    public function markAsVerified()
    {
        $this->update(['is_verified' => true]);
    }

    /**
     * Mark skill as unverified.
     */
    public function markAsUnverified()
    {
        $this->update(['is_verified' => false]);
    }

    /**
     * Get the public URL for certificate
     */
    public function getCertificateUrlAttribute($value)
    {
        if (!$value) {
            return null;
        }

        if (str_starts_with($value, 'http')) {
            return $value;
        }

        return url('storage/' . $value);
    }
}
