<?php

namespace App\Models;

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

class TicketAgent extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'device_id',
        'role',
        'status',
        'max_tickets',
        'current_tickets',
        'permissions',
        'auto_assign',
    ];

    protected $casts = [
        'permissions' => 'array',
        'auto_assign' => 'boolean',
        'max_tickets' => 'integer',
        'current_tickets' => 'integer',
    ];

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

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

    public function tickets()
    {
        return $this->hasMany(SupportTicket::class, 'assigned_to', 'user_id')
            ->where('device_id', $this->device_id);
    }

    public function activeTickets()
    {
        return $this->tickets()->open();
    }

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

    public function scopeAvailable($query)
    {
        return $query->where('status', 'online')
            ->where('auto_assign', true)
            ->whereRaw('current_tickets < max_tickets');
    }

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

    public function scopeBySupervisor($query)
    {
        return $query->where('role', 'supervisor');
    }

    public function scopeByAdmin($query)
    {
        return $query->where('role', 'admin');
    }

    // Methods
    public function isAvailable()
    {
        return $this->status === 'online' 
            && $this->auto_assign === true 
            && $this->current_tickets < $this->max_tickets;
    }

    public function canAcceptTicket()
    {
        return $this->isAvailable();
    }

    public function acceptTicket($ticketId)
    {
        if (!$this->canAcceptTicket()) {
            return false;
        }

        $ticket = SupportTicket::find($ticketId);
        
        if (!$ticket || $ticket->device_id !== $this->device_id) {
            return false;
        }

        $ticket->assignToAgent($this->user_id);
        
        return true;
    }

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

        return $this;
    }

    public function getPerformanceMetrics($startDate = null, $endDate = null)
    {
        $query = SupportTicket::where('assigned_to', $this->user_id)
            ->where('device_id', $this->device_id);

        if ($startDate) {
            $query->where('created_at', '>=', $startDate);
        }

        if ($endDate) {
            $query->where('created_at', '<=', $endDate);
        }

        $totalTickets = $query->count();
        $resolvedTickets = (clone $query)->whereIn('status', ['resolved', 'closed'])->count();
        $avgResponseTime = (clone $query)->whereNotNull('first_response_at')
            ->get()
            ->avg(function ($ticket) {
                return $ticket->calculateResponseTime();
            });
        
        $avgResolutionTime = (clone $query)->whereNotNull('resolved_at')
            ->get()
            ->avg(function ($ticket) {
                return $ticket->calculateResolutionTime();
            });

        return [
            'total_tickets' => $totalTickets,
            'resolved_tickets' => $resolvedTickets,
            'resolution_rate' => $totalTickets > 0 ? round(($resolvedTickets / $totalTickets) * 100, 2) : 0,
            'avg_response_time_minutes' => round($avgResponseTime ?? 0, 2),
            'avg_resolution_time_minutes' => round($avgResolutionTime ?? 0, 2),
            'current_active_tickets' => $this->current_tickets,
        ];
    }

    public function hasPermission($permission)
    {
        if ($this->role === 'admin') {
            return true;
        }

        if (!$this->permissions) {
            return false;
        }

        return in_array($permission, $this->permissions);
    }
}
