<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Career extends Model
{
    protected $fillable = [
        'title',
        'slug',
        'description',
        'responsibilities',
        'requirements',
        'benefits',
        'location',
        'job_location',
        'department',
        'employment_type',
        'education',
        'contact_email',
        'contact_phone',
        'skills',
        'industry',
        'working_hours',
        'salary_range',
        'base_salary',
        'is_active',
        'date_posted',
        'valid_through',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'date_posted' => 'date',
        'valid_through' => 'date',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($career) {
            if (empty($career->slug)) {
                $career->slug = Str::slug($career->title);
            }
            if (empty($career->date_posted)) {
                $career->date_posted = now();
            }
        });

        static::updating(function ($career) {
            if ($career->isDirty('title') && empty($career->slug)) {
                $career->slug = Str::slug($career->title);
            }
        });
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true)
            ->where(function ($q) {
                $q->whereNull('valid_through')
                  ->orWhere('valid_through', '>=', now());
            });
    }

    public function applications(): HasMany
    {
        return $this->hasMany(JobApplication::class);
    }
}
