<?php

namespace App\Imports;

use App\Models\Librarian\Books;
use App\Models\Library\OpeningStock;
use App\Models\Product;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Date;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ImportBookOpeningStock implements ToCollection, WithChunkReading , ShouldQueue,WithHeadingRow
{

    protected $company_id;
    protected $financial_year_id;
   

    public function __construct($company_id,$financial_year_id) 
    {
        $this->company_id = $company_id;
        $this->financial_year_id = $financial_year_id;
    }
    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {
        foreach($collection as $row)
        {

            /****************************Check Already Stock Opening Or not *****************/
            if(isset($row['book_isbn']) && $row['book_isbn']!='')
            {
                $BooksData=Product::orWhere('shortcode',$row['book_isbn'])->orWhere('short_name',$row['book_title'])->first();
                if(!empty($BooksData))
                {
                    if(isset($row['opening_stock']) && $row['opening_stock']!='' && $row['opening_stock']>0)
                    {
                        $OpeningStockData   =   OpeningStock::where('product_id',$BooksData->id)->first();
                        if(empty($OpeningStockData))
                        {
                            $OpeningStock           = OpeningStock::create([
                                'main_qty'          =>  $row['opening_stock'],
                                'product_id'        =>  $BooksData->id,
                                'company_id'        =>  $this->company_id,
                                'financial_year_id' =>  $this->financial_year_id
                            ]);
                        }
                        
                    }
                    
                }
            }
           

            
        }
    }


    public function chunkSize(): int
    {
        return 1000;
    }

    public function transformDate($value, $format = 'Y-m-d')
    {
        try {
            return Carbon::instance(Date::excelToDateTimeObject($value));
            } catch (\ErrorException $e) {
            return Carbon::createFromFormat($format, $value);
        }
    }
}
