<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Chat;
use App\Models\Agent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ChatController extends Controller
{
    // الحصول على المحادثات مع وكيل معين
    public function getChats(Request $request)
    {
        $agentId = $request->query('agent_id');
        $userId = Auth::id();

        if (!$agentId) {
            return response()->json(['error' => 'Agent ID is required'], 400);
        }

        // التحقق من وجود الوكيل
        $agent = Agent::find($agentId);
        if (!$agent) {
            return response()->json(['error' => 'Agent not found'], 404);
        }

        $chats = Chat::where('user_id', $userId)
            ->where('agent_id', $agentId)
            ->orderBy('created_at', 'asc')
            ->get();

        return response()->json([
            'success' => true,
            'chats' => $chats,
            'agent' => [
                'id' => $agent->id,
                'name' => $agent->user->name,
                'governorate' => $agent->governorate,
                'is_premium' => $agent->is_premium,
            ]
        ]);
    }

    // إرسال رسالة جديدة
    public function sendMessage(Request $request)
    {
        $request->validate([
            'agent_id' => 'required|exists:agents,id',
            'message' => 'required|string|max:1000',
            'message_type' => 'in:text,image,file',
        ]);

        $chat = Chat::create([
            'user_id' => Auth::id(),
            'agent_id' => $request->agent_id,
            'message' => $request->message,
            'is_agent' => false,
            'message_type' => $request->message_type ?? 'text',
            'file_path' => $request->file_path,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Message sent successfully',
            'chat' => $chat
        ]);
    }

    // رفع صورة
    public function uploadImage(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $filename = time() . '_' . $image->getClientOriginalName();
            $path = $image->storeAs('chat_images', $filename, 'public');

            return response()->json([
                'success' => true,
                'file_path' => $path,
                'url' => Storage::url($path)
            ]);
        }

        return response()->json(['error' => 'No image uploaded'], 400);
    }

    // تحديث حالة القراءة
    public function markAsRead(Request $request)
    {
        $request->validate([
            'agent_id' => 'required|exists:agents,id',
        ]);

        Chat::where('user_id', Auth::id())
            ->where('agent_id', $request->agent_id)
            ->where('is_agent', true)
            ->update(['is_read' => true]);

        return response()->json(['success' => true]);
    }

    // الحصول على قائمة المحادثات
    public function getChatList()
    {
        $userId = Auth::id();

        try {
            $chats = Chat::where('user_id', $userId)
                ->with(['agent.user'])
                ->selectRaw('agent_id, MAX(created_at) as last_message_time, COUNT(*) as message_count')
                ->groupBy('agent_id')
                ->orderBy('last_message_time', 'desc')
                ->get();

            $chatList = $chats->map(function ($chat) use ($userId) {
                $lastMessage = Chat::where('user_id', $userId)
                    ->where('agent_id', $chat->agent_id)
                    ->orderBy('created_at', 'desc')
                    ->first();

                // الحصول على اسم الوكيل من جدول agents مباشرة
                $agentName = $chat->agent->name ?? 'الوكيل';
                
                // إذا لم يكن هناك اسم في جدول agents، جرب الحصول عليه من User
                if ($agentName === 'الوكيل' && $chat->agent->user) {
                    $agentName = $chat->agent->user->name ?? 'الوكيل';
                }

                return [
                    'agent_id' => $chat->agent_id,
                    'agent_name' => $agentName,
                    'agent_governorate' => $chat->agent->governorate ?? 'غير محدد',
                    'is_premium' => $chat->agent->is_premium ?? false,
                    'last_message' => $lastMessage ? $lastMessage->message : 'لا توجد رسائل',
                    'last_message_time' => $lastMessage ? $lastMessage->created_at : now(),
                    'is_agent' => $lastMessage ? $lastMessage->is_agent : false,
                    'unread_count' => Chat::where('user_id', $userId)
                        ->where('agent_id', $chat->agent_id)
                        ->where('is_agent', true)
                        ->where('is_read', false)
                        ->count(),
                ];
            });

            return response()->json([
                'success' => true,
                'chats' => $chatList
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'خطأ في جلب المحادثات: ' . $e->getMessage(),
                'chats' => []
            ], 500);
        }
    }
}
