<?php

namespace App\Models;

use App\Models\Concerns\BelongsToCompany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class Leave extends Model
{
    use BelongsToCompany;

    protected $table = 'leaves';

    protected $fillable = [
        'company_id',
        'user_id',
        'leave_type_id',
        'start_date',
        'end_date',
        'total_days',
        'is_half_day',
        'half_leave',
        'reason',
        'remark',
        'withdrawal_reason',
        'is_paid',
        'status',
    ];

    protected $casts = [
        'start_date' => 'date:Y-m-d',
        'end_date' => 'date:Y-m-d',
        'total_days' => 'float',
        'is_half_day' => 'boolean',
        'is_paid' => 'boolean',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function leaveType(): BelongsTo
    {
        return $this->belongsTo(LeaveType::class, 'leave_type_id');
    }

    public function documents(): MorphMany
    {
        return $this->morphMany(Document::class, 'documentable');
    }

    /**
     * Approved leave that has not started yet (start date is strictly after today).
     */
    public function isWithdrawableBeforeStart(): bool
    {
        if ($this->status !== 'approved' || ! $this->start_date) {
            return false;
        }

        return $this->start_date->copy()->startOfDay()->greaterThan(now()->startOfDay());
    }

    public function isWithdrawalPending(): bool
    {
        return $this->status === 'withdrawal_pending';
    }

    /**
     * Statuses that still consume leave balance / block overlapping dates.
     *
     * @return list<string>
     */
    public static function activeStatuses(): array
    {
        return ['pending', 'approved', 'withdrawal_pending'];
    }

    /**
     * Statuses that still count as approved leave for attendance/payroll.
     *
     * @return list<string>
     */
    public static function approvedLikeStatuses(): array
    {
        return ['approved', 'withdrawal_pending'];
    }
}
