<?php

namespace App\Http\Controllers;

use App\Models\SupportMessage;
use App\Models\User;
use App\Models\Notification;
use Illuminate\Http\Request;

class SupportController extends Controller
{
    // USER: send a message
    public function send(Request $request)
    {
        $request->validate(['message' => 'required|string|max:1000']);

        $user = $request->user();

        $msg = SupportMessage::create([
            'user_id' => $user->id,
            'message' => $request->message,
            'sender'  => 'user',
            'read'    => false,
        ]);

        $admins = User::where('role', 'admin')->get();
        foreach ($admins as $admin) {
            Notification::create([
                'user_id' => $admin->id,
                'title'   => 'New support message',
                'message' => "{$user->name} sent a support message.",
            ]);
        }

        return response()->json(['message' => $msg]);
    }

    // USER: fetch my conversation
    public function myMessages(Request $request)
    {
        $messages = SupportMessage::where('user_id', $request->user()->id)
            ->orderBy('created_at')
            ->get();

        SupportMessage::where('user_id', $request->user()->id)
            ->where('sender', 'admin')
            ->where('read', false)
            ->update(['read' => true]);

        return response()->json(['messages' => $messages]);
    }

    // USER: count unread admin replies (for bubble badge)
    public function unreadCount(Request $request)
    {
        $count = SupportMessage::where('user_id', $request->user()->id)
            ->where('sender', 'admin')
            ->where('read', false)
            ->count();

        return response()->json(['unread' => $count]);
    }

    // ADMIN: list all conversations (grouped by user, latest first)
    public function inbox()
    {
        $userIds = SupportMessage::selectRaw('user_id, MAX(created_at) as last_at')
            ->groupBy('user_id')
            ->orderByDesc('last_at')
            ->pluck('user_id');

        $conversations = $userIds->map(function ($userId) {
            $user = User::find($userId, ['id', 'name', 'email', 'avatar']);
            $unread = SupportMessage::where('user_id', $userId)
                ->where('sender', 'user')
                ->where('read', false)
                ->count();

            return [
                'user_id' => $userId,
                'user'    => $user,
                'unread'  => $unread,
            ];
        });

        return response()->json(['conversations' => $conversations]);
    }

    // ADMIN: get one user's full conversation
    public function conversation($userId)
    {
        $messages = SupportMessage::where('user_id', $userId)
            ->orderBy('created_at')
            ->get();

        SupportMessage::where('user_id', $userId)
            ->where('sender', 'user')
            ->where('read', false)
            ->update(['read' => true]);

        $user = User::find($userId, ['id', 'name', 'email', 'avatar']);

        return response()->json(['messages' => $messages, 'user' => $user]);
    }

    // ADMIN: reply to a user
    public function reply(Request $request, $userId)
    {
        $request->validate(['message' => 'required|string|max:1000']);

        $msg = SupportMessage::create([
            'user_id' => $userId,
            'message' => $request->message,
            'sender'  => 'admin',
            'read'    => false,
        ]);

        Notification::create([
            'user_id' => $userId,
            'title'   => 'Support replied',
            'message' => 'You have a new reply from Fargo Support. Tap to view.',
        ]);

        return response()->json(['message' => $msg]);
    }

    // ADMIN: total unread (for admin badge)
    public function adminUnreadCount()
    {
        $count = SupportMessage::where('sender', 'user')
            ->where('read', false)
            ->count();

        return response()->json(['unread' => $count]);
    }
}