<?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
{
    // Menampilkan Daftar Percakapan (Inbox Utama)
    public function index()
    {
        $user = $this->getAuthenticatedUser();
        $isPetani = Auth::guard('petani')->check();

        $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();

        // Kelompokkan berdasarkan ID Lawan Bicara
        $conversations = $allMessages->groupBy(function ($pesan) use ($user) {
            return $pesan->pengirim_id == $user->id
                ? $pesan->penerima_type . '_' . $pesan->penerima_id
                : $pesan->pengirim_type . '_' . $pesan->pengirim_id;
        });

        // Format data untuk view 
        $chatList = $conversations->map(function ($msgs) use ($user) {
            $lastMsg = $msgs->first();

            // Tentukan siapa lawan bicaranya
            if ($lastMsg->pengirim_id == $user->id) {
                $lawan = $lastMsg->penerima;
            } else {
                $lawan = $lastMsg->pengirim;
            }

            return [
                'lawan_id' => $lawan->id ?? 0,
                'lawan_type' => get_class($lawan ?? new \stdClass),
                '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('sudah_dibaca', false)->count()
            ];
        });

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

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

        // Tentukan model lawan bicara
        $lawanType = $isPetani ? Pembeli::class : Petani::class;
        $lawan = $lawanType::findOrFail($id);

        // Ambil percakapan antara User Login & Lawan Bicara
        $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 pesan masuk sebagai "Sudah 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';
        return view($view, compact('chats', 'lawan'));
    }

    // Proses Kirim Pesan 
    public function store(Request $request)
    {
        $request->validate(['isi_pesan' => 'required']);
        $user = $this->getAuthenticatedUser();
        $isPetani = Auth::guard('petani')->check();

        // Menentukan tipe penerima
        $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);
    }
}
