HEX
Server: Apache
System: Linux WWW 6.1.0-40-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.153-1 (2025-09-20) x86_64
User: web11 (1011)
PHP: 8.2.29
Disabled: NONE
Upload Files
File: /var/www/ivs.kaunokolegija.lt/laravel/app/Imports/CompaniesImport.php
<?php

namespace App\Imports;

use App\Models\User;
use App\Models\Company;
use App\Models\LegalStatus;
use App\Models\ContactPerson;
use App\Models\CoopAgreement;
use App\Models\CoopAgreementType;
use App\Models\AreasOfCooperation;
use Illuminate\Support\Collection;
use App\Models\DepartmentSubsection;
use App\Models\SubAreasOfCooperation;
use Maatwebsite\Excel\Validators\Failure;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\WithValidation;

class CompaniesImport implements ToCollection, SkipsOnFailure, WithValidation
// class CompaniesImport implements ToCollection
{
    use SkipsFailures;

    public function rules(): array
    {
        return [
            '0' => 'required|string',
            // '1' => 'required|string',
            '2' => 'required',
            // '6' =>  'required|string',
            // '8' => 'nullable|date',
            // '9' => 'nullable|date',
        ];
    }

    private function extractVatCode($rekvizitai)
    {
        preg_match('/LT\d{12}/', $rekvizitai, $matches);
        return $matches[0] ?? null;
    }

    private function validateDate($date)
    {
        if (!$date || !strtotime($date)) {
            // \Log::warning("Invalid date detected: $date");
            return null;
        }
        return date('Y-m-d', strtotime($date));
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $key => $row) {
            // Skip the header row
            if ($key === 0) continue;

            if (count($row) < 20) {
                // dd("Error on row $key:", $row);
            }

            // Companies
            // 0 - name
            // 1 - legal_statuses(legalstatus_id) + create if not exist
            // 2 - companycode
            // 3 - address
            // 6 - directorname
            // 13 - name ($company->accountablepersonkks()->sync)
            // 16 - website

            // contact-people
            //- sitie???
            // 4 - email
            // 5 - phone
            // 7 - name

            // coop-agreements
            // 8 - signing_date
            // 9 - validity_date
            // 11 - number
            // 12 - name (for this contcat people relationship $company->accountablepersonkks()->sync or coopAgreements->contactpeople()->sync) )

            // coop-agreement-types (coopagreements->type_id)
            // 10 - name

            //areas-of-cooperations
            // 19 - sritys- ?? (areas-of-cooperations (pagrindines bendradarbiavimo sritys))

            // 14 - Praktika - ??? +
            // 15 - rekvizitai - (extract from strig LT(12numbers) and its company vatcode) +  
            // 17 - description (company description)
            // 18 - veiklos sritis sukurti

            $legalStatus = null;
            if(!empty($row[1])) $legalStatus = LegalStatus::firstOrCreate(['name' => $row[1]]);

            $company = Company::updateOrCreate(
                ['companycode' => $row[2]],
                [
                    'name' => $row[0],
                    'legalstatus_id' => $legalStatus->id ?? null,
                    'mainaddress' => $row[3] ?? null,
                    'directorname' => ($row[6] ?? $row[7]) ?? $row[12] ?? null,
                    'practice' => (bool) $row[14],
                    'description' => $row[17] ?? null,
                    'vatcode' => $this->extractVatCode($row[15]) ?? null,
                    'website' => $row[16] ?? null,
                ]
            );

            $this->syncRelatedEntities($company, $row);
        }
    }

    private function syncRelatedEntities(Company $company, $row)
    {
        // Sync Contact People
        if (!empty($row[7]) && !empty($row[4]) && !empty($row[5])) {
            $contactPerson = ContactPerson::updateOrCreate(
                ['name' => $row[7]],
                [
                    'email' => !empty($row[4]) ? $row[4] : null,
                    'phone' => !empty($row[5]) ? $row[5] : null,
                    'social_partner_id' => $company->id
                ]
            );
            $company->contactpersons()->syncWithoutDetaching($contactPerson->id);
        }

        // Sync Cooperation Agreements
        $signingDate = $this->validateDate($row[8] ?? null);
        $validityDate = $this->validateDate($row[9] ?? null);
        if (!empty($row[11]) && ($signingDate || $validityDate)) {
            $agreement = CoopAgreement::firstOrCreate([
                'number' => $row[11],
                'signing_date' => $row[8],
                'validity_date' => $row[9],
            ]);
            $company->coopAgreements()->syncWithoutDetaching($agreement->id);
        }

        // Sync Agreement Type
        if (!empty($row[10]) && isset($agreement)) {
            $agreementType = CoopAgreementType::firstOrCreate(['name' => $row[10]]);
            $agreement->type()->associate($agreementType);
            $agreement->save();
        }

        // Sync Areas of Cooperation
        if (!empty($row[19])) {
            $areas = explode(',', $row[19]);
            // dd($areas, $row[19]);
            foreach ($areas as $area) {
                $cooperationArea = AreasOfCooperation::firstOrCreate(['name' => trim($area)]);
                $company->coopareas()->syncWithoutDetaching($cooperationArea->id);
            }
        }

        // Sub Areas of Cooperation
        if (!empty($row[18])) {
            $subAreas = preg_split('/[,\.;]+/', $row[18]);
            foreach ($subAreas as $subArea) {
                $trimmedSubArea = trim($subArea);
                $cleanSubArea = rtrim($trimmedSubArea, '.');
                if ($cleanSubArea !== '') {
                    $cooperationArea = SubAreasOfCooperation::firstOrCreate(['name' => $cleanSubArea]);
                    $company->subareasofcooperation()->syncWithoutDetaching($cooperationArea->id);
                }
            }
        }

        if (!empty($row[13])) {
            $accountablePerson = User::where('name', $row[13])->first();

            if ($accountablePerson) {
                \Log::warning("Pririsamas useris prie company: {$accountablePerson->name} {$accountablePerson->id} - {$company->id} {$company->name}");
                $company->accountablepersonkks()->syncWithoutDetaching($accountablePerson->id);
            }
    }
    }  

    public function onFailure(Failure ...$failures)
    {
        foreach ($failures as $failure) {
            \Log::warning("Row {$failure->row()} failed: " . implode(", ", $failure->errors()));
        }
    }

}