<?php

namespace App\Models\Construction;

use App\Models\Members\User;
use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 계약 모델
 *
 * @property int $id
 * @property int $tenant_id
 * @property string $contract_code
 * @property string $project_name
 * @property int|null $partner_id
 * @property string|null $partner_name
 * @property int|null $contract_manager_id
 * @property string|null $contract_manager_name
 * @property int|null $construction_pm_id
 * @property string|null $construction_pm_name
 * @property int $total_locations
 * @property float $contract_amount
 * @property string|null $contract_start_date
 * @property string|null $contract_end_date
 * @property string $status
 * @property string $stage
 * @property int|null $bidding_id
 * @property string|null $bidding_code
 * @property string|null $remarks
 * @property bool $is_active
 * @property int|null $created_by
 * @property int|null $updated_by
 * @property int|null $deleted_by
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property \Illuminate\Support\Carbon|null $deleted_at
 */
class Contract extends Model
{
    use Auditable, BelongsToTenant, ModelTrait, SoftDeletes;

    protected $table = 'contracts';

    // 상태 상수
    public const STATUS_PENDING = 'pending';

    public const STATUS_COMPLETED = 'completed';

    // 단계 상수
    public const STAGE_ESTIMATE_SELECTED = 'estimate_selected';

    public const STAGE_ESTIMATE_PROGRESS = 'estimate_progress';

    public const STAGE_DELIVERY = 'delivery';

    public const STAGE_INSTALLATION = 'installation';

    public const STAGE_INSPECTION = 'inspection';

    public const STAGE_OTHER = 'other';

    protected $fillable = [
        'tenant_id',
        'contract_code',
        'project_name',
        'partner_id',
        'partner_name',
        'contract_manager_id',
        'contract_manager_name',
        'construction_pm_id',
        'construction_pm_name',
        'total_locations',
        'contract_amount',
        'contract_start_date',
        'contract_end_date',
        'status',
        'stage',
        'bidding_id',
        'bidding_code',
        'remarks',
        'is_active',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $casts = [
        'total_locations' => 'integer',
        'contract_amount' => 'decimal:2',
        'contract_start_date' => 'date:Y-m-d',
        'contract_end_date' => 'date:Y-m-d',
        'is_active' => 'boolean',
    ];

    protected $attributes = [
        'is_active' => true,
        'status' => self::STATUS_PENDING,
        'stage' => self::STAGE_ESTIMATE_SELECTED,
        'total_locations' => 0,
        'contract_amount' => 0,
    ];

    // =========================================================================
    // 관계 정의
    // =========================================================================

    /**
     * 계약담당자
     */
    public function contractManager(): BelongsTo
    {
        return $this->belongsTo(User::class, 'contract_manager_id');
    }

    /**
     * 공사PM
     */
    public function constructionPm(): BelongsTo
    {
        return $this->belongsTo(User::class, 'construction_pm_id');
    }

    /**
     * 생성자
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 수정자
     */
    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * 인수인계 보고서
     */
    public function handoverReport(): HasOne
    {
        return $this->hasOne(HandoverReport::class, 'contract_id');
    }

    // =========================================================================
    // 스코프
    // =========================================================================

    /**
     * 상태별 필터
     */
    public function scopeStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 단계별 필터
     */
    public function scopeStage($query, string $stage)
    {
        return $query->where('stage', $stage);
    }

    /**
     * 거래처별 필터
     */
    public function scopePartner($query, int $partnerId)
    {
        return $query->where('partner_id', $partnerId);
    }

    // =========================================================================
    // 헬퍼 메서드
    // =========================================================================

    /**
     * 상태 라벨 반환
     */
    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            self::STATUS_PENDING => '계약대기',
            self::STATUS_COMPLETED => '계약완료',
            default => $this->status,
        };
    }

    /**
     * 단계 라벨 반환
     */
    public function getStageLabelAttribute(): string
    {
        return match ($this->stage) {
            self::STAGE_ESTIMATE_SELECTED => '견적선정',
            self::STAGE_ESTIMATE_PROGRESS => '견적진행',
            self::STAGE_DELIVERY => '납품',
            self::STAGE_INSTALLATION => '설치중',
            self::STAGE_INSPECTION => '검수',
            self::STAGE_OTHER => '기타',
            default => $this->stage,
        };
    }

    /**
     * 진행중 여부
     */
    public function isPending(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    /**
     * 완료 여부
     */
    public function isCompleted(): bool
    {
        return $this->status === self::STATUS_COMPLETED;
    }
}
