<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ChatSession;
use App\Models\LeadFormSubmission;
use App\Models\PromptLibrary;

class ChatAdminController extends Controller
{
    public function dashboard()
    {
        $stats = [
            'total_sessions' => ChatSession::count(),
            'returning_sessions' => ChatSession::where('is_returning', true)->count(),
            'lead_forms' => LeadFormSubmission::count(),
            'chat_minutes' => (int) ceil(ChatSession::sum('active_seconds') / 60),
            'active_prompts' => PromptLibrary::where('status', 'active')->count(),
        ];

        $recentChats = ChatSession::query()
            ->withCount('messages')
            ->latest('last_activity_at')
            ->limit(10)
            ->get();

        $recentForms = LeadFormSubmission::query()
            ->with('session:id,phone')
            ->latest()
            ->limit(10)
            ->get();

        return view('admin.chats.dashboard', compact('stats', 'recentChats', 'recentForms'));
    }

    public function sessions()
    {
        $sessions = ChatSession::query()
            ->withCount('messages')
            ->latest('last_activity_at')
            ->paginate(20);

        return view('admin.chats.index', compact('sessions'));
    }

    public function show(ChatSession $session)
    {
        $session->load(['messages', 'formSubmissions']);

        return view('admin.chats.show', compact('session'));
    }

    public function forms()
    {
        $forms = LeadFormSubmission::query()
            ->with('session:id,phone')
            ->latest()
            ->paginate(20);

        return view('admin.forms.index', compact('forms'));
    }
}
