<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Builder;

/**
 * ChatCategory Model
 * 
 * Represents chat categories for visitor selection.
 * Managed by Super Manager and Manager roles.
 * 
 * Requirements: 4.2, 4.3
 * 
 * @property int $id
 * @property string $name
 * @property string $slug
 * @property string|null $description
 * @property int $sort_order
 * @property string $icon
 * @property string $color
 * @property bool $is_active
 * @property int|null $default_agent_id
 * @property int $expected_response_time
 * @property int|null $created_by
 * @property int $conversations_count
 */
class ChatCategory extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'slug',
        'description',
        'sort_order',
        'icon',
        'color',
        'is_active',
        'default_agent_id',
        'expected_response_time',
        'created_by',
        'conversations_count',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'is_active' => 'boolean',
        'sort_order' => 'integer',
        'expected_response_time' => 'integer',
        'conversations_count' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * Default icons available for categories.
     */
    public static function availableIcons(): array
    {
        return [
            'fa-headset' => 'Customer Support',
            'fa-question-circle' => 'General Inquiry',
            'fa-shopping-cart' => 'Sales',
            'fa-tools' => 'Technical Support',
            'fa-file-invoice-dollar' => 'Billing',
            'fa-info-circle' => 'Information',
            'fa-comments' => 'General Chat',
            'fa-handshake' => 'Partnerships',
            'fa-briefcase' => 'Business',
            'fa-graduation-cap' => 'Training',
        ];
    }

    /**
     * Default colors available for categories.
     */
    public static function availableColors(): array
    {
        return [
            '#10b981' => 'Green (Primary)',
            '#3b82f6' => 'Blue',
            '#8b5cf6' => 'Purple',
            '#f59e0b' => 'Orange',
            '#ef4444' => 'Red',
            '#06b6d4' => 'Cyan',
            '#ec4899' => 'Pink',
            '#84cc16' => 'Lime',
            '#f97316' => 'Deep Orange',
            '#6366f1' => 'Indigo',
        ];
    }

    /**
     * Get the default agent for this category.
     */
    public function defaultAgent(): BelongsTo
    {
        return $this->belongsTo(User::class, 'default_agent_id');
    }

    /**
     * Get the user who created this category.
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get conversations in this category.
     */
    public function conversations(): HasMany
    {
        return $this->hasMany(ChatConversation::class, 'category_id');
    }

    /**
     * Scope for active categories only.
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope for inactive categories.
     */
    public function scopeInactive(Builder $query): Builder
    {
        return $query->where('is_active', false);
    }

    /**
     * Scope for ordered categories.
     */
    public function scopeOrdered(Builder $query): Builder
    {
        return $query->orderBy('sort_order')->orderBy('name');
    }

    /**
     * Scope for searching categories.
     */
    public function scopeSearch(Builder $query, string $search): Builder
    {
        return $query->where(function ($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('description', 'like', "%{$search}%");
        });
    }

    /**
     * Increment conversation count.
     */
    public function incrementConversations(): void
    {
        $this->increment('conversations_count');
    }

    /**
     * Get active conversations count.
     */
    public function getActiveConversationsCountAttribute(): int
    {
        return $this->conversations()
            ->whereIn('status', [ChatConversation::STATUS_WAITING, ChatConversation::STATUS_ACTIVE])
            ->count();
    }

    /**
     * Get waiting conversations count.
     */
    public function getWaitingConversationsCountAttribute(): int
    {
        return $this->conversations()
            ->where('status', ChatConversation::STATUS_WAITING)
            ->count();
    }

    /**
     * Activate the category.
     */
    public function activate(): void
    {
        $this->update(['is_active' => true]);
    }

    /**
     * Deactivate the category.
     */
    public function deactivate(): void
    {
        $this->update(['is_active' => false]);
    }

    /**
     * Get formatted expected response time.
     */
    public function getFormattedResponseTimeAttribute(): string
    {
        $minutes = $this->expected_response_time;
        
        if ($minutes < 60) {
            return $minutes . ' minute' . ($minutes > 1 ? 's' : '');
        }
        
        $hours = floor($minutes / 60);
        $remainingMinutes = $minutes % 60;
        
        $result = $hours . ' hour' . ($hours > 1 ? 's' : '');
        
        if ($remainingMinutes > 0) {
            $result .= ' ' . $remainingMinutes . ' minute' . ($remainingMinutes > 1 ? 's' : '');
        }
        
        return $result;
    }

    /**
     * Generate slug from name.
     */
    public static function generateSlug(string $name): string
    {
        $slug = \Str::slug($name);
        $count = 1;
        
        while (self::where('slug', $slug)->exists()) {
            $slug = \Str::slug($name) . '-' . $count++;
        }
        
        return $slug;
    }
}
