<?php

namespace App\Models;

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

/**
 * LeadershipHistory Model
 *
 * Represents a historical record of a leader's term in a position.
 * Created automatically when a leadership assignment ends.
 * Stores achievements and notes about the leader's tenure.
 *
 * @property int $id
 * @property int $organization_id
 * @property int $leadership_position_id
 * @property int $user_id
 * @property \Illuminate\Support\Carbon $term_start_date
 * @property \Illuminate\Support\Carbon $term_end_date
 * @property string $position_title
 * @property string|null $notes
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class LeadershipHistory extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'organization_id',
        'leadership_position_id',
        'user_id',
        'term_start_date',
        'term_end_date',
        'position_title',
        'notes',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'term_start_date' => 'date',
        'term_end_date' => 'date',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the organization for this history record.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function organization()
    {
        return $this->belongsTo(Organization::class);
    }

    /**
     * Get the leadership position for this history record.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function leadershipPosition()
    {
        return $this->belongsTo(LeadershipPosition::class);
    }

    /**
     * Get the user (leader) for this history record.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the achievements for this history record.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function achievements()
    {
        return $this->hasMany(LeadershipAchievement::class);
    }

    /**
     * Add an achievement to this history record.
     *
     * @param string $description
     * @param string $date
     * @return LeadershipAchievement
     */
    public function addAchievement(string $description, string $date): LeadershipAchievement
    {
        return $this->achievements()->create([
            'achievement_description' => $description,
            'achievement_date' => $date,
        ]);
    }

    /**
     * Get the duration of the term in days.
     *
     * @return int
     */
    public function getTermDurationInDays(): int
    {
        return $this->term_start_date->diffInDays($this->term_end_date);
    }

    /**
     * Get the duration of the term in a human-readable format.
     *
     * @return string
     */
    public function getTermDurationAttribute(): string
    {
        return $this->term_start_date->diffForHumans($this->term_end_date, true);
    }

    /**
     * Get the leader's name.
     *
     * @return string
     */
    public function getLeaderNameAttribute(): string
    {
        return $this->user?->name ?? 'Unknown';
    }

    /**
     * Scope to filter by position.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $positionId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByPosition($query, int $positionId)
    {
        return $query->where('leadership_position_id', $positionId);
    }

    /**
     * Scope to filter by user (leader).
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $userId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Scope to filter by organization.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $organizationId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeForOrganization($query, int $organizationId)
    {
        return $query->where('organization_id', $organizationId);
    }

    /**
     * Scope to filter by date range.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $startDate
     * @param string $endDate
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeDateRange($query, string $startDate, string $endDate)
    {
        return $query->whereBetween('term_start_date', [$startDate, $endDate])
            ->orWhereBetween('term_end_date', [$startDate, $endDate]);
    }

    /**
     * Scope to order by term start date.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $direction
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOrderByTermStart($query, string $direction = 'desc')
    {
        return $query->orderBy('term_start_date', $direction);
    }

    /**
     * Scope to search by leader name or position title.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $search
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch($query, string $search)
    {
        return $query->where(function ($q) use ($search) {
            $q->where('position_title', 'like', "%{$search}%")
                ->orWhereHas('user', function ($userQuery) use ($search) {
                    $userQuery->where('name', 'like', "%{$search}%");
                });
        });
    }
}
