<?php

namespace Modules\Factor\Services;

use Modules\Factor\Entities\Factor;
use Modules\Factor\Transformers\ChequeFactorsListResource;
use Modules\Product\Entities\Product;

class FactorService
{
    public function list()
    {
        $factors=Factor::query()->with('customer')->orderByDesc('created_at')->paginate(30);
        return successResponse($factors);
    }

    public function chequeFactors()
    {
        $factors=Factor::query()->with('customer')->where('debt','!=','0')->orderByDesc('created_at')->get();
        return successResponse(ChequeFactorsListResource::collection($factors));
    }
    public function factorProducts()
    {
        $products=Product::query()->orderByDesc('created_at')->select('id','name')->get();
        return successResponse($products);
    }

    public function add($request)
    {
        $products=json_decode($request->products);
        $factor=new Factor();
        $factor->customer_id=$request->customer_id;
        $factor->price=$request->price;
        $factor->paid=$request->paid ?? 0;
        $factor->debt=$request->debt;
        $factor->pay_way=$request->pay_way;
        $factor->description=$request->description;
        $factor->save();
        if (count($products) > 0){
            foreach ($products as $product){
                $factor->products()->attach($product->product_id, [
                    'count' => $product->count,
                    'price' => $product->price,
                    'total' => $product->price * $product->count
                ]);
            }
        }

        return successResponse([]);
    }

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

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

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

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