<?php

namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use App\Models\Operator;
use App\Models\Branch;
use DB;
use Session;
use Illuminate\Support\Facades\Validator;
use Exception;
use Illuminate\Support\Facades\Hash;

class UsersImport implements ToCollection ,WithHeadingRow
{
     /**
    * @param Collection $collection
    */
    private $data = array();

    public function collection(Collection $rows){
      
    try {
        DB::beginTransaction();
        
       
        foreach ($rows->toArray() as $row) {
            if(empty($row['operator_code'])){
                continue;
            }
            if(Operator::where('Operator_Code', $row['operator_code'])->exists()){
                continue;
            }
            if(Branch::where('branch_id', $row['branch_code'])->doesntExist()){
                continue;
            }
            $password = bin2hex(openssl_random_pseudo_bytes(4));
            $operatorsObj = new Operator();
            $operatorsObj->admin_id       = Session::get('adminsession')->id;
            $operatorsObj->Registrar_Code = $row['registrar_code'];
            $operatorsObj->EA_Code = $row['ea_code'];
            $operatorsObj->Operator_Code  = $row['operator_code'];
            $operatorsObj->Operator_Name = $row['operator_name'];
            $operatorsObj->Aadhaar_Number = $row['aadhaar_number'];
            $operatorsObj->SALARY = $row['salary'];
            $operatorsObj->PF_No = $row['pf_no'];
            $operatorsObj->ESI_No = $row['esi_no'];
            $operatorsObj->Station_Code = $row['station_code'];
            $operatorsObj->NSE_IT_Certificate = $row['nse_it_certificate'];
            $operatorsObj->VTC_Village_Town_City = $row['vtc_village_town_city'];
            $operatorsObj->Post_Office = $row['post_office'];
            $operatorsObj->Block = $row['block'];
            $operatorsObj->District = $row['district'];
            $operatorsObj->State = $row['state'];
            $operatorsObj->Center_Address = $row['center_address'];
            $operatorsObj->Email_ID = $row['email_id'];
            $operatorsObj->Mobile_No = $row['mobile_no'];
            $operatorsObj->Any_Desk_ID = $row['any_desk_id'];
            $operatorsObj->password = Hash::make($password);
            $operatorsObj->view_password = $password;
            $operatorsObj->branch_code = $row['branch_code'];
            $operatorsObj->pincode = $row['pincode'];
            $operatorsObj->save();
        }
        DB::commit();

    } catch (Exception $e) {
       
        DB::rollBack();
        $this->data =  $e->getMessage();
    }
      
    }
     // Specify header row index position to skip
     public function headingRow(): int {
        return 1;
     }
     public function getMessage(){
        return $this->data;
    }
}
