<?php

namespace App\Services\WS;

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

class ServiceService
{
    use DataTable;
    /**
     * Create a new class instance.
     */
    public function __construct(private Service $service)
    {
        //
    }

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

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

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

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

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

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