<?php

namespace App\Imports\QuickBooks;

use App\Imports\QuickBooks\Concerns\SkipsQuickBooksExtraSheets;
use App\Imports\QuickBooks\Concerns\InteractsWithQuickBooksRows;
use App\Models\Employee;
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 QuickBooksEmployeesImport implements WithMultipleSheets, SkipsUnknownSheets
{
    use SkipsQuickBooksExtraSheets;

    public readonly QuickBooksEmployeesSheetImport $sheet;

    private readonly string $sheetName;

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

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

class QuickBooksEmployeesSheetImport 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, ['employee'])) ?: $this->personName($row) ?? '';

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

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

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

        $employee->fill([
            'name' => $name,
            'email' => $this->clean($this->value($row, ['main email'])) ?: null,
            'phone' => $this->clean($this->value($row, ['main phone'])) ?: null,
            'is_active' => $this->activeValue($this->value($row, ['active status'])),
            'depth' => 0,
            'parent_id' => null,
        ]);

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