# AI Support Chat Phased Implementation Roadmap

This document breaks down the implementation into logical, testable phases. Each phase can be verified independently before moving to the next.

## Phase 1: Data Architecture & Persistence
**Goal**: Prepare the database to store chat history.
1. DONE: **Migrations**: Execute the `conversations` and `messages` migrations as outlined in the initial plan.
2. **Models**: Create `App\Models\Conversation` and `App\Models\Message`.
    - Setup relationships: `Conversation hasMany Message`.
    - Add boolean `escalated` and `user_id` / `email` fields.
3. **Verification**: Confirm database schema via `artisan migrate`.

## Phase 2: AI Service Enhancement
**Goal**: Make `AiSupportService` capable of "context-aware" replies.
1. **Context injection**: Update `reply()` to accept an array of previous messages (role and content).
2. **Prompt Tuning**: Refine the system prompt to explicitly instruct Gemini on when to transition to human help.
3. **Verification**: Run a standalone test script/tinker to verify Gemini responds correctly to a sequence of messages.

## Phase 3: Controller Core Logic (The Intermediary)
**Goal**: Refactor `SupportChatController` to manage the chat state.
1. **Session/Persistent Tracking**: Implement logic to find or create a `Conversation` based on the user's session or specific ID.
2. **Message Storage**: Update the controller to save every user input and every AI response into the `messages` table.
3. **Turn Counting**: Implement the "4-turn" limit logic (or similar) to trigger escalation.
4. **Verification**: Test the controller via Postman/Curl to ensure messages are persisting and the AI is replying.

## Phase 4: Ticketing Bridge (Escalation)
**Goal**: Seamlessly transition from AI Chat to a `binshops/laravel-ticket`.
1. **Escalation Helper**: Implement `createTicketFromConversation()` within the controller. 
    - This must map the conversation text into the Ticket's `content` field.
    - It must maintain the `agent_id` and `user_id` fallbacks we established for guest support.
2. **UI Feedback**: Ensure the response to the user clearly states when a ticket has been opened.
3. **Verification**: Complete a full chat sequence through the backend and verify a ticket appears in the Admin dashboard.

## Phase 5: UI Refinement (Frontend)
**Goal**: Make the "Spatie Support Bubble" feel like a real-time chat.
1. **AJAX Bridge**: (Depending on preference) Modify the bubble's submission script to allow multiple interactions without a full page refresh/bubble reset.
2. **Success View**: Update the `success` view to display the AI's latest advice rather than just a generic "message sent" confirmation.

---
*End of Phased Roadmap. Standing by for review.*
