<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use App\Models\ContactMessage;
use Illuminate\Http\Request;

class ChatController extends Controller
{
    /**
     * Ambil semua pesan chat user yang sedang login.
     * Jika belum ada percakapan, buat otomatis.
     */
    public function index(Request $request)
    {
        $user = $request->user();

        // Cari atau buat percakapan untuk user ini
        $contact = Contact::firstOrCreate(
            ['user_id' => $user->id],
            [
                'nama'     => $user->name,
                'whatsapp' => '-',
                'usaha'    => $user->umkm->nama_usaha ?? '-',
                'pesan'    => 'Chat dimulai',
                'status'   => 'open',
            ]
        );

        $messages = $contact->messages()->oldest()->get();

        return response()->json([
            'contact' => $contact,
            'messages' => $messages,
        ]);
    }

    /**
     * Kirim pesan baru dari user.
     */
    public function send(Request $request)
    {
        $user = $request->user();

        $validated = $request->validate([
            'message' => 'required|string|max:2000',
        ]);

        // Cari atau buat percakapan
        $contact = Contact::firstOrCreate(
            ['user_id' => $user->id],
            [
                'nama'     => $user->name,
                'whatsapp' => '-',
                'usaha'    => $user->umkm->nama_usaha ?? '-',
                'pesan'    => 'Chat dimulai',
                'status'   => 'open',
            ]
        );

        $contact->update(['status' => 'open']);

        $message = ContactMessage::create([
            'contact_id' => $contact->id,
            'sender'     => 'user',
            'message'    => $validated['message'],
        ]);

        return response()->json(['success' => true, 'data' => $message], 201);
    }
}
