<?php

namespace App\Services\WS;

use App\Models\WS\Slide;
use App\Traits\DataTable;
use Exception;
use Illuminate\Support\Facades\Storage;

class SlideService
{
    use DataTable;
    /**
     * Create a new class instance.
     */
    public function __construct(private Slide $slide)
    {
        //
    }

    public function datatable()
    {
        return $this->generate($this->slide->query());
    }

    public function create($data)
    {
        $slide = $this->slide->create([
            'name' => $data->name,
            'description' => $data->description
        ]);
        if ($data->image) {
            $ext = $data->image->getClientOriginalExtension();
            $fileName = 'slide-' . time() . '.' . $ext;
            Storage::disk('public')->putFileAs('website', $data->image, $fileName);
            $slide->image = $fileName;
            $slide->update();
        }
        return $slide;
    }

    public function detail($id)
    {
        return $this->slide->findOr($id, fn () => throw new Exception("Vision not found"));
    }

    public function update($id, $data)
    {
        $slide = $this->slide->findOr($id, fn () => throw new Exception("Vision not found"));
        $slide->update([
            'name'          => $data->name,
            'description'   => $data->description
        ]);

        if (request()->hasFile('image')) {
            if ($slide->image && file_exists(public_path('storage/website/' . $slide->image))) {
                unlink(public_path('storage/website/' . $slide->image));
            }
            $ext = $data->image->getClientOriginalExtension();
            $fileName = 'slide-' . time() . '.' . $ext;
            Storage::disk('public')->putFileAs('website', $data->image, $fileName);
            $slide->image = $fileName;
            $slide->update();
        }
        return $slide;
    }

    public function delete($data)
    {
        $slides = $this->slide->whereIn('id', $data['ids'])->get();
        foreach ($slides as $slide) {
            if ($slide->image && file_exists(public_path($slide->image_url))) {
                unlink(public_path($slide->image_url));
            }
            $slide->delete();
        }
    }
}
