<?php

namespace App\Http\Controllers;

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

class SupportController extends Controller
{
    /**
     * Daftar seluruh percakapan chat dari pengguna.
     */
    public function index(Request $request)
    {
        $query = Contact::with('user', 'messages')->latest();

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('nama', 'like', "%{$search}%")
                    ->orWhere('whatsapp', 'like', "%{$search}%")
                    ->orWhere('usaha', 'like', "%{$search}%");
            });
        }

        $contacts = $query->paginate(15);
        $openCount = Contact::where('status', 'open')->count();

        return view('support.index', compact('contacts', 'openCount'));
    }

    /**
     * Detail percakapan chat dengan admin.
     */
    public function show(Contact $contact)
    {
        $contact->load(['user', 'messages']);

        // Tandai semua pesan user sudah dibaca admin
        $contact->messages()
            ->where('sender', 'user')
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

        return view('support.show', compact('contact'));
    }

    /**
     * Admin membalas pesan chat. Pesan masuk ke tabel contact_messages.
     */
    public function reply(Request $request, Contact $contact)
    {
        $validated = $request->validate([
            'admin_reply' => 'required|string|max:5000',
        ]);

        // Simpan pesan admin ke chat thread
        ContactMessage::create([
            'contact_id' => $contact->id,
            'sender'     => 'admin',
            'message'    => $validated['admin_reply'],
        ]);

        $contact->update([
            'status'     => 'replied',
            'replied_at' => now(),
        ]);

        return redirect()
            ->route('support.show', $contact->id)
            ->with('success', 'Balasan berhasil dikirim ke chat.');
    }

    /**
     * Tandai percakapan sebagai selesai / ditutup.
     */
    public function close(Contact $contact)
    {
        $contact->update(['status' => 'closed']);

        return redirect()
            ->route('support.show', $contact->id)
            ->with('success', 'Pesan ditandai sebagai selesai.');
    }
}