<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithValidation;
use App\Models\Locality;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class LocalityImport implements ToModel, WithHeadingRow, WithValidation, SkipsOnError
{

    protected $errors = [];

    public function rules(): array
    {
        return [
            'locality_number' => 'required',
            'locality_name' => 'required',
            'state' => 'required',
            'pw_gpci' => 'required',
            'pe_gpci' => 'required',
            'mp_gpci' => 'required',
            'year' => 'required',
            'dos' => 'required|numeric',
            'doe' => 'required|numeric',

        ];
    }

    public function model(array $row)
    {

        try {

            // Convert Excel date strings to DateTime objects
            $dos = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['dos']);
            $doe = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['doe']);
        } catch (\Exception $e) {
            // If conversion fails, add an error message
            $this->errors[] = [
                'message' => "Invalid date format for DOS or DOE",
                'row' => $row,
            ];
            return null; // Skip this row
        }

        $existingLocality = Locality::where('localitynumber', $row['locality_number'])
            ->where('localityname', $row['locality_name'])
            ->where('state', $row['state'])
            ->where('year', $row['year'])
            ->where('dos', $dos)
            ->where('doe', $doe)
            ->first();

        if ($existingLocality) {
            // Handle duplicate locality
            // For example, update the existing locality with new data
            $existingLocality->update([
                'wgpci' => $row['pw_gpci'],
                'pegpci' => $row['pe_gpci'],
                'mpgpci' => $row['mp_gpci'],
                // Update other attributes as needed
            ]);
            return null; // Skip this row
        }

        return  Locality::create([
            'localitynumber' => $row['locality_number'],
            'localityname' => $row['locality_name'],
            'wgpci' => $row['pw_gpci'],
            'pegpci' => $row['pe_gpci'],
            'mpgpci' => $row['mp_gpci'],
            'year' => $row['year'],
            'dos' => $dos,
            'doe' =>  $doe,
            'state' => $row['state'],

        ]);
    }

    public function batchSize(): int
    {
        return 1000; // Adjust batch size as needed
    }

    public function chunkSize(): int
    {
        return 1000; // Adjust chunk size as needed
    }

    public function onError(\Throwable $e)
    {
        // Handle errors
        $this->errors[] = $e->getMessage();
    }

    public function failures()
    {
        return $this->errors;
    }
}
