<?php

namespace App\Services\WS;

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

class AboutUsService
{
    use DataTable;
    /**
     * Create a new class instance.
     */
    public function __construct(private AboutUs $aboutUs)
    {
        //
    }

    public function dataTable()
    {
        return $this->generate($this->aboutUs->query());
    }

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

    public function count()
    {
        return $this->aboutUs->count();
    }

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

    public function update($id, $data)
    {
        $aboutUs = $this->aboutUs->findOr($id,fn() => throw new Exception("Row not found"));
        $aboutUs->update([
            'name' => $data->name,
            'description' => $data->description
        ]);
        if (request()->hasFile('image')) {
            if($aboutUs->image && file_exists(public_path('storage/website/'.$aboutUs->image))){
                unlink(public_path('storage/website/'.$aboutUs->image));
            }
            $ext = $data->image->getClientOriginalExtension();
            $fileName = 'aboutus-' . time() . '.' . $ext;
            Storage::disk('public')->putFileAs('website', $data->image, $fileName);
            $aboutUs->image = $fileName;
            $aboutUs->update();
        }
        return $aboutUs;
    }
}
