<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class Slider extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'title',
        'image_source',
        'image_path',
        'image_filename',
        'image_size',
        'image_mime_type',
        'status',
        'order',
    ];

    protected $casts = [
        'order'  => 'integer',
        'status' => 'string',
        'image_source' => 'string',
        'image_size' => 'integer',
    ];

    /**
     * Scope: only published sliders, ordered by `order` ascending.
     */
    public function scopePublished(Builder $query): Builder
    {
        return $query->where('status', 'published')->orderBy('order', 'asc');
    }

    /**
     * Scope: filter by image source type
     */
    public function scopeByImageSource(Builder $query, string $source): Builder
    {
        return $query->where('image_source', $source);
    }

    /**
     * Scope: filter by status
     */
    public function scopeByStatus(Builder $query, string $status): Builder
    {
        return $query->where('status', $status);
    }

    /**
     * Get the public URL of the image
     * @return string
     */
    public function getImageUrl(): string
    {
        if ($this->image_source === 'upload') {
            // Return the public URL for uploaded files
            return Storage::disk('public')->url($this->image_path);
        }

        // Return the URL as-is for external URLs
        return $this->image_path;
    }

    /**
     * Check if image is an uploaded file
     */
    public function isUploadedImage(): bool
    {
        return $this->image_source === 'upload';
    }

    /**
     * Check if image is an external URL
     */
    public function isExternalImage(): bool
    {
        return $this->image_source === 'url';
    }

    /**
     * Get formatted file size (for uploaded images)
     */
    public function getFormattedFileSize(): ?string
    {
        if (!$this->image_size) {
            return null;
        }

        $bytes = $this->image_size;
        $units = ['B', 'KB', 'MB', 'GB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= (1 << (10 * $pow));

        return round($bytes, 2) . ' ' . $units[$pow];
    }

    /**
     * Delete uploaded image file from storage
     */
    public function deleteImageFile(): bool
    {
        if ($this->isUploadedImage() && $this->image_path) {
            try {
                return Storage::disk('public')->delete($this->image_path);
            } catch (\Exception $e) {
                \Log::error('Failed to delete slider image: ' . $e->getMessage());
                return false;
            }
        }

        return true;
    }

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        // Clean up uploaded image file when slider is deleted
        static::deleting(function ($slider) {
            if ($slider->isUploadedImage()) {
                $slider->deleteImageFile();
            }
        });
    }
}

