sigd/app/Imports/FormImport.php

55 lines
1.6 KiB
PHP

<?php
namespace App\Imports;
use App\Services\Activity\FormService;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class FormImport implements ToCollection, WithHeadingRow
{
protected $formService;
protected $sector, $code, $inventoryYear;
protected $formDetails;
protected $instansi;
public function __construct($formService, $sector, $code, $inventoryYear, $formDetails, $instansi = null)
{
$this->formService = $formService;
$this->sector = $sector;
$this->code = $code;
$this->inventoryYear = $inventoryYear ?? date('Y');
$this->formDetails = $formDetails;
$this->instansi = $instansi;
}
public function collection(Collection $rows)
{
$data = []; // Initialize data array to hold all years' data
foreach ($rows as $row) {
$year = $row['tahun'];
$yearData = [];
$items = $row->toArray();
$items = array_values($items);
for ($i = 0; $i < count($items); $i++) {
if ($i !== 0) {
$activityCode = $this->formDetails[$i - 1]->activity_code;
$unitCode = $this->formDetails[$i - 1]->unit_code;
$yearData["{$activityCode}-{$unitCode}"] = getFormattedValue($items[$i]);
}
}
if (!isset($data[$year])) {
$data[$year] = [];
}
$data[$year] = $yearData;
}
$this->formService->save($this->sector, $this->code, $this->inventoryYear, $data, null, $this->instansi);
}
}