<?php

namespace App\Imports\BMImports;

use App\Models\bmmodels\CustomerClient;
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 ClientsImport implements ToCollection, WithHeadingRow, WithValidation, WithBatchInserts, WithChunkReading
{
    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 $rows)
    {
        $arr = [];
        foreach($rows as $row) {
            try
            {
                $check = CustomerClient::where('cust_client_phone',substr($row['phone'],-9))->where('customer_cust_id',$this->id)->get();
                if(!$check->count())
                {
                    $client = CustomerClient::create([
                        //
                        'cust_client_fullname'=> $row['name'], //fullname
                        'cust_client_idno' => $row['idno'],
                        'cust_client_phone' => substr($row['phone'],-9),
                        'cust_client_status' => 1,
                        'customer_cust_id' => $this->id,
                    ]);
                   
                }
                else
                {
                    
                    foreach($check as $check)
                    {
                        array_push($arr,$check->cust_client_phone);
                    }
                    return redirect()->back()->with('failure',"Contact already exists ".json_encode($arr));
                    
                }
                
            }
            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.
                }
            }
        }
        return redirect()->back()->with('success', 'Payees Uploaded succesfully!'); 
        
    }
    public function rules(): array
    {
        return [
            //for non batch
            'fullname' =>'string',
            'phone' =>'integer|max:799999999|min:700000000',
            'idno' =>'integer',

             // validates in batches
            //  '*.fullname' => 'string',
            //  '*.phone' =>'integer|max:799999999|min:700000000',
            //  '*.idno' =>'integer|min:11111',
        ];
    }
    public function customValidationMessages()
    {
        return [
            'fullname.string' => 'Full name must text[between a-z or A-Z]',
            'phone.integer' => 'Phone must be a number.',
            'phone.unique' => 'Phone number already exists.',
            'phone.max' => 'Phone number must be 9 characters of format "712345678"',
            'phone.min' => 'Phone number must be 9 characters of format "712345678".',
            'idno.integer' => 'ID No must be a number.',
            'idno.unique' => 'ID No already exists.',
        ];
    }
    public function batchSize(): int
    {
        return 5;
    }
    public function chunkSize(): int
    {
        return 5;
    }

}