<?php

namespace App\Http\Controllers;

use App\Models\SupportConversation;
use App\Models\SupportMessage;
use App\Services\NotificationService;
use Illuminate\Http\Request;

class SupportController extends Controller
{
    public function startChat(Request $request)
    {
        $request->validate([
            'service' => 'required|string',
            'message' => 'required|string',
            'name' => 'required|string',
            'email_phone' => 'required|string',
        ]);

        $conversation = SupportConversation::create([
            'user_id' => auth()->id(),
            'name' => $request->name,
            'email_phone' => $request->email_phone,
            'subject_service' => $request->service,
            'status' => 'open',
            'customer_last_seen_at' => now(),
        ]);

        $conversation->messages()->create([
            'sender_type' => 'customer',
            'message' => $request->message,
        ]);

        NotificationService::notifyAdmins(
            'New live chat',
            "{$conversation->name} started a chat about {$conversation->subject_service}. Contact: {$conversation->email_phone}",
            url("/admin/support-conversations/{$conversation->id}"),
            'warning',
            true
        );

        return response()->json([
            'success' => true,
            'conversation_id' => $conversation->id,
            'message' => 'Message sent successfully! We will connect with you shortly.',
        ]);
    }

    public function getMessages($id)
    {
        SupportConversation::whereKey($id)->update([
            'customer_last_seen_at' => now(),
        ]);

        $messages = SupportMessage::where('support_conversation_id', $id)
            ->orderBy('created_at', 'asc')
            ->get();
            
        return response()->json(['success' => true, 'messages' => $messages]);
    }

    public function reply(Request $request, $id)
    {
        $request->validate(['message' => 'required|string']);

        $conversation = SupportConversation::findOrFail($id);
        $conversation->update([
            'customer_last_seen_at' => now(),
            'status' => 'open',
        ]);
        
        $message = SupportMessage::create([
            'support_conversation_id' => $id,
            'sender_type' => 'customer',
            'message' => $request->message,
        ]);

        NotificationService::notifyAdmins(
            'Customer replied',
            "{$conversation->name} replied in {$conversation->subject_service}.",
            url("/admin/support-conversations/{$conversation->id}"),
            'info',
            true
        );

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

    public function adminReply(Request $request, SupportConversation $conversation)
    {
        abort_unless(auth()->check() && auth()->user()->role === 'admin', 403);

        $request->validate(['message' => 'required|string']);

        $conversation->messages()->create([
            'sender_type' => 'staff',
            'message' => $request->message,
        ]);

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

        return back()->with('status', 'Reply sent.');
    }
}
