<?php

namespace App\Http\Controllers;

use App\Events\MessageSent;
use App\Models\Message;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ChatController extends Controller
{
    // Lista de usuarios con quienes puedo chatear
    public function index()
    {
        $users = User::where('id', '!=', auth()->id())->get();
        return view('chat.index', compact('users'));
    }

    // Mensajes entre yo y otro usuario
    public function show(User $user)
    {
        $messages = Message::where(function ($q) use ($user) {
                $q->where('user_id', auth()->id())
                  ->where('receiver_id', $user->id);
            })
            ->orWhere(function ($q) use ($user) {
                $q->where('user_id', $user->id)
                  ->where('receiver_id', auth()->id());
            })
            ->with('sender')
            ->orderBy('created_at', 'asc')
            ->get();

        // marcar como leídos
        Message::where('user_id', $user->id)
            ->where('receiver_id', auth()->id())
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

        return view('chat.show', compact('user', 'messages'));
    }

    // Enviar mensaje
    public function send(Request $request)
    {
        $request->validate([
            'receiver_id' => 'required|exists:users,id',
            'body'        => 'nullable|string',
            'attachment'  => 'nullable|file|max:20480',
        ]);

        $attachment = null;
        $attachmentType = null;

        if ($request->hasFile('attachment')) {
            $file = $request->file('attachment');
            $attachment = $file->store('chat', 'local');
            $mime = $file->getMimeType();

            if (str_starts_with($mime, 'image')) $attachmentType = 'image';
            elseif (str_starts_with($mime, 'video')) $attachmentType = 'video';
            elseif (str_starts_with($mime, 'audio')) $attachmentType = 'audio';
            else $attachmentType = 'file';
        }

        $message = Message::create([
            'user_id'         => auth()->id(),
            'receiver_id'     => $request->receiver_id,
            'body'            => $request->body,
            'attachment'      => $attachment,
            'attachment_type' => $attachmentType,
        ]);

        $message->load('sender');

        broadcast(new MessageSent($message))->toOthers();

        $message->created_at = $message->created_at->format('H:i');

        return response()->json($message);
    }
}
