<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class JobPosting extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'title',
        'slug',
        'department',
        'department_id',
        'employment_type',
        'location',
        'description',
        'requirements',
        'working_hours',
        'salary_range',
        'cover_image',
        'custom_application_form_path',
        'custom_application_form_name',
        'conditions_pdf_path',
        'conditions_pdf_name',
        'required_documents',
        'use_custom_form_settings',
        'job_form_settings',
        'sort_order',
        'is_featured',
        'status',
        'published_at',
        'closes_at',
        'created_by',
    ];

    protected $casts = [
        'published_at'             => 'datetime',
        'closes_at'                => 'datetime',
        'is_featured'              => 'boolean',
        'use_custom_form_settings' => 'boolean',
        'job_form_settings'        => 'array',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        // logAll() yerine logOnly() — description/requirements gibi büyük metin alanları
        // activity_log tablosunu şişirmesin diye loglanmıyor.
        return LogOptions::defaults()
            ->logOnly([
                'title', 'slug', 'status', 'published_at', 'closes_at',
                'department', 'employment_type', 'location',
                'created_by', 'is_featured', 'sort_order',
            ])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

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

    public function departmentRelation()
    {
        return $this->belongsTo(Department::class, 'department_id');
    }

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

    public function isOpen(): bool
    {
        if ($this->status !== 'published') {
            return false;
        }
        if ($this->closes_at && $this->closes_at->isPast()) {
            return false;
        }
        return true;
    }

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

        static::creating(function ($model) {
            if (empty($model->slug)) {
                $model->slug = static::generateUniqueSlug($model->title);
            }
        });
    }

    /**
     * Benzersiz slug üretir — aynı slug varsa sonuna -2, -3 ekler
     */
    public static function generateUniqueSlug(string $title, ?int $excludeId = null): string
    {
        $base = Str::slug($title);
        $slug = $base;
        $counter = 2;

        while (true) {
            $query = static::where('slug', $slug);
            if ($excludeId) {
                $query->where('id', '!=', $excludeId);
            }
            if (!$query->exists()) {
                break;
            }
            $slug = $base . '-' . $counter;
            $counter++;
        }

        return $slug;
    }

    public function scopePublished($query)
    {
        return $query->where('status', 'published')
            ->where(function ($q) {
                $q->whereNull('closes_at')
                    ->orWhere('closes_at', '>', now());
            });
    }
}