<?php

namespace App\Imports\FCImports;

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 App\Models\fcmodels\Bulksms;
use App\Models\fcmodels\ManagementAccount;
use App\Classes\FCClasses\SMSCounter;
use Log;
use DB;

class ScheduleImport implements ToCollection, WithHeadingRow, WithValidation
{
    use Importable;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    //get cust id
    protected $id;
   

    public function __construct($org_id,$time,$api_account) {
        $this->org_id = $org_id;
        $this->api_account = $api_account;
        $this->time = $time;
    }
    /**
    * @param Collection $collection
    */
    public function collection(Collection $row)
    {
        try
        {
             $details = $row;
                $key='phone';
                $array = $row;
                $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($row))
                {
                        return redirect()->back()->with('failure',"Duplicate Phone number(s) found in excel.Check and retry");
                }
                
                
           
            foreach($details 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); 
                        }
                 }
                 //get site
                 $site = ManagementAccount::where('api_account',$this->api_account)->pluck('organization');
                    //insert scheduled smsm
                    Bulksms::create([
                        'recipients' => $row['phone'],
                        'message'=>urlencode($row['message']),
                        'datetime' => now(),
                        'authorized' => 'Yes',
                        'authorizer' => $this->org_id,
                        'date_authorized' => now(),
                        'override' => 'Excel Upload',
                        'site' => $site[0],
                        'scheduleDateTime' => $this->time,
                        'scheduleSMS_status' => 'Pending',
                        'user_id'=>$this->org_id
                    ]);
            }
            return redirect()->back()->with('success',"Scheduled 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 [
            'phone' =>'required',
            'message' => 'required'
          
        ];
    }
    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".'
    
    
    
        ];
    }
}
