<?php

namespace App\Imports\BMImports;

use App\Models\bmmodels\ClientBatch;

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 ClientsBatchImport implements ToCollection, WithHeadingRow, WithBatchInserts, WithChunkReading, WithValidation
{
    use Importable;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    //get cust id
    protected $id;
    protected $customer_user_id;

    public function __construct($id,$customer_user_id) {
        $this->id = $id;
        $this->customer_user_id = $customer_user_id;
    }
    //insert to db
    public function collection(Collection $rows)
    {
        $arr = [];
        foreach($rows as $row) {
            try
            {
                $checkex = ClientBatch::where('client_batch_customer_id',$this->id)->where('client_batch_status',0)->where('client_phone',substr($row['phone'],-9))->get();
                
                if(!$checkex->count())
                {
                    $todaydate = date('Ymd');
                    //get maximum batch id
                    $maxBatch = ClientBatch::where('client_batch_customer_id',$this->id)->max('client_batch_id');
                    // dd($maxBatch);
                    if($maxBatch){
                        $batch = $maxBatch + 1;
                    }
                    else{
                        $batch = $this->id. $todaydate . 1;
                    }
                     $check = ClientBatch::where('client_phone',substr($row['phone'],-9))->where('client_batch_customer_id',$this->id)
                            ->where('client_batch_id','LIKE',"%$todaydate%")->pluck('client_phone');
                    
                    
                    if(count($check) > 4)
                    {
                       return count($check).' Contact Paid more than 5 times today!';                
                    }
                    else
                    {
                        $batchin = ClientBatch::create([
                            //
                            'client_name'=> $row['name'],
                            'client_idno' => $row['idno'],
                            'client_phone' => substr($row['phone'],-9),
                            'transfer_amount' => $row['amount'],
                            'client_batch_status' => 0,
                            'client_batch_id' => $batch,
                            'client_batch_customer_id' => $this->id,
                            'client_batch_customer_user_id'=>$this->customer_user_id,
                        ]);
                        
                    }
                }
                else
                {
                    foreach($checkex as $check)
                    {
                        array_push($arr,$check->client_phone);
                    }
                }
            }
            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()->route('batch.index')->with('success', 'Batch to be paid has been added succesfully!');
        return redirect()->back()->with('failure',"Pending payment for Contact already exists: ".json_encode($arr));
    }
    public function rules(): array
    {
        return [
            //for non batchClientBatch
            'fullname' =>'string',
            'amount' =>'integer',
            '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]',
            'amount.integer' => 'Amount must be a positive number[e.g 10000]',
            '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 200;
    }
    public function chunkSize(): int
    {
        return 200;
    }

}
