<?php

declare(strict_types=1);

namespace Leadlion\StockUpdates\Cron;

use Magento\Catalog\Api\Data\BasePriceInterfaceFactory;
use Magento\Catalog\Api\Data\SpecialPriceInterfaceFactory;
use Magento\Catalog\Model\Product\Price\BasePriceStorage;
use Magento\Framework\Exception\LocalizedException;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Model\Product\Price\SpecialPriceStorage;
use Monolog\Logger as MonoLogger;
use Monolog\Handler\StreamHandler;
use Monolog\Level;

class PtcPrices
{
    const PTC_FEED_URL = "https://erp.ptc-auto.ro/feed/products_qty_price_feed_4.csv?access_token=b82cd663-0bf8-49d8-aa42-dd74b539fcec";

    private $basePriceStorage;
    private $specialPriceStorage;

    private $basePriceInterfaceFactory;
    private $specialPriceInterfaceFactory;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    public function __construct(
        BasePriceStorage $basePriceStorage,
        BasePriceInterfaceFactory $basePriceInterfaceFactory,
        CollectionFactory $collectionFactory,
        SpecialPriceStorage $specialPriceStorage,
        SpecialPriceInterfaceFactory $specialPriceInterfaceFactory
    ) {
        $this->basePriceStorage = $basePriceStorage;
        $this->specialPriceStorage = $specialPriceStorage;
        $this->basePriceInterfaceFactory = $basePriceInterfaceFactory;
        $this->specialPriceInterfaceFactory = $specialPriceInterfaceFactory;
        $this->collectionFactory = $collectionFactory;
    }

    public function execute()
    {
        $monolog = new MonoLogger('ptc_pricess');
        $monolog->pushHandler(new StreamHandler(BP . '/var/log/ptc_prices.log', Level::Debug));
        $logger = $monolog;

        $feedContent = $this->getFeedContent($logger);
        $skuFzs[] = array_keys($feedContent);

        $collection = $this->collectionFactory->create()
            ->addAttributeToSelect('sku_fz')
            ->addAttributeToSelect('sku')
            ->addAttributeToFilter('sku_fz', $skuFzs)
            ->addAttributeToFilter('attribute_set_id', ['neq' => 65]);

        $productPrices = [];

        foreach ($collection as $product) {
            if (isset($feedContent[$product->getSkuFz()])) {
                $sku = $product->getSku();
                $stockInfo = $feedContent[$product->getSkuFz()];
                $listPrice = $stockInfo[3];

                if ($listPrice < 1) {
                    continue;
                }
                $productPrices[] = [
                    'sku' => $sku,
                    'price' => $listPrice,
                    'special_price' => $listPrice,
                    'store_id' => 0
                ];

                $logger->info('PTC $item: '.$sku);
                $logger->info('$product sku: ' .$product->getData('sku').' sku_fz: '. $product->getData('sku_fz'). ' list price: '. $listPrice);
            }
        }

        $prices = [];
        $specialPrices = [];

        foreach ($productPrices as $productPrice) {
            $priceObject = $this->basePriceInterfaceFactory->create()
                ->setSku($productPrice['sku'])
                ->setPrice($productPrice['price'])
                ->setStoreId($productPrice['store_id']);
            $prices[] = $priceObject;

            $specialPriceObject = $this->specialPriceInterfaceFactory->create()
                ->setSku($productPrice['sku'])
                ->setPrice($productPrice['special_price'])
                ->setStoreId($productPrice['store_id']);
            $specialPrices[] = $specialPriceObject;
        }

        try {
            $this->basePriceStorage->update($prices);
            $this->specialPriceStorage->update($specialPrices);
        } catch (LocalizedException $e) {
            $logger->info('Error updating PTC product prices: '.$e->getMessage());
        }
    }

    private function getFeedContent($logger)
    {
        /*
            $data[0] - SKU
            $data[1] - Quantity
            $data[2] - Price
            $data[3] - List Price
            $data[4] - Name
        */
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::PTC_FEED_URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            $logger->info('Error when reading the file:' . curl_error($ch));
            curl_close($ch);
            exit;
        }

        curl_close($ch);

        $data = [];
        $lines = explode(PHP_EOL, $response);
        foreach ($lines as $line) {
            $data[] = str_getcsv($line);
        }

        $data = array_filter($data);
        
        $contentFile = [];
        foreach ($data as $key => $info) {
            $contentFile[$info[0]] = $info;
        }
        
        return $contentFile;
    }
}
