<?php

namespace App\Imports;

use App\Models\Category;
use App\Models\Product;
use App\Models\ProductImage;
use App\Traits\GeneralHelperTrait;
use Exception;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class ProductsImport implements ToModel, WithHeadingRow
{
    use GeneralHelperTrait;

    protected $companyId;
    public function __construct($companyId)
    {
        $this->companyId = $companyId;
    }

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        try{
            $priceData = $this->extractPrice($row['price']); // Replace 'price' with the actual column name
            $categoryId = Category::where('name', $row['category'])->value('id');
    
            $bestBefore = is_numeric($row['best_before']) 
            ? Date::excelToDateTimeObject($row['best_before'])->format('Y-m-d') 
            : \Carbon\Carbon::parse($row[1])->format('Y-m-d');

            if($this->companyId){
                $product = Product::create([
                    'company_id'    => $this->companyId ?? $row['company'] ?? 0,
                    'category_id'   => $categoryId ?? 1,
                    'name'          => $row['name'],
                    'unit_type'     => $row['unit_type'],
                    'unit_size'     => $row['size'],
                    'unit_per_case' => $row['packing'],
                    'quantity'      => $row['qunatity'],
                    'type'          => $row['type'] ?? 'Buying',
                    'stock_location' => $row['stock_location'] ?? '',
                    'currency'      => $priceData['currency'] ?? '$',
                    'price'         => $priceData['amount'] ?? 0,
                    'is_contact_company' => $priceData['label'],
                    'description'   => $row['description'] ?? "",
                    'expiry_date'   => $bestBefore ?? null,
                    'slug'          => $this->createUniqueSlug($row['name'], 'App\Models\Product'),
                ]);

                if(isset($row['image']) && $row['image'] != null){
                    $extension = pathinfo($row['image'], PATHINFO_EXTENSION);

                    ProductImage::create([
                        'product_id' => $product->id,
                        'file' => $row['image'],
                        'ext' => $extension ?? null
                    ]);
                }

                return $product;
            }
        }catch(Exception $ex){
            Log::error("Error in Import Products", array('data' => $ex->getMessage()));
        }
        return null;
    }

    private function extractPrice($value)
    {
        // Handle "Contact for Price" case
        if (stripos($value, 'contact') !== false) {
            return [
                'currency' => '$',
                'amount'   => 0.00,
                'label'    => 1, // Store as a label
            ];
        }

        // Extract currency and price using regex
        // preg_match('/([^\d.,]*)([\d.,]+)/', $value, $matches);
        preg_match('/^\s*([^\d\s]+)?\s*([\d,.]+)/', $value, $matches);
        return [
            'currency' => $matches[1] ?? '$',  // Extract currency symbol
            'amount'   => isset($matches[2]) ? floatval(str_replace(',', '', $matches[2])) : null, // Convert to float
            'label'    => 0,
        ];
    }
}
