97 lines
2.5 KiB
PHP
97 lines
2.5 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Http\Controllers\User;
|
||
|
|
|
||
|
|
use App\Http\Controllers\Controller;
|
||
|
|
use Illuminate\Http\Request;
|
||
|
|
use App\Models\SupportTicket;
|
||
|
|
use App\Models\ChatMessage;
|
||
|
|
use App\Events\NewChatMessage;
|
||
|
|
|
||
|
|
class ChatController extends Controller
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Start chat or return existing ticket for this user
|
||
|
|
*/
|
||
|
|
public function startChat()
|
||
|
|
{
|
||
|
|
// One chat ticket per user
|
||
|
|
$ticket = SupportTicket::firstOrCreate([
|
||
|
|
'user_id' => auth()->id(),
|
||
|
|
]);
|
||
|
|
|
||
|
|
return response()->json([
|
||
|
|
'success' => true,
|
||
|
|
'ticket' => $ticket
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Load all messages for this ticket
|
||
|
|
*/
|
||
|
|
public function getMessages($ticketId)
|
||
|
|
{
|
||
|
|
// Ensure this ticket belongs to the logged-in user
|
||
|
|
$ticket = SupportTicket::where('id', $ticketId)
|
||
|
|
->where('user_id', auth()->id())
|
||
|
|
->firstOrFail();
|
||
|
|
|
||
|
|
$messages = ChatMessage::where('ticket_id', $ticketId)
|
||
|
|
->orderBy('created_at', 'asc')
|
||
|
|
->with('sender')
|
||
|
|
->get();
|
||
|
|
|
||
|
|
return response()->json([
|
||
|
|
'success' => true,
|
||
|
|
'messages' => $messages
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Send text or file message from user → admin/staff
|
||
|
|
*/
|
||
|
|
public function sendMessage(Request $request, $ticketId)
|
||
|
|
{
|
||
|
|
$request->validate([
|
||
|
|
'message' => 'nullable|string',
|
||
|
|
'file' => 'nullable|file|max:20480', // 20MB limit
|
||
|
|
]);
|
||
|
|
|
||
|
|
// Validate ticket ownership
|
||
|
|
$ticket = SupportTicket::where('id', $ticketId)
|
||
|
|
->where('user_id', auth()->id())
|
||
|
|
->firstOrFail();
|
||
|
|
|
||
|
|
$data = [
|
||
|
|
'ticket_id' => $ticketId,
|
||
|
|
'sender_id' => auth()->id(),
|
||
|
|
'sender_type' => \App\Models\User::class,
|
||
|
|
'message' => $request->message,
|
||
|
|
|
||
|
|
'read_by_admin' => false,
|
||
|
|
'read_by_user' => true,
|
||
|
|
];
|
||
|
|
|
||
|
|
// Handle file upload
|
||
|
|
if ($request->hasFile('file')) {
|
||
|
|
$path = $request->file('file')->store('chat', 'public');
|
||
|
|
$data['file_path'] = $path;
|
||
|
|
$data['file_type'] = $request->file('file')->getMimeType();
|
||
|
|
}
|
||
|
|
|
||
|
|
// Save message
|
||
|
|
$message = ChatMessage::create($data);
|
||
|
|
|
||
|
|
// Load sender info for broadcast
|
||
|
|
$message->load('sender');
|
||
|
|
|
||
|
|
// Fire real-time event
|
||
|
|
broadcast(new NewChatMessage($message));
|
||
|
|
|
||
|
|
return response()->json([
|
||
|
|
'success' => true,
|
||
|
|
'message' => $message
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
}
|