<?php
namespace App\Imports;

// use Maatwebsite\Excel\Concerns\Import;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use App\Models\Account; 
use App\Service\AccountGroupService;
use Log;

class AccountsImport implements ToModel, WithHeadingRow
{
    // use Importable;

    public function model(array $rows)
    {   
        // dd($rows);
        Log::info($rows);
        Log::info("Above Rows");
        $existingItem = Account::where('account_name', $rows['account_name'])
            ->where('account_type', $rows['account_group'])
            ->first();
        
        
        if($existingItem==null && $rows['account_name']!=null && $rows['account_type']!=null){
            //Getting Account Code

            $account_service=new AccountGroupService;
            $account_code=$account_service->updateAccountGroup($rows['account_type']);

            $obj['account_name'] = $rows['account_name'];
            $obj['account_type'] = $rows['account_group'];
            $obj['account_group_id'] = $rows['account_group_id']??0;
            $obj['account_code'] = $account_code;
            $obj['account_posting'] = $rows['account_posting_id']==1?'Profit & Loss':'Balance Sheet';
            $obj['account_posting_id'] = $rows['account_posting_id']??0;
            $obj['acc_case_name'] = $rows['acc_case_name']??null;
            $obj['lock_status'] = 1;

            return new Account($obj); // 👈 This ensures the row is actually saved
        }else{
            return null;
        }
            
    }
}