<?php

namespace App\Services;

use App\Models\Slider;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class SliderService
{
    private const UPLOAD_DISK = 'public';
    private const UPLOAD_PATH = 'sliders';

    /**
     * Return all published sliders ordered by `order` ascending.
     * Used by the homepage to populate the hero slider.
     */
    public function getPublished(): Collection
    {
        return Slider::published()->get();
    }

    /**
     * Return all sliders ordered by `order` ascending.
     * Used by the admin index listing.
     */
    public function getAll(): Collection
    {
        return Slider::orderBy('order', 'asc')->get();
    }

    /**
     * Create a new Slider record with file upload support
     */
    public function create(array $data): Slider
    {
        $data['title'] = strip_tags($data['title'] ?? '');

        // Handle image upload or URL
        $data = $this->processImageData($data);

        return Slider::create($data);
    }

    /**
     * Update an existing Slider record with file upload support
     */
    public function update(Slider $slider, array $data): Slider
    {
        if (isset($data['title'])) {
            $data['title'] = strip_tags($data['title']);
        }

        // Handle image upload or URL
        $data = $this->processImageData($data, $slider);

        $slider->update($data);

        return $slider->fresh();
    }

    /**
     * Delete a Slider record permanently
     */
    public function delete(Slider $slider): bool
    {
        // Delete uploaded image file if exists
        if ($slider->isUploadedImage()) {
            $slider->deleteImageFile();
        }

        return (bool) $slider->delete();
    }

    /**
     * Process image data - handle file uploads and URLs
     */
    private function processImageData(array $data, ?Slider $existingSlider = null): array
    {
        $imageSource = $data['image_source'] ?? 'url';

        if ($imageSource === 'upload') {
            if (isset($data['image_file']) && $data['image_file'] instanceof UploadedFile) {
                // Delete old uploaded file if updating
                if ($existingSlider && $existingSlider->isUploadedImage()) {
                    $existingSlider->deleteImageFile();
                }

                // Upload new file
                $uploadedFile = $data['image_file'];
                $filename = $uploadedFile->hashName('sliders');
                $path = $uploadedFile->storeAs('sliders', $filename, self::UPLOAD_DISK);

                $data['image_path'] = $path;
                $data['image_filename'] = $uploadedFile->getClientOriginalName();
                $data['image_size'] = $uploadedFile->getSize();
                $data['image_mime_type'] = $uploadedFile->getMimeType();
            } elseif ($existingSlider && $existingSlider->isUploadedImage()) {
                // Keep existing file if no new file provided during update
                $data['image_path'] = $existingSlider->image_path;
                $data['image_filename'] = $existingSlider->image_filename;
                $data['image_size'] = $existingSlider->image_size;
                $data['image_mime_type'] = $existingSlider->image_mime_type;
            }

            // Remove image_file from data as it's processed
            unset($data['image_file'], $data['image_url']);

        } else {
            // URL mode
            // Delete old uploaded file if switching from upload to URL
            if ($existingSlider && $existingSlider->isUploadedImage()) {
                $existingSlider->deleteImageFile();
            }

            $data['image_path'] = $data['image_url'] ?? '';
            $data['image_filename'] = null;
            $data['image_size'] = null;
            $data['image_mime_type'] = null;

            // Remove file-related fields
            unset($data['image_file']);
        }

        return $data;
    }

    /**
     * Get all sliders with filtering and pagination
     */
    public function getAllWithFilters($status = null, $source = null): Collection
    {
        $query = Slider::query();

        if ($status && in_array($status, ['published', 'draft', 'archived'])) {
            $query->byStatus($status);
        }

        if ($source && in_array($source, ['upload', 'url'])) {
            $query->byImageSource($source);
        }

        return $query->orderBy('order', 'asc')->get();
    }
}
