<?php

namespace App\Imports;

use App\Lead;
use App\User;
use App\TimeZoneList;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Auth;

class LeadsImport implements ToCollection, WithStartRow
{

	private $data; 

    public function __construct(array $data = [])
    {
        $this->data = $data; 
    }

	/**
    * @param Collection $rows
    */
	public function collection(Collection $rows)
    {
		$row_count = count($rows);

		$company_id = company_id();
		$user_id = Auth::user()->id;
		
		$i = 0;
        $j = 1;
	
        foreach ($rows as $row) 
        {
            //print_r($row[0]); die;
        	if($row->filter()->isEmpty()){
	            continue;
	    	}

			Validator::make($rows->toArray(), [
	            "$i.0" => 'required|max:150',
	            "$i.1" => 'required',
	            "$i.4" => 'required',
	        ],[
			    "$i.0.required"     => _lang('Row No')." $j - "._lang('Name must required'),
			    "$i.0.max"          => _lang('Row No')." $j - "._lang('Company Name field length max 150 character'),
			    "$i.1.required"        => _lang('Row No')." $j - "._lang('Phone Must be valid'),
			    "$i.4.required"     => _lang('Row No')." $j - "._lang('City must required'),
			])->validate();

			$i++;
			$j++;	
			
			$le = Lead::where('phone', '=', $row[1])->where('company_id', '=', $company_id)->first();
			$tz=TimeZoneList::where('name','like',"%".$row[4]."%")->first();
			
			$le2 = (array)$le;
            if ($le == '') {
                $lead = new Lead();
    			$lead->name = $row[7];
    			$lead->company_name = $row[0];
    			$lead->email = $row[8];
    
    			$lead->lead_status_id = 16;
    			$lead->lead_source_id = 1;
    			$lead->created_user_id = $user_id;
    			$lead->phone = $row[1];
    			$lead->website = $row[9];
    			$lead->country = $row[3];
    		//	$lead->city = $row[6];
    		//	$lead->state = $row[7];
    			$lead->time_zone = $tz->id??0;
    			$lead->zone_state = $row[5];
    			
    			$lead->zip = $row[6];
    			$lead->address = $row[2];
    			$lead->company_id = $company_id;
    			$lead->save();
    
    			create_log('leads', $lead->id, _lang('Created Lead'));
            	create_log('leads', $lead->id, _lang('Assign to').' '.$lead->assigned_user->name);
            	// send notifications email
    	        if($this->data['assigned_user_id'] != '' || $this->data['assigned_user_id'] !=0 || $this->data['assigned_user_id'] !="0") {
    
    	            sendAssignContactEmail("Lead assigned to you", User::find($this->data['assigned_user_id']), $lead);
    	        }
            }
        }
  
    }
	
	/**
     * @return int
    */
    public function startRow(): int
    {
        return 2;
    }
	
}
