<?php

namespace App\Http\Controllers\SchoolAdmin;

use App\Http\Controllers\Controller;
use App\Models\Message;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MessageController extends Controller
{
    public function index()
    {
        // Get all unique conversations for the current school admin
        $conversations = Message::where('sender_id', auth()->id())
            ->orWhere('receiver_id', auth()->id())
            ->select(DB::raw('CASE WHEN sender_id = ' . auth()->id() . ' THEN receiver_id ELSE sender_id END as other_user_id'), DB::raw('MAX(created_at) as last_message_time'))
            ->groupBy('other_user_id')
            ->orderBy('last_message_time', 'desc')
            ->get();

        $users = User::whereIn('id', $conversations->pluck('other_user_id'))
            ->get()
            ->keyBy('id');

        return view('schooladmin.communication.messages.index', compact('conversations', 'users'));
    }

    public function chat(User $user)
    {
        $messages = Message::where(function ($query) use ($user) {
                $query->where('sender_id', auth()->id())->where('receiver_id', $user->id);
            })
            ->orWhere(function ($query) use ($user) {
                $query->where('sender_id', $user->id())->where('receiver_id', auth()->id());
            })
            ->orderBy('created_at', 'asc')
            ->get();

        // Mark as read
        Message::where('sender_id', $user->id)
            ->where('receiver_id', auth()->id())
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

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

    public function store(Request $request)
    {
        $request->validate([
            'receiver_id' => 'required|exists:users,id',
            'message' => 'required|string',
        ]);

        Message::create([
            'school_id' => auth()->user()->school_id,
            'sender_id' => auth()->id(),
            'receiver_id' => $request->receiver_id,
            'message' => $request->message,
        ]);

        return back()->with('success', 'Message sent.');
    }
}
