<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\Conversation; // Assuming your Conversation model
use App\Models\Message; // Assuming your Message model
use App\Models\SchoolService;
use App\Models\Booking;
use App\Models\SchoolServiceBookingDetail;

use App\Models\User;
use Illuminate\Support\Facades\Auth;

class UserMessageController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        // Fetch conversations where the user is a participant
        $conversations = Conversation::where('user_id', $user->id)->orWhere('doctor_id', $user->id)->with(['messages' => function ($query) {    $query->latest()->limit(1);}, 'user', 'secondParticipant'])->orderBy('last_message_at', 'desc')->get();

        // Fetch confirmed school service bookings for the current user
        $schoolServiceBookings = Booking::where('user_id', $user->id)->where('status', 'confirmed')->where('bookable_type', SchoolService::class)->with(['schoolServiceBookingDetail.schoolService.instructor' => function ($query) {$query->where('role', 100);}])->get();

        foreach ($schoolServiceBookings as $booking) {
            if ($booking->schoolServiceBookingDetail && $booking->schoolServiceBookingDetail->schoolService) {
                $instructor = $booking->schoolServiceBookingDetail->schoolService->instructor;

                if ($instructor) {
                // Find or create a conversation between the user and the instructor
                $existingConversation = $conversations->first(function ($conversation) use ($user, $instructor) {
                    return ($conversation->user_id === $user->id && $conversation->doctor_id === $instructor->id) || ($conversation->doctor_id === $instructor->id && $conversation->user_id === $user->id);
                });

                if (!$existingConversation) {
                    $newConversation = Conversation::create([
                        'user_id' => $user->id,
                        'doctor_id' => $instructor->id,
                        'last_message_at' => now(),
                    ]);
                    // Reload the conversation with relationships for consistent structure
                    $newConversation->load(['messages' => function ($query) {
                        $query->latest()->limit(1);
                    }, 'user', 'secondParticipant']);
                    $conversations->push($newConversation);
                }
            }
        }

        $conversations = $conversations->map(function ($conversation) use ($user) {
            $otherParticipant = $conversation->user_id == $user->id ? $conversation->secondParticipant : $conversation->user;
            return [
                'id' => $conversation->id,
                'with' => $otherParticipant->name,
                'avatar' => 'https://ui-avatars.com/api/?name=' . urlencode($otherParticipant->name) . '&background=random',
                'lastMessage' => $conversation->messages->first() ? $conversation->messages->first()->body : 'No messages yet',
                'timestamp' => $conversation->last_message_at ? $conversation->last_message_at->diffForHumans() : null,
                'unread' => $conversation->messages()->where('sender_id', '!=', $user->id)->whereNull('read_at')->count(),
                ];
            });
    
            return Inertia::render('User/Messages/Index', [
                'conversations' => $conversations,
            ]);
        }
    }
    
    public function show(Conversation $conversation)
    {
        $this->authorize('view', $conversation);

        $conversation->messages()->where('sender_id', '!=', auth()->id())->whereNull('read_at')->update(['read_at' => now()]);

        return response()->json([
            'messages' => $conversation->messages()->orderBy('created_at', 'asc')->get()->map(function ($message) {
                return [
                    'id' => $message->id,
                    'from' => $message->sender_id == auth()->id() ? 'You' : $message->sender->name,
                    'text' => $message->body,
                    'timestamp' => $message->created_at->format('h:i A'),
                ];
            }),
        ]);
    }

    public function store(Request $request, Conversation $conversation)
    {
        $this->authorize('update', $conversation);

        $request->validate([
            'body' => 'required|string',
        ]);

        $message = $conversation->messages()->create([
            'sender_id' => auth()->id(),
            'body' => $request->body,
        ]);

        $conversation->update(['last_message_at' => now()]);

        return response()->json([
            'id' => $message->id,
            'from' => 'You',
            'text' => $message->body,
            'timestamp' => $message->created_at->format('h:i A'),
        ]);
    }
}
