<?php

namespace App\Imports;

use App\Models\BulkPharmacyRequest;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class PharmacyBulk implements ToModel, WithHeadingRow, WithValidation, SkipsOnError
{

    protected $errors = [];
    private $currentdatetime;

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

    public function rules(): array
    {
        return [
            'dos' => 'required|numeric',
            'ndc' => 'required',
            'units' => 'required|numeric|min:1',
            'payment_total' => 'nullable|numeric',
            'product_type' => 'nullable|in:d,c',

        ];
    }

    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
        }


        // Validate ProductType
        if (isset($row['product_type']) && strtoupper($row['product_type']) === 'c') {
            $this->errors[] = [
                'message' => "Compound feature is not available yet.",
                'row' => $row,
            ];
            return null; // Skip this row
        }



        return BulkPharmacyRequest::create([
            'bulk_id' => $this->currentdatetime,
            'product_type' => $row['product_type'] ?? "d",
            'date_of_service' => $dos,
            'ndc_number' => $row['ndc'],
            'units' => $row['units'],
            'payment_total' => $row['payment_total'] ?? 0,
            "created_on" => now()
        ]);


    }

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