<?php
namespace App\Imports;

use App\RBIBlacklist;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;

class RBIBlacklistImport implements ToCollection {

    use Importable;

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {

        $headers = $collection[0];

        unset($collection[0]);

        $response = [];
        $user_id = Auth::user()->id;
        $date = Carbon::now()->toDateTimeString();
        foreach ($collection as $item){
            foreach ($headers as $headerKey => $header) {
                if ($header && isset($item[$headerKey]) && $item[$headerKey]) {
                    $isExist = RBIBlacklist::where('document_value',$item[$headerKey])->where('document_type',$header)->first(['id']);
                    if(!isset($isExist->id)) {
                        $response[] = [
                            'document_value' => $item[$headerKey],
                            'document_type' => $header,
                            'user_id' => $user_id,
                            'created_at' => $date
                        ];
                    }
                }
            }
        }


        if($response) {
            RBIBlacklist::insert($response);
        }
        // TODO: Implement collection() method.
    }
}