<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Collection;

class BalanceDataImport implements ToCollection, WithHeadingRow
{
    protected $results = [
        'successfulRows' => [],
        'failedRows' => [],
    ];

    public function collection(Collection $rows)
    {
        if (empty($rows->first()['id'])) {
            $this->results['failedRows'][] = [
                'row' => [],
                'error' => 'Column id is required but missing in the import file'
            ];
            return;
        }

        foreach ($rows as $row) {
            if (empty($row['id']) && $row['id'] !== '0' && $row['id'] !== 0) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'id is required'
                ];
                continue;
            }

            $total = $row['total'] ?? 0;

            // Hanya masukkan jika total lebih besar dari 0
            if ((float) $total > 0) {
                $this->results['successfulRows'][] = [
                    'id' => $row['id'],
                    'name' => $row['name'] ?? null,
                    'total' => $total,
                ];
            }
        }
    }

    public function getResults()
    {
        return $this->results;
    }
}
