<?php

namespace App\Modules\Admin;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Modules\Clients\Client;

class Contract extends Model
{
    protected $table = 'contracts';

    protected $fillable = [
        'client_id',
        'name',
        'description',
        'start_date',
        'end_date',
        'value',
        'status',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'value' => 'decimal:2',
    ];

    /**
     * Get the client that owns the contract.
     */
    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    /**
     * Get the clients associated with this contract.
     */
    public function clients(): HasMany
    {
        return $this->hasMany(Client::class, 'contract_id');
    }

    /**
     * Check if the contract is active.
     */
    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    /**
     * Check if the contract is expired.
     */
    public function isExpired(): bool
    {
        if (!$this->end_date) {
            return false;
        }
        
        return $this->end_date->isPast();
    }

    /**
     * Get the contract status with automatic expiration check.
     */
    public function getEffectiveStatusAttribute(): string
    {
        if ($this->status === 'active' && $this->isExpired()) {
            return 'expired';
        }
        
        return $this->status;
    }

    /**
     * Scope to get only active contracts.
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope to get only expired contracts.
     */
    public function scopeExpired($query)
    {
        return $query->where('status', 'expired')
            ->orWhere(function ($q) {
                $q->where('status', 'active')
                  ->where('end_date', '<', now());
            });
    }
} 