# AI Support Chat Integration Plan

This document outlines the proposed transformation of the support bubble flow to incorporate a Gemini AI assistance layer before escalating issues to the standard ticketing system.

## Objective
To implement an intermediary AI chat layer using `AiSupportService.php` that interacts with the user via the `Spatie Support Bubble` interface. The goal is to provide immediate automated assistance and only create a manual ticket in the `binshops/laravel-ticket` system if the AI cannot resolve the request or if the user explicitly requests human escalation.

## Key Components
- **Frontend**: Support Bubble UI (Spatie)
- **Controller**: `SupportChatController.php` (Intermediate Logic)
- **AI Service**: `AiSupportService.php` (Gemini API Integration)
- **Ticketing**: `binshops/laravel-ticket` (Final Escalation)

## High-Level Workflow
1. User submits a message through the Support Bubble.
2. `SupportChatController` intercepts the request.
3. The request is passed to `AiSupportService` for a Gemini-generated response.
4. The response is returned to the user via the bubble.
5. If escalation is required, a ticket is then generated.

---
*Ready for further instructions and detailed planning.*

These files exist:
`SupportChatController.php` (Intermediate Logic)
`AiSupportService.php` (Gemini API Integration)

This is what has been done:

./vendor/bin/sail php artisan make:model Conversation -m
public function up()
{
    Schema::create('conversations', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
        $table->string('email')->nullable(); // for guest chats
        $table->boolean('escalated')->default(false);
        $table->timestamps();
    });
}

./vendor/bin/sail php artisan make:model Message -m
public function up()
{
    Schema::create('messages', function (Blueprint $table) {
        $table->id();
        $table->foreignId('conversation_id')->constrained()->cascadeOnDelete();
        $table->enum('role', ['user', 'assistant']);
        $table->text('content');
        $table->timestamps();
    });
}

This is an example controller, it is just a guide for how we could extend ours to perform the same

namespace App\Http\Controllers;

use App\Models\Conversation;
use App\Models\Message;
use App\Services\AiSupportService;
use Illuminate\Http\Request;

class SupportChatController extends Controller
{
    public function start(Request $request)
    {
        $conversation = Conversation::create([
            'user_id' => auth()->id(),
            'email'   => $request->email,
        ]);

        return response()->json([
            'conversation_id' => $conversation->id
        ]);
    }

    public function chat(Request $request, AiSupportService $ai)
    {
        $conversation = Conversation::findOrFail($request->conversation_id);

        if ($conversation->escalated) {
            return response()->json([
                'reply' => 'A human agent will respond shortly.',
                'escalated' => true
            ]);
        }

        // Save user message
        $conversation->messages()->create([
            'role' => 'user',
            'content' => $request->message
        ]);

        $messageCount = $conversation->messages()->count();

        // Escalate after 4 user messages
        if ($messageCount >= 8) { // 4 user + 4 assistant approx
            $ticket = $this->createTicketFromConversation($conversation);

            $conversation->update(['escalated' => true]);

            return response()->json([
                'reply' => 'I’m connecting you to a human agent now.',
                'escalated' => true,
                'ticket_id' => $ticket->id
            ]);
        }

        $reply = $ai->reply($request->message);

        // Save assistant reply
        $conversation->messages()->create([
            'role' => 'assistant',
            'content' => $reply
        ]);

        return response()->json([
            'reply' => $reply,
            'escalated' => false
        ]);
    }

    protected function createTicketFromConversation(Conversation $conversation)
    {
        return \App\Models\Ticket::create([
            'subject' => 'Support Chat Escalation',
            'description' => $conversation->messages
                ->map(fn ($m) => strtoupper($m->role) . ": " . $m->content)
                ->implode("\n\n"),
            'user_id' => $conversation->user_id
        ]);
    }
}

routes:
Route::post('/support/start', [SupportChatController::class, 'start']);
Route::post('/support/chat', [SupportChatController::class, 'chat']);

