<?php

namespace App\Imports\BundlesImports;

use App\Models\atmodels\Airtime_contact;
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 Auth;
class BundlesContactsImport 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='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=[];
               $groups_arr=[];
            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); 
                    }
             }
             Log::info($this->id);
          //check if exists
                 $check=Airtime_contact::where('contact',$number)->where('customer_id',$this->id)->get();
                 if($check->count())
                 {
                    array_push($phones_arr,$check[0]->contact);
                    array_push($groups_arr,$check[0]->group_id);
                 }
                }
                
                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)    {
             //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); 
                    }
             }
             $shop_id=Auth::user()->shop_id;

             Airtime_contact::create([
        
            //
            'customer_id' => $this->id,
            'fname'=> $foo['name'],
            'contact' => $number,
            'group_id' => $foo['group_id'] ?? NULL,
            'ime'=> $foo['imei'],
            'bundle'=> '1',
            'ShopID' => $shop_id,
        ]);







        
        }
        return redirect()->back()->with('success',"Contacts 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
           

             'contact' =>'integer|max:799999999999|min:700000000|unique:contacts,contact',
          
        ];
    }
    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;
    }

}
