<?php

namespace App\Services;

use App\Models\Setting;
use App\Models\ChatConversation;
use App\Models\ChatMessage;
use GuzzleHttp\Client;

class AIChatService
{
    protected ?string $provider;
    protected ?string $apiKey;
    protected ?string $model;
    protected ?string $personality;

    public function __construct()
    {
        $this->provider = Setting::where('key', 'chat_ai_provider')->value('value') ?? 'openai';
        $this->apiKey = Setting::where('key', 'chat_ai_api_key')->value('value');
        $this->model = Setting::where('key', 'chat_ai_model')->value('value') ?? 'gpt-3.5-turbo';
        $this->personality = Setting::where('key', 'chat_ai_personality')->value('value') 
            ?? 'أنت مساعد ودود لمتجر روابي نحلة للعسل الطبيعي. ساعد الزبائن بالإجابة على أسئلتهم حول المنتجات والطلبات والشحن. كن لطيفاً ومختصراً.';
    }

    public function isConfigured(): bool
    {
        return !empty($this->apiKey);
    }

    public function generateResponse(string $userMessage, array $conversationHistory = []): string
    {
        if (!$this->isConfigured()) {
            return 'عذراً، خدمة الشات الذكي غير مفعلة حالياً. يرجى التواصل معنا عبر الواتساب.';
        }

        try {
            return match ($this->provider) {
                'openai' => $this->callOpenAI($userMessage, $conversationHistory),
                'deepseek' => $this->callDeepSeek($userMessage, $conversationHistory),
                'gemini' => $this->callGemini($userMessage, $conversationHistory),
                default => 'مزود الخدمة غير مدعوم.',
            };
        } catch (\Exception $e) {
            \Log::error('AI Chat Error: ' . $e->getMessage());
            return 'عذراً، حدث خطأ في معالجة رسالتك. يرجى المحاولة مرة أخرى.';
        }
    }

    protected function callOpenAI(string $message, array $history): string
    {
        $client = new Client();
        $messages = [['role' => 'system', 'content' => $this->personality]];
        
        foreach ($history as $msg) {
            $messages[] = [
                'role' => $msg['sender_type'] === 'customer' ? 'user' : 'assistant',
                'content' => $msg['message'],
            ];
        }
        $messages[] = ['role' => 'user', 'content' => $message];

        $response = $client->post('https://api.openai.com/v1/chat/completions', [
            'headers' => [
                'Authorization' => "Bearer {$this->apiKey}",
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'model' => $this->model,
                'messages' => $messages,
                'max_tokens' => 500,
                'temperature' => 0.7,
            ],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['choices'][0]['message']['content'] ?? 'لم أتمكن من فهم سؤالك.';
    }

    protected function callDeepSeek(string $message, array $history): string
    {
        $client = new Client();
        $messages = [['role' => 'system', 'content' => $this->personality]];
        
        foreach ($history as $msg) {
            $messages[] = [
                'role' => $msg['sender_type'] === 'customer' ? 'user' : 'assistant',
                'content' => $msg['message'],
            ];
        }
        $messages[] = ['role' => 'user', 'content' => $message];

        $response = $client->post('https://api.deepseek.com/v1/chat/completions', [
            'headers' => [
                'Authorization' => "Bearer {$this->apiKey}",
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'model' => $this->model ?: 'deepseek-chat',
                'messages' => $messages,
                'max_tokens' => 500,
            ],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['choices'][0]['message']['content'] ?? 'لم أتمكن من فهم سؤالك.';
    }

    protected function callGemini(string $message, array $history): string
    {
        $client = new Client();
        $contents = [];
        
        foreach ($history as $msg) {
            $contents[] = [
                'role' => $msg['sender_type'] === 'customer' ? 'user' : 'model',
                'parts' => [['text' => $msg['message']]],
            ];
        }
        $contents[] = ['role' => 'user', 'parts' => [['text' => $message]]];

        $model = $this->model ?: 'gemini-pro';
        $response = $client->post("https://generativelanguage.googleapis.com/v1/models/{$model}:generateContent?key={$this->apiKey}", [
            'headers' => ['Content-Type' => 'application/json'],
            'json' => [
                'contents' => $contents,
                'systemInstruction' => ['parts' => [['text' => $this->personality]]],
            ],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['candidates'][0]['content']['parts'][0]['text'] ?? 'لم أتمكن من فهم سؤالك.';
    }
}
