<?php

namespace App\Imports;

use App\User;
use App\Role;
use App\History;
use App\Partner;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;


class ImportUser implements ToModel, WithStartRow, WithCalculatedFormulas
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $us = Role::where('name', 'Member')->get();

        // dump($row);
        // dd($row);
        // die;
        if (!isset($row[2])) {
            return null;
        }else{

            do{
                $nip = mt_rand(100000,999999);
            // $dokumen = Str::random(40);
            $cekuniq =  User::where('nip', $nip);
        }while(empty($cekuniq)); 
        
        $user = User::create([
            'name' => $row[0],
            'email' => $row[1],
            'password' => bcrypt($row[2]),
            'nip' => $nip,
            'is_active' => 1,
            'position_id' => $row[3],
            'division_id' => $row[4],
            'status_id' => $row[5],
            'partner_id' => $row[6],
            'is_bpjskes' => $row[8],
            'is_bpjstk' => $row[9],
            'awal_masuk' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[10])->format("Y-m-d"),
            'nama_ibu_kandung' => $row[11],
            'no_handpone' => $row[12],
            'alamat' => $row[13],
            'tanggal_lahir' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[14])->format("Y-m-d"),
            'tempat_lahir' => $row[15],
            'nik' => $row[16],
            'company_id' => Auth::user()->company->id,
            'role_id' =>$us[0]->id,


        ]);
        // return $user;
        // $user;
        $partner = Partner::find($row[6]);
        return new History([
            'user_id' => $user->id,
            'description' => 'Ditempatkan di '. $partner->name,
            'tanggal' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[7])->format("Y-m-d")
        ]);
    }
    }
    public function startRow(): int
    {
        return 2;
    }
}