<?php

namespace Modules\BuyFactor\Services;

use Modules\BuyFactor\Entities\BuyFactor;
use Modules\Supplier\Entities\Supplier;
use Symfony\Component\String\ByteString;

class BuyFactorService
{
    public function list()
    {
        $buy_factor=BuyFactor::query()->with('supplier')->orderByDesc('created_at')->paginate(30);
        return successResponse($buy_factor);
    }

    public function suppliersList()
    {
        $suppliers=Supplier::query()->orderByDesc('created_at')->get();
        return successResponse($suppliers);
    }


    public function add($request)
    {
        $products=json_decode($request->products);
        $total=0;
        $factor=new BuyFactor();
        $factor->supplier_id=$request->supplier_id;
        $factor->price=0;
        $factor->created_at = $request->created_at;
        $factor->description=$request->description;
        $factor->save();
        if (count($products) > 0){
            foreach ($products as $product){
                $factor->products()->create([
                    'name' => $product->name,
                    'count' => $product->count,
                    'price' => $product->price,
                    'total' => $product->price * $product->count
                ]);
                $total +=$product->price * $product->count;
            }
        }
        $factor->price=$total;
        $factor->save();
        return successResponse([]);
    }

    public function show($id)
    {
        $factor=BuyFactor::query()->with(['supplier','products'])->where('id',$id)->first();
        if (!$factor){
            return failedResponse('فاکتور یافت نشد',404);
        }

        return  successResponse(['factor'=>$factor]);
    }

    public function delete($id)
    {
        $factor=BuyFactor::query()->where('id',$id)->first();
        if (!$factor){
            return failedResponse('فاکتور یافت نشد',404);
        }
        $factor->delete();
        return  successResponse(['factor'=>$factor]);
    }

    public function edit($id,$request)
    {
        $factor=BuyFactor::query()->where('id',$id)->first();
        if (!$factor){
            return failedResponse('فاکتور یافت نشد',404);
        }
        $factor->price=$request->price;
        $factor->description=$request->description;
        $factor->save();
        return successResponse([]);
    }
}