<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class JobExperience extends Model
{
    use HasFactory;
    protected $appends = ['total_compensation'];

    protected $fillable = [
        'user_id',
        'job_title',
        'company_name',
        'level',
        'work_status',
        'still_employed',
        'employment_month',
        'employment_year',
        'number_of_years_as_employee',
        'years_of_experience',
        'years_in_level',
        'location',
        'post_code',
        'city',
        'state',
        'country',
        'work_arrangement',
        'employment_type',
        'annual_base_salary',
        'bonus_commission',
        'overtime_pay',
        'equity',
        'currency',
        'benefits',
        'is_published',
        'published_at',
        'job_description',
        'industry',
        'company_size',
    ];

    protected $casts = [
        'still_employed' => 'boolean',
        'is_published' => 'boolean',
        'published_at' => 'datetime',
        'annual_base_salary' => 'decimal:2',
        'bonus_commission' => 'decimal:2',
        'overtime_pay' => 'decimal:2',
        'equity' => 'decimal:2',
        'number_of_years_as_employee' => 'int',
        'years_of_experience' => 'int',
        'years_in_level' => 'int',
    ];

    // Relationships
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
    

    // Scopes
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    public function scopeCurrent($query)
    {
        return $query->where('still_employed', true);
    }

    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    // Accessors
    public function getTotalCompensationAttribute(): float
    {
        return ($this->annual_base_salary ?? 0)
             + ($this->bonus_commission ?? 0)
             + ($this->overtime_pay ?? 0)
             + ($this->equity ?? 0);
    }

    public function getFormattedSalaryAttribute(): string
    {
        if (!$this->annual_base_salary) {
            return 'Not disclosed';
        }

        return number_format($this->annual_base_salary) . ' ' . $this->currency;
    }

    public function getBenefitsArrayAttribute(): array
    {
        if (empty($this->benefits)) {
            return [];
        }
        
        // Splits by comma and trims whitespace
        return array_map('trim', explode(',', $this->benefits));
    }

    public function markAsActive(): void
    {
        // Deactivate all other jobs for this user
        self::where('user_id', $this->user_id)
            ->where('id', '!=', $this->id)
            ->update(['still_employed' => false]);

        $this->update(['still_employed' => true]);
    }

    public function publish(): void
    {
        $this->update([
            'is_published' => true,
            'published_at' => now(),
        ]);
    }

    public function unpublish(): void
    {
        $this->update([
            'is_published' => false,
            'published_at' => null,
        ]);
    }

    // RateMyPay Relationships
    public function rateMyPays(): HasMany
    {
        return $this->hasMany(RateMyPay::class);
    }

    public function hasBeenShared(): bool
    {
        return $this->rateMyPays()->exists();
    }

    public function getLatestRateMyPay()
    {
        return $this->rateMyPays()->latest()->first();
    }
}
