<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;

class SitePaymentPopup extends Model
{
    use HasFactory;

    protected $fillable = [
        'site_id',
        'desktop_image_path',
        'mobile_image_path',
        'desktop_enabled',
        'mobile_enabled',
        'popup_click_url',
        'popup_footer_text',
        'popup_footer_url',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'desktop_enabled' => 'boolean',
        'mobile_enabled' => 'boolean',
    ];

    public function site()
    {
        return $this->belongsTo(Site::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function getDesktopImageUrlAttribute(): ?string
    {
        return $this->resolveImageUrl($this->desktop_image_path);
    }

    public function getMobileImageUrlAttribute(): ?string
    {
        return $this->resolveImageUrl($this->mobile_image_path);
    }

    private function resolveImageUrl(?string $path): ?string
    {
        $path = trim((string) $path);
        if ($path === '') {
            return null;
        }

        if (preg_match('/^https?:\/\//i', $path)) {
            return $path;
        }

        $relativePath = ltrim($path, '/');
        if (str_starts_with($relativePath, 'storage/')) {
            return '/' . $relativePath;
        }

        if (File::exists(public_path($relativePath))) {
            return '/' . $relativePath;
        }

        // Backward compatibility: migrate old storage/app/public file to public/ on first read.
        $legacyStorageFile = storage_path('app/public/' . $relativePath);
        if (File::exists($legacyStorageFile)) {
            $publicFile = public_path($relativePath);
            $publicDirectory = dirname($publicFile);
            if (!File::exists($publicDirectory)) {
                File::makeDirectory($publicDirectory, 0755, true);
            }
            if (!File::exists($publicFile)) {
                File::copy($legacyStorageFile, $publicFile);
            }

            return '/' . $relativePath;
        }

        return '/' . $relativePath;
    }
}
