<?php

namespace Modules\Internal\Services;

use App\Exceptions\ImportRowException;
use App\Models\Benefit;
use App\Models\Corporate;
use App\Models\Drug;
use App\Models\Formularium;
use App\Models\Plan;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;

class CorporateService
{    
    protected function validateFormulariumRow($row)
    {
        if (empty($row['code'])) {
            throw new ImportRowException(__('formularium.CODE_REQUIRED'), 0, null, $row);
        }

        if (empty($row['item_code'])) {
            throw new ImportRowException(__('formularium.TYPE_REQUIRED'), 0, null, $row);
        }
    }

    public function handleFormulariumRow(Formularium $formularium, $row)
    {
        try {
            $formularium_item_data = $row;
            $formularium_item_data["corporate_id"] = $formularium->id;

            $this->validatePlanRow($formularium_item_data);
            $drug = Drug::where('code', $formularium_item_data['item_code'])->first();

            if (empty($drug)) {
              throw new ImportRowException(__('formularium.DRUG_CODE_NOT_FOUND'), 0, null, $row);
            }

            $formulariumItem = $formularium->items()->create([
                'item_id' =>  $drug->id,
            ]);

            return $formulariumItem;
        } catch (\Exception $e) {
            throw $e;
        }
    }
}
