<?php

namespace App\Imports\Ecommerce\Product;

use App\Models\Ecommerce\Product\Inventory\Inventory;
use App\Models\Ecommerce\Product\Product\Product;
use App\Repositories\Ecommerce\Product\ProductRepository;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Row;

class ProductImport implements OnEachRow, WithHeadingRow
{
    public function __construct(
        protected int $channel_id
    ) {}

    public function onRow(Row $row)
    {
        $rowIndex = $row->getIndex();
        $row = $row->toArray();

        $product = Product::query()
            ->whereJsonContains('options->channel_id', $this->channel_id)
            ->whereJsonContains('options->ynamdyr_product_code', $row['product_code'])
            ->first();

        $product ? $this->updateProduct($product, $row) : $this->createProduct($row);

        // brand_id
        // categories
        // collections
        // images
        // inventories
        // options => json_encode(ProductRepository::shippingAttributes())
    }

    public function createProduct($row)
    {
        $product = new Product(array_merge(
            $this->baseColumns($row),
            [
                'stock' => $row['stock'],
                'options' => json_encode(
                    array_merge(
                        ProductRepository::shippingAttributes(),
                        [
                            'channel_id' => $this->channel_id,
                            'ynamdyr_product_code' => $row['product_code'],
                            // 'ynamdyr_brand_id' => $row['brand_id'],
                            // 'ynamdyr_category_id' => $row['category_id'],
                        ]
                    )
                ),
            ]
        ));

        $product->save();

        $inventory = Inventory::where('channel_id', $this->channel_id)->first('id')?->id;

        if ($inventory) {
            $product->inventories()->attach($inventory, ['stock' => $row['stock']]);
        }

        $product->channels()->attach($this->channel_id);
    }

    public function updateProduct($product, $row)
    {
        $inventory = Inventory::where('channel_id', $this->channel_id)->first(['inventories.id']);

        if ($inventory) {
            $stockRecord = DB::table('inventory_product')
                ->where('product_id', $product->id)
                ->where('inventory_id', $inventory->id)
                ->get();

            if ($stockRecord->isNotEmpty()) {
                DB::table('inventory_product')
                    ->where('product_id', $product->id)
                    ->where('inventory_id', $inventory->id)
                    ->update([
                        'stock' => $row['stock'],
                    ]);
            } else {
                DB::table('inventory_product')
                    ->where('product_id', $product->id)
                    ->where('inventory_id', $inventory->id)
                    ->insert([
                        'product_id' => $product->id,
                        'inventory_id' => $inventory->id,
                        'stock' => $row['stock'],
                    ]);
            }
        }

        $product->update(array_merge(
            $this->baseColumns($row),
            [
                'stock' => $product->inventories()->sum('inventory_product.stock'),
            ]
        ));
    }

    public function baseColumns($row)
    {
        return [
            'name' => $row['name_tm'],
            'barcode' => $row['barcode'],
            'description' => $row['description_tm'],
            'old_price_amount' => $row['old_price'],
            'cost_amount' => $row['sale_price'],
            'price_amount' => $row['sale_price'],
            'is_visible' => true,
        ];
    }
}
