<?php

namespace App\Imports;

use App\Models\Employee;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Carbon\Carbon;
use DateTime;

class EmployeeImport implements ToModel, WithStartRow
{
    public function model(array $row)
    {
        $dateOfBirth = $this->parseDate($row[13]);
        $joiningDate = $this->parseDate($row[14]);
        $probationEndDate = $this->parseDate($row[20]);
        $noticePeriodStartDate = $this->parseDate($row[21]);
        $noticePeriodEndDate = $this->parseDate($row[22]);

        return new Employee([
            'designation_id'              => $row[0],
            'department_id'               => $row[1],
            'gender_id'                   => $row[2],
            'language_id'                 => $row[3],
            'title_id'                    => $row[4],
            'country_id'                  => $row[5],
            'state_id'                    => $row[6],
            'city_id'                     => $row[7],
            'employee_type_id'            => $row[8],
            'marital_status_id'           => $row[9],
            'role_in_project_id'          => $row[10],
            'name'                        => $row[11],
            'email'                       => $row[12],
            'date_of_birth'               => optional($dateOfBirth)->format('Y-m-d'),
            'joining_date'                => optional($joiningDate)->format('Y-m-d'),
            'phone_no'                    => $row[15],
            'user_role'                   => $row[16],
            'address'                     => $row[17],
            'about'                       => $row[18],
            'skills'                      => $row[19],
            'probation_end_date'          => optional($probationEndDate)->format('Y-m-d'),
            'notice_period_start_date'    => optional($noticePeriodStartDate)->format('Y-m-d'),
            'notice_period_end_date'      => optional($noticePeriodEndDate)->format('Y-m-d'),
            'login_allowed'               => $row[23],
            'recieve_email_notifications' => $row[24],
            'hourly_rate'                 => $row[25],
            'slack_member_id'             => $row[26],
        ]);
    }

    public function startRow(): int
    {
        return 2;
    }

    private function parseDate($dateString)
    {
        try {
            // Attempt to parse the date using strtotime
            $timestamp = strtotime($dateString);

            if ($timestamp === false) {
                throw new \Exception('Invalid date string');
            }

            $parsedDate = Carbon::createFromTimestamp($timestamp);

            return $parsedDate->isValid() ? $parsedDate->startOfDay() : null;
        } catch (\Exception $e) {
            // Handle the case when the date format is not as expected
            return null;
        }
    }

}
