<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Pesan;
use App\Models\Petani;
use App\Models\Pembeli;
use Illuminate\Support\Facades\Auth;

class PesanController extends Controller
{
    // Helper untuk mengambil daftar chat
    private function getChatList($user)
    {
        $allMessages = Pesan::where(function ($q) use ($user) {
            $q->where('pengirim_id', $user->id)->where('pengirim_type', get_class($user));
        })->orWhere(function ($q) use ($user) {
            $q->where('penerima_id', $user->id)->where('penerima_type', get_class($user));
        })->orderBy('created_at', 'desc')->get();

        $conversations = $allMessages->groupBy(function ($pesan) use ($user) {
            if ($pesan->pengirim_id == $user->id && $pesan->pengirim_type == get_class($user)) {
                return $pesan->penerima_type . '_' . $pesan->penerima_id;
            } else {
                return $pesan->pengirim_type . '_' . $pesan->pengirim_id;
            }
        });

        return $conversations->map(function ($msgs) use ($user) {
            $lastMsg = $msgs->first();

            if ($lastMsg->pengirim_id == $user->id && $lastMsg->pengirim_type == get_class($user)) {
                $lawan = $lastMsg->penerima;
            } else {
                $lawan = $lastMsg->pengirim;
            }

            // Fallback 
            $lawanObj = $lawan ?? new \stdClass;

            return [
                'lawan_id' => $lawan->id ?? 0,
                'lawan_type' => get_class($lawanObj),
                'nama' => $lawan->nama_lengkap ?? 'User Terhapus',
                'foto' => $lawan->foto ?? null,
                'last_message' => $lastMsg->isi_pesan,
                'time' => $lastMsg->created_at->diffForHumans(),
                'unread' => $msgs->where('penerima_id', $user->id)
                    ->where('penerima_type', get_class($user))
                    ->where('sudah_dibaca', false)
                    ->count()
            ];
        });
    }

    public function index()
    {
        $user = $this->getAuthenticatedUser();
        $isPetani = Auth::guard('petani')->check();

        // Panggil helper
        $chatList = $this->getChatList($user);

        $view = $isPetani ? 'petani.pesan.index' : 'landing.pesan.index';
        return view($view, compact('chatList'));
    }

    public function show($id)
    {
        $user = $this->getAuthenticatedUser();
        $isPetani = Auth::guard('petani')->check();

        //  Ambil List Chat juga (untuk Sidebar Kiri)
        $chatList = $this->getChatList($user);

        // Logika Detail Chat (Kanan)
        $lawanType = $isPetani ? Pembeli::class : Petani::class;
        $lawan = $lawanType::findOrFail($id);

        $chats = Pesan::where(function ($q) use ($user, $lawan, $lawanType) {
            $q->where('pengirim_id', $user->id)->where('pengirim_type', get_class($user))
                ->where('penerima_id', $lawan->id)->where('penerima_type', $lawanType);
        })->orWhere(function ($q) use ($user, $lawan, $lawanType) {
            $q->where('pengirim_id', $lawan->id)->where('pengirim_type', $lawanType)
                ->where('penerima_id', $user->id)->where('penerima_type', get_class($user));
        })->orderBy('created_at', 'asc')->get();

        // Tandai dibaca
        Pesan::where('pengirim_id', $lawan->id)->where('pengirim_type', $lawanType)
            ->where('penerima_id', $user->id)->update(['sudah_dibaca' => true]);

        $view = $isPetani ? 'petani.pesan.show' : 'landing.pesan.show';

        // Kirim $chatList, $chats, dan $lawan
        return view($view, compact('chatList', 'chats', 'lawan'));
    }

    public function store(Request $request)
    {
        $request->validate(['isi_pesan' => 'required']);
        $user = $this->getAuthenticatedUser();
        $isPetani = Auth::guard('petani')->check();
        $penerimaType = $isPetani ? 'App\Models\Pembeli' : 'App\Models\Petani';

        Pesan::create([
            'pengirim_id' => $user->id,
            'pengirim_type' => get_class($user),
            'penerima_id' => $request->penerima_id,
            'penerima_type' => $penerimaType,
            'isi_pesan' => $request->isi_pesan,
            'sudah_dibaca' => false,
        ]);

        return back();
    }

    private function getAuthenticatedUser()
    {
        if (Auth::guard('petani')->check()) return Auth::guard('petani')->user();
        if (Auth::guard('pembeli')->check()) return Auth::guard('pembeli')->user();
        abort(403);
    }
}
