<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\FundingChat;
use App\Models\FundingMessage;
use App\Models\Funding;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class FundingChatController extends Controller
{
    /**
     * Get available payment methods.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPaymentMethods()
    {
        $paymentMethods = [
            'Bank Transfer',
            'PayPal',
            'Wise',
            'Credit Card',
            'Cryptocurrency'
        ];

        return response()->json([
            'status' => 'success',
            'payment_methods' => $paymentMethods
        ]);
    }

    /**
     * Start a new chat.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function startChat(Request $request)
    {
        $request->validate([
            'payment_method' => 'required|string',
            'funding_id' => 'nullable|exists:fundings,id'
        ]);

        $chat = FundingChat::create([
            'user_id' => Auth::id(),
            'payment_method' => $request->payment_method,
            'status' => 'pending',
            'funding_id' => $request->funding_id
        ]);

        // If this chat is linked to a funding, add a system message
        if ($request->funding_id) {
            $funding = Funding::find($request->funding_id);
            
            // Create a system message
            FundingMessage::create([
                'chat_id' => $chat->id,
                'sender_id' => null, // Null sender indicates system message
                'message' => 'Transaction has been initiated. You can chat with the other party here.',
                'is_system' => true
            ]);

            // Update the funding with the chat ID
            $funding->chat_id = $chat->id;
            $funding->save();
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Chat started successfully',
            'chat_id' => $chat->id
        ]);
    }

    /**
     * Get a chat by funding ID.
     *
     * @param  int  $fundingId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getChatByFunding($fundingId)
    {
        $chat = FundingChat::where('funding_id', $fundingId)->first();

        if (!$chat) {
            return response()->json([
                'status' => 'error',
                'message' => 'No chat found for this funding'
            ], 404);
        }

        return response()->json([
            'status' => 'success',
            'chat_id' => $chat->id
        ]);
    }

    /**
     * Send a new message in a chat.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendMessage(Request $request)
    {
        $request->validate([
            'chat_id' => 'required|exists:funding_chats,id',
            'message' => 'required|string',
            'is_system' => 'nullable|boolean'
        ]);

        $message = FundingMessage::create([
            'chat_id' => $request->chat_id,
            'sender_id' => $request->is_system ? null : Auth::id(),
            'message' => $request->message,
            'is_system' => $request->is_system ?? false
        ]);

        return response()->json([
            'status' => 'success',
            'message' => 'Message sent successfully'
        ]);
    }

    /**
     * Get messages from a chat.
     *
     * @param  int  $chatId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getChatMessages($chatId)
    {
        $messages = FundingMessage::where('chat_id', $chatId)
            ->orderBy('created_at', 'asc')
            ->get()
            ->map(function($message) {
                return [
                    'message' => $message->message,
                    'sender' => $message->sender_id === Auth::id() ? 'user' : ($message->is_system ? 'system' : 'admin'),
                    'direction' => $message->sender_id === Auth::id() ? 'outgoing' : 'incoming',
                    'is_system' => (bool) $message->is_system,
                    'created_at' => $message->created_at
                ];
            });

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

    /**
     * Get chat message count for a funding ID.
     *
     * @param  int  $fundingId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getChatCount($fundingId)
    {
        $chat = FundingChat::where('funding_id', $fundingId)->first();
        $count = 0;
        
        if ($chat) {
            $count = FundingMessage::where('chat_id', $chat->id)->count();
        }

        return response()->json([
            'status' => 'success',
            'count' => $count,
            'chat_id' => $chat ? $chat->id : null
        ]);
    }

    /**
     * Get chat details for admin view.
     *
     * @param  int  $chatId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminChatDetails($chatId)
    {
        $chat = FundingChat::with(['funding', 'user'])->find($chatId);
        
        if (!$chat) {
            return response()->json([
                'status' => 'error',
                'message' => 'Chat not found'
            ], 404);
        }

        $messages = FundingMessage::where('chat_id', $chatId)
            ->with('sender')
            ->orderBy('created_at', 'asc')
            ->get()
            ->map(function($message) {
                return [
                    'id' => $message->id,
                    'message' => $message->message,
                    'sender_name' => $message->sender ? $message->sender->name : 'System',
                    'sender_id' => $message->sender_id,
                    'is_system' => (bool) $message->is_system,
                    'created_at' => $message->created_at,
                    'time' => $message->created_at->format('h:i A'),
                    'date' => $message->created_at->format('M d, Y')
                ];
            });

        $fundingDetails = null;
        if ($chat->funding) {
            $fundingDetails = [
                'id' => $chat->funding->id,
                'amount' => $chat->funding->amount,
                'status' => $chat->funding->status,
                'created_at' => $chat->funding->created_at->format('M d, Y')
            ];
        }

        return response()->json([
            'status' => 'success',
            'chat' => [
                'id' => $chat->id,
                'payment_method' => $chat->payment_method,
                'status' => $chat->status,
                'created_at' => $chat->created_at->format('M d, Y'),
                'user' => $chat->user ? [
                    'id' => $chat->user->id,
                    'name' => $chat->user->name,
                    'email' => $chat->user->email
                ] : null,
                'funding' => $fundingDetails
            ],
            'messages' => $messages
        ]);
    }

    /**
     * Send a message as admin.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendAdminMessage(Request $request)
    {
        $request->validate([
            'chat_id' => 'required|exists:funding_chats,id',
            'message' => 'required|string'
        ]);

        $message = FundingMessage::create([
            'chat_id' => $request->chat_id,
            'sender_id' => Auth::id(),
            'message' => $request->message,
            'is_system' => false
        ]);

        return response()->json([
            'status' => 'success',
            'message' => 'Message sent successfully',
            'message_details' => [
                'id' => $message->id,
                'message' => $message->message,
                'sender_name' => Auth::user()->name,
                'sender_id' => Auth::id(),
                'is_system' => false,
                'created_at' => $message->created_at,
                'time' => $message->created_at->format('h:i A'),
                'date' => $message->created_at->format('M d, Y')
            ]
        ]);
    }
} 