<?php

namespace App\Classes\Modules\Imports\Services;

use App\Classes\ValueObjects\Constants\BusinessType;
use App\Models\Company;

use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithValidation;

class ImportsDebtor implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
  public function __construct() {

  }

  public function model($row = [])
  {
      try {
          preg_match_all('/([0-9]{3,4}[a-zA-Z]{3,4})/', $row['desc2'], $matches);

          foreach ($matches[0] as $match){
              $reference = $match;
              $debtor =  $row['code'];
              $company = Company::whereNull('debtor')->whereHas('companyModules', function($query) use ($reference) {
                  $query->whereHas('connections', function($query) use ($reference) {
                      $query->where('invitee_reference', $reference);
                  });
              })->first();

              if ($company) {
                  $company->debtor = $debtor;
                  $company->update();
              }

          }

      } catch (\Exception $exception){
          dd($exception);
      }
  }

  public function batchSize(): int
  {
    return 100;
  }

  public function rules(): array
  {
      return [

      ];
  }
}
