<?php

namespace App\Imports;

use App\Models\CarReport;
use Illuminate\Support\Collection;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Carbon\Carbon;

class CarMileageReportImport implements ToCollection, WithHeadingRow, WithChunkReading
{
    /**
    * @param Collection $collection
    */
    private $object_name = "";
    public function collection(Collection $rows)
    {

        $this->object_name = "";
        foreach ($rows as $row) 
        {

            $in_row = $row->toArray();
            
            // dd($in_row);
            
            if(isset($in_row[0]) && $in_row[0] == "Object:"){
                $this->object_name = $in_row[1];
                continue;
            }

            if(isset($in_row[0]) && $in_row[0] == "Time A"){
                continue;
            }

            // Time A

            if(isset($in_row[0]) && $in_row[0] == "" && $in_row[1] == "" && $in_row[2] == "")
            {
                continue;
            }

            $formatted_start_time = Carbon::createFromFormat('Y-m-d H:i:s',$row["time_a"])->format('H:i:s');
            $formatted_end_time = Carbon::createFromFormat('Y-m-d H:i:s',$row["time_b"])->format('H:i:s');

            $car_report = CarReport::create([
                'object_id' => $this->object_name,
                'start_time' => $row['time_a'],
                'start_position' => $row['position_a'],
                'end_time' => $row['time_b'],
                'end_position' => $row['position_b'],
                'duration' => date( "H:i:s",strtotime($formatted_end_time) - strtotime($formatted_start_time)),
                'length' => preg_replace('/[^\d.]/','',$row['length']),
                'fuel_consumption' => preg_replace('/[^\d.]/','',$row['fuel_consumption']),
                // 'avg_fuel_consumption' => $row['avg._fuel_cons._(100_km)'],
                'fuel_cost' => preg_replace('/[^\d.]/','',$row['fuel_cost']),
                'driver' => $row['driver'],
                'trailer' => $row['trailer'],
            ]);
        }
    }
    
    // public function headingRow(): int
    // {
    //     return 6;
    // }
    public function chunkSize(): int
    {
        return 1000;
    }
   
}
