<?php

namespace App\Imports\FCImports;

use App\Models\fcmodels\Import;
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;
class MessageSmscontactssImport 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
        {
            
                     
          $details = $row->toArray();
            $key='phone';
            $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 Phone number(s) found in excel");
            }
             
            
            $phones_arr=[];
            $foos = $row;
            foreach($row as $row)      
            {
   
            
            //get the phone number
            $no=str_replace(' ', '',$row['phone']);
            //get the phone number variable to store the value
            $number="";
            //format the number to pick any format
             if((substr($no, 0, 4)=="+254")||(substr($no, 0, 3)=="254")||(substr($no, 0, 2)=="07")||(substr($no, 0, 1)=="7")){
                  
                    if(substr($no, 0, 4)=="+254"){
                        $number="254" . substr($no, 4);
                    }
                    
                    elseif(substr($no, 0, 3)=="254"){
                        $number="254" . substr($no, 3);  
                    }
                    elseif(substr($no, 0, 1)=="0"){
                        $number="254" . substr($no, 1); 
                    }
                    elseif(substr($no, 0, 1)=="7"){
                        $number="2547" . substr($no, 1); 
                    }
             }
          //check if exists
                 $check=Import::where('phone',$number)->where('organization_id',$this->id)->get();
                 if($check->count())
                 {
                    array_push($phones_arr,$check[0]->phone);
                 }
                }
                
                if(count($phones_arr)>0)
                {
                    return redirect()->back()->with('failure',"Phone number(s) already added ".json_encode($phones_arr));
                }
                
                foreach($foos as $foo)      
                {
                     //get the phone number
                    $no=str_replace(' ', '',$foo['phone']);
                    //get the phone number variable to store the value
                    $number="";
                    //format the number to pick any format
                     if((substr($no, 0, 4)=="+254")||(substr($no, 0, 3)=="254")||(substr($no, 0, 2)=="07")||(substr($no, 0, 1)=="7")){
                          
                        if(substr($no, 0, 4)=="+254"){
                            $number="254" . substr($no, 4);
                        }
                        
                        elseif(substr($no, 0, 3)=="254"){
                            $number="254" . substr($no, 3);  
                        }
                        elseif(substr($no, 0, 1)=="0"){
                            $number="254" . substr($no, 1); 
                        }
                        elseif(substr($no, 0, 1)=="7"){
                            $number="2547" . substr($no, 1); 
                        }
                     }
         
         

                     if(count($phones_arr)>0)
                {
          
                  return redirect()->back()->with('failure',"Phone number(s) already added ".json_encode($phones_arr));
                }     
             Import::create([
                //format the phone number to 254
                
                
                
                'import_name'=> $row['name'],
                'phone' => $number,
                
    
                'status' => '0',
                'organization_id' => $this->id,
            ]);
        }
                    return redirect()->back()->with('success',"Import successful");   
       
        }
        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
            'name' =>'string',
            'phone' =>'required|integer|max:799999999999|min:700000000',
          
        ];
    }
    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;
    }

}
