<?php

namespace App\Services\WS;

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

class VisionService
{
    use DataTable;
    /**
     * Create a new class instance.
     */
    public function __construct(private Vision $vision)
    {
        //
    }

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

    public function create($data)
    {
        $vision = $this->vision->create([
            'name' => $data->name,
            'description' => $data->description
        ]);
        if ($data->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 detail($id)
    {
        return $this->vision->findOr($id, fn () => throw new Exception("Vision not found"));
    }

    public function update($id, $data)
    {
        $vision = $this->vision->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)
    {
        $visions = $this->vision->whereIn('id', $data['ids'])->get();
        foreach ($visions as $vision) {
            if ($vision->image && file_exists(public_path($vision->image_url))) {
                unlink(public_path($vision->image_url));
            }
            $vision->delete();
        }
    }
}
