<?php

namespace App\Http\Controllers;

use App\Events\ChatMessageSent;
use App\Models\Chat;
use App\Models\Guru;
use App\Models\Rujukan;
use App\Models\Siswa;
use App\Models\Spesialis;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ChatController extends Controller
{
    public function index($receiverId = null)
    {
        $auth = Auth::user();

        // Tentukan target role (Siswa <-> GuruBK)
        $targetRole = $auth->hasRole('GuruBK') ? 'Siswa' : 'GuruBK';

        // Ambil semua user berdasarkan role
        $users = User::role($targetRole)->get();

        $canChatWith = [];

        if ($auth->hasRole('Siswa')) {
            $siswa = Siswa::where('id_user', $auth->id)->first();

            if ($siswa) {
                // Ambil semua user yang role-nya GuruBK
                $users = User::role('GuruBK')->get();

                // daftar id user GuruBK supaya bisa diizinkan chat
                $canChatWith = $users->pluck('id')->toArray();
            }
        } elseif ($auth->hasRole('GuruBK')) {
            $guru = Guru::where('id_user', $auth->id)->first();

            if ($guru) {
                // Ambil siswa binaan YANG SUDAH MENGISI KUESIONER
                $siswas = Siswa::whereHas('jawabanKuesioner')->get();
                $users = User::whereIn('id', $siswas->pluck('id_user'))->get();
                $canChatWith = $siswas->pluck('id_user')->toArray();

                // 🔹 Tambahkan spesialis ke daftar chat
                $spesialisUsers = User::role('Spesialis')->get(); // pakai spatie/laravel-permission
                $users = $users->merge($spesialisUsers);
                $canChatWith = array_merge($canChatWith, $spesialisUsers->pluck('id')->toArray());
            }
        }


        // Tetapkan receiver (jika ada)
        $receiver = $receiverId ? User::find($receiverId) : null;
        $chats = $this->getChats($auth, $receiver);

        return view('chat', compact('users', 'chats', 'receiver', 'canChatWith'));
    }

    protected function getChats($auth, $receiver)
    {
        if (!$receiver) return collect();

        return Chat::where(function ($q) use ($auth, $receiver) {
            $q->where('sender_id', $auth->id)
                ->where('receiver_id', $receiver->id);
        })
            ->orWhere(function ($q) use ($auth, $receiver) {
                $q->where('sender_id', $receiver->id)
                    ->where('receiver_id', $auth->id);
            })
            ->orderBy('created_at')
            ->get();
    }



    public function store(Request $request)
    {
        try {
            $chat = Chat::create([
                'sender_id' => Auth::user()->id,
                'receiver_id' => $request->receiver_id,
                'message' => $request->message,
                'status' => 0,
                'id_rujukan' => null,
            ]);

            broadcast(new ChatMessageSent(
                $chat->message,
                $chat->sender_id,
                $chat->receiver_id
            ))->toOthers();

            return response()->json([
                'status' => 'success',
                'message' => 'Pesan berhasil dikirim',
                'data' => $chat,
                'redirect' => route('chat.index', $chat->receiver_id)
            ]);
        } catch (\Throwable $e) {
            Log::error($e);
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 500);
        }
    }
}
