<?php

namespace App\Imports\QuickBooks;

use App\Imports\QuickBooks\Concerns\SkipsQuickBooksExtraSheets;
use App\Imports\QuickBooks\Concerns\InteractsWithQuickBooksRows;
use App\Models\OtherName;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\SkipsUnknownSheets;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class QuickBooksOtherNamesImport implements WithMultipleSheets, SkipsUnknownSheets
{
    use SkipsQuickBooksExtraSheets;

    public readonly QuickBooksOtherNamesSheetImport $sheet;

    private readonly string $sheetName;

    public function __construct(int $companyId, string $sheetName = 'Sheet1')
    {
        $this->sheetName = $sheetName;
        $this->sheet = new QuickBooksOtherNamesSheetImport($companyId);
    }

    public function sheets(): array
    {
        return [$this->sheetName => $this->sheet];
    }
}

class QuickBooksOtherNamesSheetImport implements ToCollection, WithHeadingRow
{
    use InteractsWithQuickBooksRows;

    public int $created = 0;
    public int $updated = 0;
    public int $skipped = 0;
    public array $errors = [];

    public function __construct(private readonly int $companyId)
    {
    }

    public function collection(Collection $rows): void
    {
        foreach ($rows as $offset => $row) {
            $this->importRow($this->normalizeRow($row), $offset + 2);
        }
    }

    private function importRow(array $row, int $line): void
    {
        $name = $this->clean($this->value($row, ['other name']));

        if ($name === '') {
            $this->skipped++;
            return;
        }

        $otherName = OtherName::withoutGlobalScopes()
            ->where('company_id', $this->companyId)
            ->whereNull('deleted_at')
            ->where('name', $name)
            ->first();

        $isNew = !$otherName;
        $otherName ??= new OtherName(['company_id' => $this->companyId]);

        $otherName->fill([
            'name' => $name,
            'address' => $this->clean($this->value($row, ['address'])) ?: null,
            'type' => 'quickbooks',
            'is_active' => true,
        ]);

        try {
            $otherName->save();
            $isNew ? $this->created++ : $this->updated++;
        } catch (\Throwable $e) {
            $this->errors[] = "Row {$line}: {$e->getMessage()}";
        }
    }
}
