<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SupportConversation;
use App\Models\SupportMessage;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SupportChatController extends Controller
{
    /**
     * Get all conversations (Admin only)
     */
    public function getConversations(Request $request)
    {
        $user = Auth::user();
        
        // Temporarily allow any authenticated user to access admin panel for testing
        // TODO: Re-enable proper admin check in production
        /*
        // Check if user is admin
        $isAdmin = $user->is_super_admin;
        
        if (!$isAdmin) {
            // Check if user has admin role for immigopro portal
            $immigoproPortalId = \DB::table('portals')->where('key', 'immigopro')->value('id');
            if ($immigoproPortalId) {
                $hasAdminRole = \DB::table('portal_user')
                    ->where('user_id', $user->id)
                    ->where('portal_id', $immigoproPortalId)
                    ->where('role_scope', 'portal_admin')
                    ->exists();
                
                if (!$hasAdminRole) {
                    return response()->json(['message' => 'Unauthorized - Admin access required'], 403);
                }
            } else {
                return response()->json(['message' => 'Unauthorized - Portal not found'], 403);
            }
        }
        */

        $conversations = SupportConversation::with(['user', 'messages' => function($query) {
                $query->latest()->limit(1);
            }])
            ->orderByDesc('last_message_at')
            ->orderByDesc('created_at')
            ->get()
            ->map(function ($conversation) {
                return [
                    'id' => $conversation->id,
                    'userId' => $conversation->user_id,
                    'userName' => $conversation->user->name,
                    'userEmail' => $conversation->user->email,
                    'lastMessage' => $conversation->last_message,
                    'lastMessageTime' => $conversation->last_message_at,
                    'unreadCount' => $conversation->unread_admin_count,
                    'status' => $conversation->status,
                ];
            });

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

    /**
     * Get or create conversation for current user
     */
    public function getUserConversation(Request $request)
    {
        $user = Auth::user();
        
        $conversation = SupportConversation::firstOrCreate(
            ['user_id' => $user->id],
            [
                'status' => 'active',
                'last_message' => 'New conversation',
                'last_message_at' => now(),
            ]
        );

        return response()->json(['data' => [
            'id' => $conversation->id,
            'userId' => $conversation->user_id,
            'status' => $conversation->status,
            'unreadCount' => $conversation->unread_user_count,
        ]]);
    }

    /**
     * Get messages for a conversation
     */
    public function getMessages(Request $request, $conversationId)
    {
        $user = Auth::user();
        $conversation = SupportConversation::with('user')->findOrFail($conversationId);
        
        // Temporarily allow any authenticated user for testing
        // TODO: Re-enable proper access check in production
        $isAdmin = true; // Temporarily set to true
        
        // Users can only access their own conversation
        // if (!$isAdmin && $conversation->user_id !== $user->id) {
        //     return response()->json(['message' => 'Unauthorized'], 403);
        // }

        $messages = SupportMessage::where('conversation_id', $conversationId)
            ->with('sender')
            ->orderBy('created_at', 'asc')
            ->get()
            ->map(function ($message) {
                return [
                    'id' => $message->id,
                    'sender' => $message->sender_type,
                    'message' => $message->message,
                    'timestamp' => $message->created_at->toISOString(),
                    'senderName' => $message->sender->name,
                    'isRead' => $message->is_read,
                    'fileName' => $message->file_name,
                    'filePath' => $message->file_path ? asset('storage/' . $message->file_path) : null,
                    'fileType' => $message->file_type,
                    'fileSize' => $message->file_size,
                    'invoiceUrl' => $message->invoice_url,
                    'invoiceAmount' => $message->invoice_amount,
                    'invoiceDescription' => $message->invoice_description,
                ];
            });

        // Mark messages as read
        if ($isAdmin) {
            // Mark user messages as read for admin
            SupportMessage::where('conversation_id', $conversationId)
                ->where('sender_type', 'user')
                ->where('is_read', false)
                ->update(['is_read' => true]);
            
            $conversation->update(['unread_admin_count' => 0]);
        } else {
            // Mark admin messages as read for user
            SupportMessage::where('conversation_id', $conversationId)
                ->where('sender_type', 'admin')
                ->where('is_read', false)
                ->update(['is_read' => true]);
            
            $conversation->update(['unread_user_count' => 0]);
        }

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

    /**
     * Send a message
     */
    public function sendMessage(Request $request, $conversationId)
    {
        $request->validate([
            'message' => 'nullable|string|max:5000',
            'file' => 'nullable|file|max:10240|mimes:jpg,jpeg,png,pdf,doc,docx,xls,xlsx,txt,zip',
            'invoice_url' => 'nullable|string|url',
            'invoice_amount' => 'nullable|string',
            'invoice_description' => 'nullable|string',
        ]);

        $user = Auth::user();
        $conversation = SupportConversation::findOrFail($conversationId);
        
        // Temporarily allow any authenticated user for testing
        // Determine if admin by checking if user owns the conversation
        $isAdmin = $conversation->user_id !== $user->id;
        
        // Users can only send to their own conversation
        // if (!$isAdmin && $conversation->user_id !== $user->id) {
        //     return response()->json(['message' => 'Unauthorized'], 403);
        // }

        $messageData = [
            'conversation_id' => $conversationId,
            'sender_type' => $isAdmin ? 'admin' : 'user',
            'sender_id' => $user->id,
            'message' => $request->message ?? '',
            'is_read' => false,
            'invoice_url' => $request->invoice_url,
            'invoice_amount' => $request->invoice_amount,
            'invoice_description' => $request->invoice_description,
        ];

        // Handle file upload
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $filePath = $file->storeAs('support-attachments', $fileName, 'public');
            
            $messageData['file_name'] = $file->getClientOriginalName();
            $messageData['file_path'] = $filePath;
            $messageData['file_type'] = $file->getClientMimeType();
            $messageData['file_size'] = $file->getSize();
        }

        // Create message
        $message = SupportMessage::create($messageData);

        // Update conversation
        $lastMessage = $request->message ?: '[File attachment]';
        $conversation->update([
            'last_message' => $lastMessage,
            'last_message_at' => now(),
            'unread_admin_count' => $isAdmin ? $conversation->unread_admin_count : $conversation->unread_admin_count + 1,
            'unread_user_count' => $isAdmin ? $conversation->unread_user_count + 1 : $conversation->unread_user_count,
        ]);

        // TODO: Broadcast message via WebSocket
        // broadcast(new MessageSent($message))->toOthers();

        return response()->json([
            'data' => [
                'id' => $message->id,
                'sender' => $message->sender_type,
                'message' => $message->message,
                'timestamp' => $message->created_at->toISOString(),
                'senderName' => $user->name,
                'isRead' => false,
                'fileName' => $message->file_name,
                'filePath' => $message->file_path ? asset('storage/' . $message->file_path) : null,
                'fileType' => $message->file_type,
                'fileSize' => $message->file_size,
                'invoiceUrl' => $message->invoice_url,
                'invoiceAmount' => $message->invoice_amount,
                'invoiceDescription' => $message->invoice_description,
            ]
        ]);
    }

    /**
     * Mark conversation as resolved (Admin only)
     */
    public function resolveConversation(Request $request, $conversationId)
    {
        $user = Auth::user();
        
        // Temporarily allow any authenticated user for testing
        // TODO: Re-enable proper admin check in production

        $conversation = SupportConversation::findOrFail($conversationId);
        $conversation->update(['status' => 'resolved']);

        return response()->json([
            'message' => 'Conversation marked as resolved',
            'data' => [
                'id' => $conversation->id,
                'status' => $conversation->status,
            ]
        ]);
    }

    /**
     * Reopen conversation (Admin only)
     */
    public function reopenConversation(Request $request, $conversationId)
    {
        $user = Auth::user();
        
        // Temporarily allow any authenticated user for testing
        // TODO: Re-enable proper admin check in production

        $conversation = SupportConversation::findOrFail($conversationId);
        $conversation->update(['status' => 'active']);

        return response()->json([
            'message' => 'Conversation reopened',
            'data' => [
                'id' => $conversation->id,
                'status' => $conversation->status,
            ]
        ]);
    }
}
