<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SupportMessage extends Model
{
    protected $fillable = [
        'ticket_id',
        'sender_type',
        'sender_id',
        'message',
        'image',
        'is_read'
    ];

    protected function casts(): array
    {
        return [
            'is_read' => 'boolean',
        ];
    }

    public function ticket(): BelongsTo
    {
        return $this->belongsTo(SupportTicket::class, 'ticket_id');
    }

    public function sender(): BelongsTo
    {
        return $this->belongsTo(User::class, 'sender_id');
    }

    public function getImageUrlAttribute(): ?string
    {
        if (!$this->image) {
            return null;
        }

        // If it's already a full URL, return as is
        if (filter_var($this->image, FILTER_VALIDATE_URL)) {
            return $this->image;
        }

        // Get base URL - prioritize request, then env, then default
        $baseUrl = null;
        
        // Method 1: Try to get from current request (most reliable)
        try {
            $request = request();
            if ($request && $request->getSchemeAndHttpHost()) {
                $baseUrl = $request->getSchemeAndHttpHost();
            }
        } catch (\Exception $e) {
            // Continue to next method
        }
        
        // Method 2: Use config with port detection
        if (!$baseUrl) {
            $configUrl = config('app.url', 'http://localhost');
            $baseUrl = rtrim($configUrl, '/');
            
            // If localhost without port, add port 8000 (Laravel default)
            if ($baseUrl === 'http://localhost' || $baseUrl === 'http://localhost/') {
                $baseUrl = 'http://localhost:8000';
            }
        }
        
        // Ensure image path format is correct
        // Database stores: support/{ticket_id}/{filename}
        // Need: storage/support/{ticket_id}/{filename}
        $imagePath = ltrim($this->image, '/');
        if (!str_starts_with($imagePath, 'storage/')) {
            $imagePath = 'storage/' . $imagePath;
        }
        
        // Return full URL: http://localhost:8000/storage/support/1/filename.jpg
        return rtrim($baseUrl, '/') . '/' . $imagePath;
    }
}

