<?php

namespace App\Http\Controllers\Brand;

use App\Http\Controllers\Controller;
use App\Models\MessageThread;
use App\Models\Message;
use App\Models\User;
use Illuminate\Http\Request;

class MessageController extends Controller
{
    /**
     * Display a listing of message threads
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $threads = MessageThread::whereHas('participants', function ($query) {
            $query->where('user_id', auth()->id());
        })->with(['participants.user', 'latestMessage'])
        ->orderBy('updated_at', 'desc')
        ->paginate(20);
        
        return view('brand.messages.index', compact('threads'));
    }
    
    /**
     * Display the specified message thread
     *
     * @param  \App\Models\MessageThread  $thread
     * @return \Illuminate\Http\Response
     */
    public function show(MessageThread $thread)
    {
        // Ensure the user is a participant in the thread
        if (!$thread->participants()->where('user_id', auth()->id())->exists()) {
            abort(403);
        }
        
        // Mark messages as read
        $thread->messages()
            ->where('recipient_id', auth()->id())
            ->where('is_read', false)
            ->update(['is_read' => true, 'read_at' => now()]);
            
        // Mark thread as read for this user
        $thread->participants()
            ->where('user_id', auth()->id())
            ->update(['is_read' => true, 'last_read_at' => now()]);
        
        $messages = $thread->messages()->with('sender')->orderBy('created_at', 'asc')->get();
        $participants = $thread->participants()->with('user')->get();
        
        return view('brand.messages.show', compact('thread', 'messages', 'participants'));
    }
    
    /**
     * Store a newly created message thread
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'recipient_id' => 'required|exists:users,id',
            'subject' => 'nullable|string|max:255',
            'message' => 'required|string',
            'attachment' => 'nullable|file|max:2048',
        ]);
        
        // Check if a thread already exists between these users
        $existingThread = MessageThread::whereHas('participants', function ($query) use ($validated) {
            $query->where('user_id', auth()->id());
        })->whereHas('participants', function ($query) use ($validated) {
            $query->where('user_id', $validated['recipient_id']);
        })->first();
        
        if ($existingThread) {
            // Use existing thread
            $thread = $existingThread;
        } else {
            // Create new thread
            $thread = new MessageThread([
                'subject' => $validated['subject'] ?? null,
            ]);
            $thread->save();
            
            // Add participants
            $thread->participants()->createMany([
                ['user_id' => auth()->id()],
                ['user_id' => $validated['recipient_id']],
            ]);
        }
        
        // Handle file upload
        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('messages', 'public');
        }
        
        // Create the message
        $message = new Message([
            'sender_id' => auth()->id(),
            'recipient_id' => $validated['recipient_id'],
            'subject' => $validated['subject'] ?? null,
            'message' => $validated['message'],
            'attachment_path' => $attachmentPath,
            'thread_id' => $thread->id,
        ]);
        $message->save();
        
        // Update thread timestamp
        $thread->updated_at = now();
        $thread->save();
        
        return redirect()->route('brand.messages.show', $thread)->with('success', 'Message sent successfully!');
    }
    
    /**
     * Reply to an existing message thread
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\MessageThread  $thread
     * @return \Illuminate\Http\Response
     */
    public function reply(Request $request, MessageThread $thread)
    {
        // Ensure the user is a participant in the thread
        if (!$thread->participants()->where('user_id', auth()->id())->exists()) {
            abort(403);
        }
        
        $validated = $request->validate([
            'message' => 'required|string',
            'attachment' => 'nullable|file|max:2048',
        ]);
        
        // Get other participants
        $otherParticipants = $thread->participants()->where('user_id', '!=', auth()->id())->get();
        
        // Handle file upload
        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('messages', 'public');
        }
        
        // Create messages for each participant
        foreach ($otherParticipants as $participant) {
            $message = new Message([
                'sender_id' => auth()->id(),
                'recipient_id' => $participant->user_id,
                'subject' => $thread->subject,
                'message' => $validated['message'],
                'attachment_path' => $attachmentPath,
                'thread_id' => $thread->id,
            ]);
            $message->save();
        }
        
        // Update thread timestamp
        $thread->updated_at = now();
        $thread->save();
        
        return redirect()->back()->with('success', 'Reply sent successfully!');
    }
}