<?php

namespace App\Http\Controllers;

use App\Models\Message;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class ChatController extends Controller
{
    public function index()
    {
        $my_id = Auth::id();
        $me = Auth::user();
        
        $users = User::where('id', '!=', $my_id)->orderBy('username', 'asc')->get();
        
        return view('chat.index', compact('me', 'users'));
    }

    public function fetchMessages(Request $request)
    {
        $outgoing_id = Auth::id();
        $receiver_id = $request->receiver_id;

        if (!$receiver_id) {
            return "<div class='text-center text-gray-400 mt-10 text-xs'>Pilih teman untuk memulai chat</div>";
        }

        $incoming_id = $receiver_id;
        $output = "";

        $messages = Message::with('repliedMessage')
            ->where(function ($query) use ($outgoing_id, $incoming_id) {
                $query->where('sender_id', $outgoing_id)->where('receiver_id', $incoming_id);
            })
            ->orWhere(function ($query) use ($outgoing_id, $incoming_id) {
                $query->where('sender_id', $incoming_id)->where('receiver_id', $outgoing_id);
            })
            ->orderBy('created_at', 'asc')
            ->get();

        if ($messages->count() > 0) {
            foreach ($messages as $row) {
                $waktu = $row->created_at->format('H:i');
                $msg_id = $row->id;
                $raw_msg = $row->msg;
                $reply_to = $row->reply_to;
                $is_edited = $row->is_edited;

                // --- 1. LOGIKA TAMPILAN BALASAN (REPLY QUOTE) ---
                $reply_html = "";
                if ($reply_to && $row->repliedMessage) {
                    $reply_text = $row->repliedMessage->msg;
                    
                    if (strpos($reply_text, '[IMAGE]:') === 0) $reply_text = "📷 Gambar";
                    elseif (strpos($reply_text, '[FILE]:') === 0) $reply_text = "📁 Dokumen";
                    
                    $short_reply = (mb_strlen($reply_text) > 100) ? mb_substr($reply_text, 0, 100) . "..." : $reply_text;
                    
                    $reply_html = '
                    <div class="bg-black/10 border-l-4 border-teal-400 p-2 mb-2 rounded text-[11px] text-gray-200 italic opacity-80 leading-snug break-words">
                        ' . htmlspecialchars($short_reply) . '
                    </div>';
                }

                // --- 3. LOGIKA DETEKSI KONTEN (TEKS / GAMBAR / FILE) ---
                if (strpos($raw_msg, '[IMAGE]:') === 0) {
                    $img_name = str_replace('[IMAGE]:', '', $raw_msg);
                    $content = '<img src="'.asset('uploads/'.$img_name).'" class="rounded-lg max-w-full h-auto mt-1 cursor-pointer" onclick="window.open(this.src)">';
                    $is_file = true;
                } elseif (strpos($raw_msg, '[FILE]:') === 0) {
                    $file_name = str_replace('[FILE]:', '', $raw_msg);
                    $content = '<a href="'.asset('uploads/'.$file_name).'" target="_blank" class="flex items-center gap-2 bg-black/10 p-2 rounded-xl text-xs">
                                    <i class="fa-solid fa-file-lines text-lg"></i>
                                    <span class="truncate w-32">'. htmlspecialchars($file_name) .'</span>
                                </a>';
                    $is_file = true;
                } else {
                    $content = '<p class="text-[13px] md:text-sm leading-relaxed mb-1 pr-2">'. htmlspecialchars($raw_msg) .'</p>';
                    $is_file = false;
                }

                $js_msg = (!$is_file) ? addslashes(htmlspecialchars($raw_msg)) : "";

                // --- 4. RENDER BUBBLE CHAT ---
                if ($row->sender_id == $outgoing_id) {
                    // Bubble Kanan (Saya)
                    $output .= '
                    <div class="flex justify-end mb-3">
                        <div class="bg-teal-600 text-white p-3 rounded-2xl rounded-tr-none max-w-[85%] md:max-w-[70%] shadow-sm relative cursor-pointer active:scale-95 transition-transform"
                             onclick="showMsgOptions(\''.$msg_id.'\', \''.$js_msg.'\')">
                            ' . $reply_html . '
                            ' . $content . '
                            <div class="flex items-center justify-end gap-1 mt-1">
                                '.($is_edited && !$is_file ? '<span class="text-[9px] opacity-60 italic">diedit</span>' : '').'
                                <span class="text-[10px] opacity-70">'. $waktu .'</span>
                            </div>
                        </div>
                    </div>';
                } else {
                    // Bubble Kiri (Lawan)
                    $reply_html_left = str_replace('text-gray-200', 'text-gray-500', $reply_html);
                    $output .= '
                    <div class="flex justify-start mb-3">
                        <div class="bg-white text-gray-800 p-3 rounded-2xl rounded-tl-none max-w-[85%] md:max-w-[70%] shadow-sm relative border border-gray-100 cursor-pointer active:scale-95 transition-transform"
                             onclick="showMsgOptions(\''.$msg_id.'\', \''.$js_msg.'\')">
                            ' . $reply_html_left . '
                            ' . $content . '
                            <div class="flex items-center justify-end gap-1 mt-1">
                                '.($is_edited && !$is_file ? '<span class="text-[9px] text-gray-400 italic">diedit</span>' : '').'
                                <span class="text-[10px] text-gray-400">'. $waktu .'</span>
                            </div>
                        </div>
                    </div>';
                }
            }
        } else {
            $output .= '<div class="flex flex-col items-center justify-center h-full opacity-30 mt-20">
                            <i class="fa-solid fa-comments text-5xl mb-2"></i>
                            <p class="text-xs">Belum ada pesan. Sapa temanmu!</p>
                        </div>';
        }

        return $output;
    }

    public function sendMessage(Request $request)
    {
        $request->validate([
            'receiver_id' => 'required',
            'message' => 'required'
        ]);

        Message::create([
            'sender_id' => Auth::id(),
            'receiver_id' => $request->receiver_id,
            'msg' => $request->message,
            'reply_to' => $request->reply_id ?: null,
        ]);

        return response()->json(['status' => 'success']);
    }

    public function editMessage(Request $request)
    {
        $message = Message::where('id', $request->msg_id)->where('sender_id', Auth::id())->first();
        if ($message) {
            $message->msg = $request->new_msg;
            $message->is_edited = true;
            $message->save();
            return response()->json(['status' => 'success']);
        }
        return response()->json(['status' => 'error'], 403);
    }

    public function deleteMessage(Request $request)
    {
        $message = Message::where('id', $request->msg_id)->where('sender_id', Auth::id())->first();
        if ($message) {
            $message->delete();
            return response()->json(['status' => 'success']);
        }
        return response()->json(['status' => 'error'], 403);
    }

    public function uploadFile(Request $request)
    {
        $request->validate([
            'file' => 'required|file',
            'receiver_id' => 'required',
            'type' => 'required'
        ]);

        $file = $request->file('file');
        $fileName = time() . "_" . $file->getClientOriginalName();
        $file->move(public_path('uploads'), $fileName);

        $msg_content = ($request->type === 'image') ? "[IMAGE]:".$fileName : "[FILE]:".$fileName;

        Message::create([
            'sender_id' => Auth::id(),
            'receiver_id' => $request->receiver_id,
            'msg' => $msg_content
        ]);

        return response()->json(['status' => 'success']);
    }

    public function updateProfile(Request $request)
    {
        $user = Auth::user();

        if ($request->filled('nama_lengkap')) {
            $user->nama_lengkap = $request->nama_lengkap;
        }

        if ($request->filled('password')) {
            $user->password = Hash::make($request->password);
        }

        if ($request->hasFile('avatar')) {
            $file = $request->file('avatar');
            $fileName = time() . "_" . $file->getClientOriginalName();
            $file->move(public_path('uploads'), $fileName);
            $user->avatar = $fileName;
        }

        $user->save();

        return response()->json(['status' => 'success', 'avatar' => asset('uploads/'.$user->avatar)]);
    }

    public function surprise()
    {
        return view('surprise');
    }
}
