<?php

namespace App\Http\Controllers\Developer;

use App\Http\Controllers\Admin\ChatController as AdminChatController;
use App\Models\ChatSession;
use App\Models\ChatMessage;
use Illuminate\Http\Request;

class ChatController extends AdminChatController
{
    public function index()
    {
        $sessions = ChatSession::with(['tenant', 'latestMessage'])
            ->active()
            ->orderBy('last_message_at', 'desc')
            ->paginate(20);

        $unreadCount = ChatMessage::forAdmin()->unread()->count();

        return view('developer.chat.index', compact('sessions', 'unreadCount'));
    }

    public function show($id)
    {
        $session = ChatSession::with(['tenant', 'messages' => function($query) {
            $query->orderBy('created_at', 'asc');
        }])->findOrFail($id);

        // Mark messages as read
        ChatMessage::where('chat_session_id', $id)
            ->forAdmin()
            ->unread()
            ->update([
                'is_read' => true,
                'read_at' => now()
            ]);

        return view('developer.chat.show', compact('session'));
    }
}
