<?php

namespace Modules\Product\Services;

use Illuminate\Support\Facades\Storage;
use Modules\Product\Entities\Product;

class ProductService
{
    public function list()
    {
        $products=Product::query()->orderByDesc('created_at')->paginate(30);
        return successResponse($products);
    }

    public function add($request)
    {
        $product=new Product();
        $product->name=$request->name;
        $product->sell_price=$request->sell_price;
        $product->price=$request->price;
        $product->capacity=$request->capacity;
        $product->total_amount=$request->total_amount;
        if ($request->image){
                $image = $request->file('image');
                $name = $image->hashName(); // Generates a hashed name for the image
                $path = 'images/products'; // Directory path
                Storage::putFileAs($path, $image, $name); // Only pass the file name, not the full path
                $product->image = $path . '/' . $name; // Store the relative path in the database
        }
        $product->save();
        return successResponse([]);
    }

    public function show($id)
    {
        $product=Product::query()->where('id',$id)->first();
        if (!$product){
            return failedResponse('محصول مورد نظر یافت نشد',404);
        }
        return  successResponse(['product'=>$product]);
    }

    public function delete($id)
    {
        $product=Product::query()->where('id',$id)->first();
        if (!$product){
            return failedResponse('محصول مورد نظر یافت نشد',404);
        }
        $product->delete();
        return  successResponse([]);
    }

    public function changeCapacity($request,$id)
    {
        $product=Product::query()->where('id',$id)->first();
        if (!$product){
            return failedResponse('محصول مورد نظر یافت نشد',404);
        }

        $product->capacity=$request->capacity;
        $product->total_amount=$request->total_amount;
        $product->save();

        return  successResponse([]);
    }
}