<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use App\ChartOfAccount;
use App\AccountType;

class ChartsOfAccountImport implements ToModel, WithHeadingRow
{
    /**
    * @param Collection $collection
    */
 protected   $saveRow= [];
    public function model(array $row)
    {
        $words = ['name', 'number','account_type_number','description','opening_balance','sub_account_id'];

        if(!empty($row['name']) && !empty($row['number']) && !empty($row['account_type_number'])){
     
            $this->saveRow[] = [
                'id' => $row['id'],
                'name' => $row['name'],
                'number' => $row['number'],
            ];

            $charts_of_account = new ChartOfAccount;
        $charts_of_account->name =$row['name'];
        $charts_of_account->number =$row['number'];
         $accounttype=  AccountType::where('number',$row['account_type_number'])->first();
         if(!empty($accounttype)){
        $charts_of_account->account_type_id =  $accounttype->id;
         }
         else{
            //   return null;
         }
        $charts_of_account->description = $row['description'];
        $charts_of_account->opening_balance = $row['opening_balance'];
        if(!empty($row['sub_account_id'])){
         $subAccountId =$row['sub_account_id'];
         $number =   $this->searchById($subAccountId);
         if ($number !== null) {
            $num=    ChartOfAccount::where('number',$number)->first();
            if(!empty($num)){
                $charts_of_account->sub_account_id = $num->id;
            }
        }
       
        }
        

        
        $charts_of_account->save();
        return  $charts_of_account;
        }
        // return null;
       
    }

    public function searchById($subAccountId)
    {
        $filteredRows = array_filter($this->saveRow, function ($saveRowVal) use ($subAccountId) {
            return $saveRowVal['id'] == $subAccountId;
        });

        $filteredRows = array_values($filteredRows);

        if (!empty($filteredRows)) {
            return $filteredRows[0]['number'];
        }

        return null;
    }
}
