<?php

namespace App\Services;

use App\Models\MasterFormulation;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class MasterFormulationService
{
    public function getAllMasterFormulations()
    {
        $masterFormulations = MasterFormulation::with(['creator', 'updater'])
            ->orderBy('created_at', 'desc')
            ->get();
        return $masterFormulations;
    }

    public function createMasterFormulation($request)
    {
        // product is no longer provided; brand_name and product_name are stored as text
        return DB::transaction(function () use ($request) {
            $data = [
                'brand_name' => $request->brand_name,
                'product_name' => $request->product_name,
                'batch_size' => $request->batch_size,
                'created_by' => $request->created_by,
            ];
            $model = MasterFormulation::create($data);
            // dd($request->items);
            foreach ($request->items as $repeater) {
                $model->mfItems()->create([
                    'raw_material_item_id' => $repeater['raw_material_item'],
                    'quantity' => $repeater['quantity'],
                ]);
            }

            return $model;
        });
        // return MasterFormulation::create($request);
    }

    public function updateMasterFormulation(MasterFormulation $model,  $request)
    {
        // Only brand_name, product_name, batch_size are updatable

        // return $masterFormulation->update($data);
         return DB::transaction(function () use ($request,$model) {
            $data = [
                'brand_name' => $request->brand_name,
                'product_name' => $request->product_name,
                'batch_size' => $request->batch_size,
                'created_by' => $request->created_by,
            ];
            $model->update($data);
            
              $model->mfItems()->delete();
            foreach ($request->items as $repeater) {
                $model->mfItems()->create([
                    'raw_material_item_id' => $repeater['raw_material_item'],
                    'quantity' => $repeater['quantity'],
                ]);
            }

            return $model;
        });
    }

    public function deleteMasterFormulation(MasterFormulation $masterFormulation)
    {
        return $masterFormulation->delete();
    }

    public function getMasterFormulationById($id)
    {
        return MasterFormulation::with(['creator', 'updater'])->findOrFail($id);
    }
}
