<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Models\Product;
use App\Models\ProductImage;
use App\Models\ProductCategory;

use Maatwebsite\Excel\Concerns\WithHeadingRow;

class BulkProductUploadImport implements ToCollection, WithHeadingRow
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $rows)
    {
        foreach($rows as $row){
            $pro = Product::create([
                'product_name' => $row['title'],
                'slug' => Product::getUniqueSlug($row['title']),
                'description' => $row['description'],
                'content' => $row['content'],
                'price' =>$row['price'],
                'actual_price' =>$row['mrp'],
                'delivery_delay_days' =>$row['delay_days'],
                'alt_key' =>$row['alt'],
                'meta_title' =>$row['meta_title'],
                'meta_description' =>$row['meta_description'],
                'extra_field' =>$row['agent_link'],
                'fnid' =>$row['img_id'],
            ]);
            ProductImage::create([
                'product_id' => $pro->id,
                'name' => $row['img_id'].".webp",
                'default_image' => 'Y',
            ]);
            $category = explode("|",$row['category']);
            foreach($category as $key => $cat){
                ProductCategory::create([
                    'product_id' => $pro->id,
                    'category_id' => $cat,
                ]);
            }
            if($pro){
                $sku_generate_array = array();
                $sku_generate_array['product_type'] = 'A';
                $sku_generate_array['delivery_by']  = 'C';
                $sku_generate_array['product_id']   = $pro->id;
                $sku_generate_array['country_id']   = 99;
                $sku = @$this->generate_sku($sku_generate_array);
                /* Update product sku */
                Product::where('id',$pro->id)->update(['sku'=>$sku]);
            }
        }
         
    }
    public function generate_sku($request){
        $formated_number = '';
        $total_digit_number = '00000';
        $product_id = $request['product_id'];
        $product_id_length = strlen((string)$product_id);
        $concate_digit_and_pid = $total_digit_number.$product_id;
        $formated_product_number = substr($concate_digit_and_pid, $product_id_length);
        
        
        $country_sort_code = "ABC";
        $webside_code = 1;
        $formated_number = $request['product_type'].$request['delivery_by'].$formated_product_number.$country_sort_code;
        return $formated_number;
    }
}
