<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\SupportTicket;
use App\Models\SupportMessage;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class SupportController extends Controller
{
    /**
     * Get base URL with correct port for image URLs
     */
    private function getBaseUrl(Request $request): string
    {
        $baseUrl = $request->getSchemeAndHttpHost();
        
        // For localhost, ensure port 8000 is included
        if (str_contains($baseUrl, 'localhost')) {
            // Check if port is missing
            $parsed = parse_url($baseUrl);
            if (!isset($parsed['port'])) {
                $baseUrl = 'http://localhost:8000';
            }
        }
        
        return rtrim($baseUrl, '/');
    }
    
    public function getMessages(Request $request)
    {
        $user = $request->user();

        // Get user's latest ticket (any status) so history is never lost; create only if none exists
        $ticket = SupportTicket::where('user_id', $user->id)
            ->orderByRaw('COALESCE(last_message_at, created_at) DESC')
            ->first();

        if (!$ticket) {
            $ticket = SupportTicket::create([
                'user_id' => $user->id,
                'status' => 'open',
                'priority' => 'medium',
            ]);
        }

        // Ensure greeting message exists
        $greetingExists = SupportMessage::where('ticket_id', $ticket->id)
            ->where('sender_type', 'system')
            ->where('message', 'Hello, may I help you?')
            ->exists();

        if (!$greetingExists) {
            SupportMessage::create([
                'ticket_id' => $ticket->id,
                'sender_type' => 'system',
                'message' => 'Hello, may I help you?',
                'is_read' => true,
            ]);
        }

        // Mark all messages as read when user opens chat
        SupportMessage::where('ticket_id', $ticket->id)
            ->where('is_read', false)
            ->update(['is_read' => true]);

        // Get all messages
        $baseUrl = $this->getBaseUrl($request);
        
        $messages = SupportMessage::where('ticket_id', $ticket->id)
            ->orderBy('created_at', 'asc')
            ->get()
            ->map(function ($message) use ($baseUrl) {
                $imageUrl = null;
                if ($message->image) {
                    // Skip if image path contains placeholders (invalid data)
                    if (str_contains($message->image, '{ticket_id}') || str_contains($message->image, '{filename}')) {
                        // Invalid placeholder data - skip image URL generation
                        $imageUrl = null;
                    } else {
                        // Check if file actually exists before generating URL
                        $imagePath = ltrim($message->image, '/');
                        $fullPath = storage_path('app/public/' . $imagePath);
                        
                        // Only include image URL if file exists
                        if (file_exists($fullPath)) {
                            if (!str_starts_with($imagePath, 'storage/')) {
                                $imagePath = 'storage/' . $imagePath;
                            }
                            $imageUrl = rtrim($baseUrl, '/') . '/' . $imagePath;
                        }
                        // If file doesn't exist, imageUrl remains null (won't cause 404 errors)
                    }
                }
                
                return [
                    'id' => $message->id,
                    'sender_type' => $message->sender_type,
                    'message' => $message->message,
                    'image' => $imageUrl, // null if file doesn't exist
                    'created_at' => $message->created_at->toISOString(),
                ];
            });

        return response()->json([
            'success' => true,
            'messages' => $messages,
            'ticket_id' => $ticket->id,
        ]);
    }

    public function getUnreadCount(Request $request)
    {
        $user = $request->user();

        $ticket = SupportTicket::where('user_id', $user->id)
            ->orderByRaw('COALESCE(last_message_at, created_at) DESC')
            ->first();

        if (!$ticket) {
            return response()->json([
                'success' => true,
                'unread_count' => 0,
            ]);
        }

        // Count unread messages (admin/system messages that user hasn't read)
        $unreadCount = SupportMessage::where('ticket_id', $ticket->id)
            ->whereIn('sender_type', ['admin', 'system'])
            ->where('is_read', false)
            ->count();

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

    public function sendMessage(Request $request)
    {
        $user = $request->user();
        \Illuminate\Support\Facades\Log::info('Support sendMessage', [
            'has_file' => $request->hasFile('image'),
            'content_type' => $request->header('Content-Type'),
        ]);

        $request->validate([
            'message' => 'nullable|string|max:5000',
            'image' => 'nullable|image|max:5120', // 5MB max
        ]);

        if (empty(trim($request->message ?? '')) && !$request->hasFile('image')) {
            \Illuminate\Support\Facades\Log::warning('Support sendMessage: no message and no image');
            return response()->json([
                'success' => false,
                'message' => 'Please provide a message or image'
            ], 422);
        }

        // Get user's latest ticket (any status) so messages stay in one thread; create only if none
        $ticket = SupportTicket::where('user_id', $user->id)
            ->orderByRaw('COALESCE(last_message_at, created_at) DESC')
            ->first();

        if (!$ticket) {
            $ticket = SupportTicket::create([
                'user_id' => $user->id,
                'status' => 'open',
                'priority' => 'medium',
            ]);
        }

        // Reopen if closed so user can continue the same thread
        if ($ticket->status !== 'open' && $ticket->status !== 'pending') {
            $ticket->update(['status' => 'open']);
        }

        // Handle image upload
        $imagePath = null;
        if ($request->hasFile('image')) {
            try {
                $image = $request->file('image');
                
                // Validate image
                if (!$image->isValid()) {
                    \Illuminate\Support\Facades\Log::error('Image upload error: Invalid file');
                    return response()->json([
                        'success' => false,
                        'message' => 'Invalid image file. Please try again.'
                    ], 422);
                }
                
                // Ensure directory exists using Laravel's Storage facade
                $directory = 'public/support/' . $ticket->id;
                Storage::makeDirectory($directory, 0755, true);
                
                // Generate unique filename
                $uuid = Str::uuid();
                $extension = $image->getClientOriginalExtension();
                $filename = 'support/' . $ticket->id . '/' . $uuid . '.' . $extension;
                
                // Store file using Storage facade directly
                $storedPath = Storage::disk('public')->putFileAs(
                    'support/' . $ticket->id,
                    $image,
                    $uuid . '.' . $extension
                );
                
                // Verify file was stored
                if (!$storedPath || !Storage::disk('public')->exists($storedPath)) {
                    \Illuminate\Support\Facades\Log::error('Image upload error: File not stored. Path: ' . ($storedPath ?? 'null'));
                    return response()->json([
                        'success' => false,
                        'message' => 'Failed to save image. Please try again.'
                    ], 500);
                }
                
                // Get relative path for database (without 'public/' prefix)
                $imagePath = $storedPath; // Storage::disk('public') already returns path without 'public/' prefix
                
                // Verify file actually exists on disk
                $fullPath = storage_path('app/public/' . $imagePath);
                if (!file_exists($fullPath)) {
                    \Illuminate\Support\Facades\Log::error('Image upload error: File not found on disk. Full path: ' . $fullPath);
                    return response()->json([
                        'success' => false,
                        'message' => 'Failed to save image. Please try again.'
                    ], 500);
                }
                
                \Illuminate\Support\Facades\Log::info('Image uploaded successfully: ' . $imagePath . ' | Full path: ' . $fullPath . ' | Size: ' . filesize($fullPath) . ' bytes');
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Image upload error: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to upload image: ' . $e->getMessage()
                ], 500);
            }
        }

        // Create message (preserve emojis and special characters)
        try {
            $message = SupportMessage::create([
                'ticket_id' => $ticket->id,
                'sender_type' => 'user',
                'sender_id' => $user->id,
                'message' => $request->message ?: null,
                'image' => $imagePath,
                'is_read' => false,
            ]);

            // Update ticket last message time and ensure open
            $ticket->update([
                'last_message_at' => now(),
                'status' => 'open',
            ]);

            // Generate image URL with correct base URL from request
            $baseUrl = $this->getBaseUrl($request);
            
            $imageUrl = null;
            if ($message->image) {
                // Skip if image path contains placeholders (invalid data)
                if (str_contains($message->image, '{ticket_id}') || str_contains($message->image, '{filename}')) {
                    // Invalid placeholder data - skip image URL generation
                    $imageUrl = null;
                } else {
                    // Get image path from database (format: support/{ticket_id}/{filename})
                    $dbImagePath = ltrim($message->image, '/');
                    // Add storage/ prefix for URL (format: storage/support/{ticket_id}/{filename})
                    if (!str_starts_with($dbImagePath, 'storage/')) {
                        $dbImagePath = 'storage/' . $dbImagePath;
                    }
                    // Generate full URL: http://localhost:8000/storage/support/1/filename.jpg
                    $imageUrl = rtrim($baseUrl, '/') . '/' . $dbImagePath;
                }
            }
            
            \Illuminate\Support\Facades\Log::info('Support message sent', [
                'ticket_id' => $ticket->id,
                'user_id' => $user->id,
                'message_id' => $message->id,
            ]);
            return response()->json([
                'success' => true,
                'message' => [
                    'id' => $message->id,
                    'sender_type' => $message->sender_type,
                    'message' => $message->message,
                    'image' => $imageUrl,
                    'created_at' => $message->created_at->toISOString(),
                ],
            ]);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Support message creation failed', [
                'ticket_id' => $ticket->id ?? null,
                'user_id' => $user->id,
                'error' => $e->getMessage(),
            ]);
            return response()->json([
                'success' => false,
                'message' => 'Failed to send message. Please try again.'
            ], 500);
        }
    }
}

