<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ChatConversation;
use App\Models\ChatMessage;
use Illuminate\Http\Request;

class ChatController extends Controller
{
    /**
     * Customer's chat conversations.
     */
    public function conversations(Request $request)
    {
        $conversations = ChatConversation::where('customer_id', $request->user()->id)
            ->with(['lastMessage'])
            ->withCount(['messages as unread_count' => function ($q) {
                $q->where('is_read', false)->where('sender_type', 'admin');
            }])
            ->orderBy('updated_at', 'desc')
            ->get();

        return response()->json(['data' => $conversations]);
    }

    /**
     * Create a new conversation.
     */
    public function createConversation(Request $request)
    {
        $request->validate([
            'subject' => 'nullable|string|max:255',
            'message' => 'required|string|max:2000',
        ]);

        $conversation = ChatConversation::create([
            'customer_id' => $request->user()->id,
            'subject' => $request->subject ?? 'محادثة جديدة',
            'status' => 'open',
        ]);

        // Create the first message
        $message = ChatMessage::create([
            'chat_conversation_id' => $conversation->id,
            'sender_type' => 'customer',
            'sender_id' => $request->user()->id,
            'message' => $request->message,
        ]);

        $conversation->load(['messages', 'lastMessage']);

        return response()->json([
            'message' => 'تم إنشاء المحادثة',
            'data' => $conversation,
        ], 201);
    }

    /**
     * Messages in a conversation.
     */
    public function messages(Request $request, ChatConversation $conversation)
    {
        if ($conversation->customer_id !== $request->user()->id) {
            return response()->json(['message' => 'غير مصرح'], 403);
        }

        // Mark admin messages as read
        $conversation->messages()
            ->where('sender_type', 'admin')
            ->where('is_read', false)
            ->update(['is_read' => true]);

        $messages = $conversation->messages()
            ->orderBy('created_at', 'asc')
            ->paginate(50);

        return response()->json($messages);
    }

    /**
     * Send a message in a conversation.
     */
    public function sendMessage(Request $request, ChatConversation $conversation)
    {
        if ($conversation->customer_id !== $request->user()->id) {
            return response()->json(['message' => 'غير مصرح'], 403);
        }

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

        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('chat-attachments', 'public');
        }

        $message = ChatMessage::create([
            'chat_conversation_id' => $conversation->id,
            'sender_type' => 'customer',
            'sender_id' => $request->user()->id,
            'message' => $request->message,
            'attachment' => $attachmentPath,
        ]);

        // Update conversation timestamp
        $conversation->touch();

        if ($conversation->status === 'closed') {
            $conversation->update(['status' => 'open']);
        }

        return response()->json([
            'message' => 'تم إرسال الرسالة',
            'data' => $message,
        ], 201);
    }
}
