<?php

namespace App\Models;

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

class Lead extends Model
{
    use HasFactory;

    protected $fillable = [
        'device_id',
        'customer_phone',
        'customer_name',
        'customer_email',
        'source',
        'status',
        'lead_score',
        'notes',
        'custom_fields',
        'assigned_to',
        'ticket_id',
        'last_contact_at',
        'converted_at',
    ];

    protected $casts = [
        'notes' => 'array',
        'custom_fields' => 'array',
        'last_contact_at' => 'datetime',
        'converted_at' => 'datetime',
        'lead_score' => 'integer',
    ];

    // Relationships
    public function device()
    {
        return $this->belongsTo(Device::class);
    }

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

    public function ticket()
    {
        return $this->belongsTo(SupportTicket::class);
    }

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

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

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

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

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

    public function scopeAssigned($query)
    {
        return $query->whereNotNull('assigned_to');
    }

    public function scopeUnassigned($query)
    {
        return $query->whereNull('assigned_to');
    }

    public function scopeForDevice($query, $deviceId)
    {
        return $query->where('device_id', $deviceId);
    }

    public function scopeHighScore($query, $minScore = 70)
    {
        return $query->where('lead_score', '>=', $minScore);
    }

    public function scopeBySource($query, $source)
    {
        return $query->where('source', $source);
    }

    // Methods
    public function qualify()
    {
        $this->status = 'qualified';
        $this->save();

        $this->addNote('Lead qualified for further engagement.');

        return $this;
    }

    public function convert()
    {
        $this->status = 'converted';
        $this->converted_at = now();
        $this->save();

        $this->addNote('Lead successfully converted to customer.');

        return $this;
    }

    public function markAsLost($reason = null)
    {
        $this->status = 'lost';
        $this->save();

        if ($reason) {
            $this->addNote("Lead marked as lost. Reason: {$reason}");
        }

        return $this;
    }

    public function updateScore($points)
    {
        $this->lead_score = max(0, min(100, $this->lead_score + $points));
        $this->save();

        return $this;
    }

    public function addNote($note, $userId = null)
    {
        $notes = $this->notes ?? [];
        
        $notes[] = [
            'note' => $note,
            'user_id' => $userId ?? auth()->id(),
            'timestamp' => now()->toDateTimeString(),
        ];

        $this->notes = $notes;
        $this->save();

        return $this;
    }

    public function assignToAgent($agentId)
    {
        $this->assigned_to = $agentId;
        $this->save();

        $agent = User::find($agentId);
        if ($agent) {
            $this->addNote("Lead assigned to agent: {$agent->name}");
        }

        return $this;
    }

    public function updateContactDate()
    {
        $this->last_contact_at = now();
        $this->save();

        return $this;
    }

    public function moveToStatus($newStatus)
    {
        $oldStatus = $this->status;
        $this->status = $newStatus;
        $this->save();

        $this->addNote("Status changed from {$oldStatus} to {$newStatus}");

        return $this;
    }

    public function setCustomField($key, $value)
    {
        $customFields = $this->custom_fields ?? [];
        $customFields[$key] = $value;
        
        $this->custom_fields = $customFields;
        $this->save();

        return $this;
    }

    public function getCustomField($key, $default = null)
    {
        return $this->custom_fields[$key] ?? $default;
    }

    public function isConverted()
    {
        return $this->status === 'converted';
    }

    public function isLost()
    {
        return $this->status === 'lost';
    }

    public function isActive()
    {
        return !in_array($this->status, ['converted', 'lost']);
    }
}
