<?php

namespace App\Imports;

use App\Models\BulkOmfs;
use App\Models\ConversionFactor;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class OmfsBulk implements ToModel,WithHeadingRow, WithValidation
{

    protected $errors = [];
    private $currentdatetime;

    public function __construct() {
        $this->currentdatetime = date('Y-m-d H:i:s');
    }

    public function rules(): array
    {
        return [
            'service_name' => 'required',
            'dos' => 'required|numeric',
            'service_type' => 'required',
            'provider_type' => 'required',
            'conversion_factor' => 'required',
            'locality_type' => 'required',
            'locality_state' => 'required',
            // 'locality_number' => 'required',
            // 'locality_name' => 'required',
            // 'localityzip' => 'required',
            'cptcode' => 'required',
            'units' => 'required|integer|min:1',
            'payment_total' => 'required',
            // 'modifiers' => 'required',
        

        ];
    }

    public function model(array $row)
    {
        try {

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

      

        return BulkOmfs::create([
            'bulk_id' => $this->currentdatetime ,
            'service_name' => $row['service_name'],
            'dos' => $dos,
            'service_type' => $row['service_type'],
            'provider_type' => $row['provider_type'],
            'conversion_factor' => $row['conversion_factor'],
            'locality_type' => $row['locality_type'],
            'locality_state' => $row['locality_state'],
            'locality_number' => $row['locality_number'],
            'locality_name' => $row['locality_name'],
            'localityzip' => $row['localityzip'],
            'cptcode' => $row['cptcode'],
            'units' => $row['units'],
            'payment_total' => $row['payment_total'],
            'modifiers' => $row['modifiers'],
        ]);

    }

    public function getbulkid()
    {
        return $this->currentdatetime;
    }

    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;
    }

}
