<?php

namespace App\Models\Sale;

use App\Models\Agency\Agency;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class SaleActivity extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'sale_activities';

    protected $fillable = [
        'agency_id',
        'sale_id',
        'reference_no',
        'activity_type',
        'subject',
        'description',
        'location',
        'meeting_link',
        'direction',
        'contact_method',
        'duration_minutes',
        'outcome',
        'activity_date',
        'scheduled_date',
        'completed_date',
        'due_date',
        'assigned_to',
        'performed_by',
        'status',
        'priority',
        'is_important',
        'is_pinned',
        'is_private',
        'requires_follow_up',
        'follow_up_date',
        'result',
        'action_taken',
        'next_steps',
        'metadata',
        'attachments',
        'tags',
    ];

    protected function casts(): array
    {
        return [
            // Enum
            'activity_type' => \App\Enums\ActivityType::class,

            // Dates
            'activity_date' => 'datetime',
            'scheduled_date' => 'datetime',
            'completed_date' => 'datetime',
            'due_date' => 'datetime',
            'follow_up_date' => 'date',

            // JSON
            'metadata' => 'array',
            'attachments' => 'array',
            'tags' => 'array',

            // Booleans
            'is_important' => 'boolean',
            'is_pinned' => 'boolean',
            'is_private' => 'boolean',
            'requires_follow_up' => 'boolean',
        ];
    }

    // ─── RELATIONSHIPS ───────────────────────────────────────────────────────

    public function agency()
    {
        return $this->belongsTo(Agency::class);
    }

    public function sale()
    {
        return $this->belongsTo(Sale::class, 'sale_id');
    }

    public function assignedTo()
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

    public function performer()
    {
        return $this->belongsTo(User::class, 'performed_by');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    // ─── SCOPES ──────────────────────────────────────────────────────────────

    public function scopeByAgency($query, int $agencyId)
    {
        return $query->where('agency_id', $agencyId);
    }

    public function scopeBySale($query, int $saleId)
    {
        return $query->where('sale_id', $saleId);
    }

    public function scopeByType($query, string $type)
    {
        return $query->where('activity_type', $type);
    }

    public function scopeByStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

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

    public function scopeUnpinned($query)
    {
        return $query->where('is_pinned', false);
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeInProgress($query)
    {
        return $query->where('status', 'in_progress');
    }

    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }

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

    // ─── HELPER METHODS ──────────────────────────────────────────────────────

    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    public function isCompleted(): bool
    {
        return $this->status === 'completed';
    }

    public function isOverdue(): bool
    {
        return $this->due_date && $this->due_date->isPast() && !$this->isCompleted();
    }

    public function getActivityTypeLabelAttribute(): string
    {
        return $this->activity_type instanceof \App\Enums\ActivityType 
            ? $this->activity_type->label() 
            : (\App\Enums\ActivityType::tryFrom($this->activity_type)?->label() ?? ucfirst($this->activity_type));
    }

    public function getActivityTypeIconAttribute(): string
    {
        return $this->activity_type instanceof \App\Enums\ActivityType 
            ? $this->activity_type->icon() 
            : (\App\Enums\ActivityType::tryFrom($this->activity_type)?->icon() ?? 'fa-info-circle text-muted');
    }

    public function getStatusLabelAttribute(): string
    {
        return [
            'pending' => 'Beklemede',
            'in_progress' => 'Devam Ediyor',
            'completed' => 'Tamamlandı',
            'cancelled' => 'İptal Edildi',
            'deferred' => 'Ertelendi',
        ][$this->status] ?? ucfirst($this->status);
    }

    public function getPriorityLabelAttribute(): string
    {
        return [
            'low' => 'Düşük',
            'normal' => 'Normal',
            'high' => 'Yüksek',
            'urgent' => 'Acil',
        ][$this->priority] ?? ucfirst($this->priority);
    }

    // ─── BOOT ────────────────────────────────────────────────────────────────

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (SaleActivity $activity) {
            if (auth()->check()) {
                if (!$activity->performed_by) {
                    $activity->performed_by = auth()->id();
                }
            }

            if (!$activity->activity_date) {
                $activity->activity_date = now();
            }
        });

        static::updating(function (SaleActivity $activity) {
            if ($activity->isDirty('status') && $activity->status === 'completed' && !$activity->completed_date) {
                $activity->completed_date = now();
            }
        });
    }
}
