<?php

namespace App\Imports;

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

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

    protected $validCategoryIds = [];

    protected $fallbackCategoryId = 8;

    public function __construct(array $categoryIds)
    {
        // Normalize semua id jadi integer
        $this->validCategoryIds = array_map('intval', $categoryIds);

        // Pastikan fallback id selalu ada
        if (!in_array($this->fallbackCategoryId, $this->validCategoryIds, true)) {
            $this->validCategoryIds[] = $this->fallbackCategoryId;
        }
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {

            // =========================
            // VALIDASI NAME
            // =========================
            if (empty($row['name'])) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'Name is required',
                ];

                continue;
            }

            // =========================
            // VALIDASI CATEGORY_ID
            // =========================
            if (
                !isset($row['category_id']) ||
                trim((string) $row['category_id']) === ''
            ) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'category_id (parent account) is required',
                ];

                continue;
            }

            // Normalize category id dari excel
            $categoryId = (int) trim((string) $row['category_id']);

            // Fallback ke 8 jika tidak valid
            if (!in_array($categoryId, $this->validCategoryIds, true)) {
                $categoryId = $this->fallbackCategoryId;
            }

            // =========================
            // CEK PARENT ACCOUNT
            // =========================
            $parentAccount = Akun::find($categoryId);

            // Kalau parent tidak ada, fallback lagi ke 8
            if (!$parentAccount) {
                $categoryId = $this->fallbackCategoryId;
                $parentAccount = Akun::find($categoryId);
            }

            // Kalau fallback juga tidak ada
            if (!$parentAccount) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => "Fallback parent account with id {$this->fallbackCategoryId} not found",
                ];

                continue;
            }

            // =========================
            // CEK DUPLIKAT
            // =========================
            $existingAccount = Akun::whereRaw(
                'LOWER(name) = ?',
                [strtolower(trim($row['name']))]
            )
                ->where('perent_id', $categoryId)
                ->first();

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

                continue;
            }

            // =========================
            // CREATE ACCOUNT
            // =========================
            try {

                $akun = Akun::create([
                    'name' => trim($row['name']),
                    'perent_id' => $categoryId,
                    'akun_desc' => $row['desc'] ?? null,
                    'is_productionasset' => $this->parseBoolean(
                        $row['production_asset'] ?? false
                    ),
                    '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;
    }

    private function parseBoolean($value): bool
    {
        if (is_bool($value)) {
            return $value;
        }

        $trueValues = [
            'ya',
            'yes',
            'true',
            '1',
            'on',
        ];

        $lower = strtolower(trim((string) $value));

        return in_array($lower, $trueValues, true);
    }
}
