<?php

namespace App\Models;

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

class Chatbot extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'sender',
        'name',
        'description',
        'type',
        'is_active',
        'config',
        'intents',
        'fallback_message',
        'priority',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'config' => 'array',
        'intents' => 'array',
    ];

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

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

    public function sessions()
    {
        return $this->hasMany(ChatbotSession::class);
    }

    public function intentsData()
    {
        return $this->hasMany(ChatbotIntent::class);
    }

    public function processMessage($phone, $message)
    {
        // Find or create session
        $session = ChatbotSession::firstOrCreate(
            [
                'chatbot_id' => $this->id,
                'phone' => $phone,
            ],
            [
                'session_id' => uniqid('session_'),
                'context' => [],
                'last_activity' => now(),
            ]
        );

        $session->update(['last_activity' => now()]);

        // Match intent
        $response = $this->matchIntent($message);
        
        // Log conversation
        ChatbotConversation::create([
            'chatbot_session_id' => $session->id,
            'user_message' => $message,
            'bot_response' => $response['message'] ?? $this->fallback_message,
            'intent' => $response['intent'] ?? null,
            'confidence' => $response['confidence'] ?? null,
        ]);

        return $response['message'] ?? $this->fallback_message;
    }

    private function matchIntent($message)
    {
        if (!$this->intents) {
            return ['message' => $this->fallback_message];
        }

        foreach ($this->intents as $intent) {
            if (isset($intent['patterns'])) {
                foreach ($intent['patterns'] as $pattern) {
                    if (stripos($message, $pattern) !== false) {
                        $responses = $intent['responses'] ?? [];
                        return [
                            'message' => $responses[array_rand($responses)] ?? $this->fallback_message,
                            'intent' => $intent['name'] ?? 'unknown',
                            'confidence' => 85.00,
                        ];
                    }
                }
            }
        }

        return ['message' => $this->fallback_message];
    }
}
