<?php

namespace App\Imports;

use App\Models\Akun;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

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

    protected $parentId;

    public function __construct($parentId)
    {
        $this->parentId = $parentId;
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            // Check required fields based on user request (name, desc)
            if (empty($row['name'])) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'Name is required'
                ];
                continue;
            }

            // Use the parentId passed from the controller
            $parentId = $this->parentId;

            // Check for duplicate name in the same parent (case-insensitive)
            $existingAccount = Akun::whereRaw('LOWER(name) = ?', [strtolower($row['name'])])
                ->where('perent_id', $parentId)
                ->first();

            if ($existingAccount) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'Account name already exists in this parent'
                ];
                continue;
            }

            try {
                $akun = Akun::create([
                    'name' => $row['name'],
                    'perent_id' => $parentId,
                    'akun_desc' => $row['desc'] ?? null,
                    'total' => 0,
                    'iscash' => 0,
                    'isheader' => 0,
                    'iscashout' => 0,
                    'iscashin' => 0,
                ]);

                $this->results['successfulRows'][] = $akun;
            } catch (\Exception $e) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => $e->getMessage()
                ];
            }
        }
    }

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