<?php

namespace App\Services\WS;

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

class MenuService
{
    use DataTable;
    /**
     * Create a new class instance.
     */
    public function __construct(private Menu $menu)
    {
        //
    }

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

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

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

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

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

    public function delete($data)
    {
        $services = $this->menu->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();
        }
    }
}
