<?php

namespace App\Console\Commands;

use App\Helpers\StringHelper;
use App\Models\Product;
use App\Shopify\ShopifyService;
use Illuminate\Console\Command;

class CheckHandleDuplicates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'area:check-handle-duplicates';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Checks for duplicate orders in SAP';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(ShopifyService $service)
    {
        $products = Product::whereNull('parent_id')->where('disabled', 0)->get();
        $handles = [];
        foreach ($products as $product) {
            $productName = $service->getShopifyProductName($product, config('shopify-app.default_language'));
            if ($product->is_parent) {
                $handle = StringHelper::urlize(ltrim($product->sap_matnr, '0') . ' ' . $productName);
            } else {
                $handle = StringHelper::urlize($productName);
            }
            if (in_array($handle, $handles)) {
                $this->info("Duplicate handle found: {$product->is_parent} $handle for product ID: {$product->id}");
            } else {
                $handles[] = $handle;
            }
        }
        return 0;
    }
}
