<?php

namespace App\Imports\IMEImports;

use App\Models\fcmodels\ImeData;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
//batch inserts do not rollback all but the batch that failed 
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Log;
use Carbon\Carbon;
class IMEWarrantImport implements ToCollection, WithHeadingRow, WithBatchInserts, WithChunkReading, WithValidation
{
    use Importable;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    //get cust id
    protected $id;

    public function __construct($id) {
        $this->id = $id;
    }
    //insert to db
    public function collection(Collection $row)
    {

        
        try
        {
                 
             $foos= $row->toArray(); 
          $details = $row->toArray();
            $key='imei_data_number';
            $array = $details;
            $temp_array = array();
            $i = 0;
            $key_array = array();
              
            foreach($array as $val) {
                if (!in_array($val[$key], $key_array)) {
                $key_array[$i] = $val[$key];
                $temp_array[$i] = $val;
                }
                $i++;
            }
            
            if(count($temp_array)<count($details))
            {
                    return redirect()->back()->with('failure',"Duplicate imei_data_number number(s) found in excel");
            }
               $phones_arr=[];
               $groups_arr=[];
            foreach($row as $row)      
            {
   
            
            //get the imei_data_number number
   
             Log::info($this->id);
          //check if exists
                 $check=ImeData::where('imei_data_number','88888888')->get();
                 if($check->count())
                 {
                    array_push($phones_arr,$check[0]->imei_data_number);
                 }
                }
                
                if(count($phones_arr)>0 && count($groups_arr)>0)  
                {
                  //  return redirect()->back()->with('success',"Phone number(s) already added ".json_encode($phones_arr));
                   // return redirect()->back()->with('failure',"Phone number(s) already added ".json_encode($phones_arr));
                }
            
            
           foreach($foos as $foo)    {
            Log::info($foo['valid_till']);
            $datess = \Carbon\Carbon::createFromTimestamp($foo['valid_till'])->toDateTimeString();
           // $date = Carbon::parse($foo['valid_till']);
           $date=$foo['valid_till'];
           Log::info($date);
             ImeData::create([

            'imei_data_number' =>$foo['imei_data_number'],
            'valid_till' => $date,
            'organization_id' => '2',
        ]);
        }
        return redirect()->back()->with('success',"IMEI warrants Uploaded Succesfully" );
        }
        catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
            $failures = $e->failures();
            
            foreach ($failures as $failure) {
                $failure->row(); // row that went wrong
                $failure->attribute(); // heading row
                $failure->errors(); // Actual error messages from Laravel validator
                $failure->values(); // The values of the row that has failed.
            }
        }
    }
   public function rules(): array
    {
        return [
            //for non batch
           

            // 'phone' =>'integer|max:799999999999|min:700000000|unique:contacts,phone',
          
        ];
    }
    public function customValidationMessages()
    {
        return [
       
            'phone.max' => 'Phone number must be 12 characters of format "254712345678"',
            'phone.min' => 'Phone number must be 12 characters of format "254712345678".'
    
    
     
        ];
    }
    public function batchSize(): int
    {
        return 200;
    }
    public function chunkSize(): int
    {
        return 200;
    }

}
