<?php

namespace App\Service\PurchaseMaker;

use App\Models\purchase_maker_masters;
use App\Models\PurchaseMaker;
use Illuminate\Support\Facades\Auth;

class PurchaseMakerService
{
    public static function PurchaseMakerCreate(array $data)
    {

        $collect = collect($data);
        $sum = array_reduce($collect['list'], function ($item, $item2) {
            return $item + $item2['total'];
        }, 0);

        $master_id = purchase_maker_masters::create([
            'total_product' => count($collect['list']),
            'po_date' => $collect['po_date'],
            'po_no' => $collect['po_no'],
            'supplier_id' => isset($collect['supplier_id']) ? $collect['supplier_id'] : null,
            'created_by' => Auth::user()->id,
            'shop_id' => auth()->user()->shop_id,
            'total' => $sum,
        ]);

        foreach ($collect['list'] as $key => $value) {

            PurchaseMaker::create([
                'purchase_maker_masters_id' => $master_id->id,
                'product_id' => $value['product_id'],
                'attribute_id' => $value['attribute_id'],
                'carton_box' => $value['carton_box'] ?? null,
                'quantity' => $value['quantity'],
                'price' => $value['price'],
                'total' => $value['total'],
            ]);
        }
    }

    public static function PurchaseMakerUpdate(array $data, $id)
    {
        $collect = collect($data);
        $sum = array_reduce($collect['list'], function ($item, $item2) {
            return $item + $item2['total'];
        }, 0);
        purchase_maker_masters::find($id)->update([
            'total_product' => count($collect['list']),
            'po_date' => $collect['po_date'],
            'supplier_id' => isset($collect['supplier_id']) ? $collect['supplier_id'] : null,
            'created_by' => Auth::user()->id,
            'shop_id' => auth()->user()->shop_id,
            'total' => $sum,
        ]);

        PurchaseMaker::where('purchase_maker_masters_id', $id)->delete();
        foreach ($collect['list'] as $key => $value) {
            PurchaseMaker::create([
                'purchase_maker_masters_id' => $id,
                'product_id' => $value['product_id'],
                'attribute_id' => $value['attribute_id'],
                'carton_box' => $value['carton_box'] ?? null,
                'quantity' => $value['quantity'],
                'price' => $value['price'],
                'total' => $value['total'],
            ]);
        }
    }
}
