<?php

namespace Autogedal\Extend\Cron;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\HTTP\Client\Curl;
use Psr\Log\LoggerInterface;

class SplitAleoFeed
{
    protected Filesystem $filesystem;
    protected LoggerInterface $logger;
    protected Curl $curl;

    protected string $feedUrl = 'https://b2b.aleo.ro/userfiles/CCEAD380-5E19-4246-96CD-5E0BBEB6C560/feeds/CEADE686-459A-4B2F-9921-99CED181A2DF.csv?key=E277C639-7F52-4862-ABE7-D5493AA705A2';

    public function __construct(
        Filesystem $filesystem,
        LoggerInterface $logger,
        Curl $curl
    ) {
        $this->filesystem = $filesystem;
        $this->logger = $logger;
        $this->curl = $curl;
    }

    public function execute()
    {
        try {
            $mediaPath = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA)->getAbsolutePath();

            $this->curl->setOptions([
                CURLOPT_TIMEOUT => 300,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_MAXREDIRS => 5,
                CURLOPT_SSL_VERIFYPEER => false,
            ]);
            $this->curl->get($this->feedUrl);

            if ($this->curl->getStatus() !== 200) {
                $this->logger->error('SplitAleoFeed: Failed to download feed. HTTP ' . $this->curl->getStatus());
                return;
            }

            $content = $this->curl->getBody();
            if (empty($content)) {
                $this->logger->error('SplitAleoFeed: Downloaded feed is empty.');
                return;
            }

            $handle = fopen('php://temp', 'r+');
            fwrite($handle, $content);
            rewind($handle);

            $header = fgetcsv($handle, 0, ',');
            if (!$header) {
                fclose($handle);
                $this->logger->error('SplitAleoFeed: Empty or invalid CSV.');
                return;
            }

            $categoryIndex = array_search('Categorie', $header);
            if ($categoryIndex === false) {
                fclose($handle);
                $this->logger->error('SplitAleoFeed: Column "Categorie" not found.');
                return;
            }

            $suportBiciclete             = [$header];
            $cutiiPortbagaj              = [$header];
            $suportSchiuri               = [$header];
            $accesoriiCutiiPortbagaj     = [$header];
            $accesoriiSuporturiBicicleta = [$header];

            while (($row = fgetcsv($handle, 0, ',')) !== false) {
                $categorie = trim($row[$categoryIndex] ?? '');
                $parent = str_contains($categorie, '/')
                    ? trim(substr($categorie, 0, strpos($categorie, '/')))
                    : $categorie;

                if ($parent === 'Suporturi biciclete') {
                    $leaf = str_contains($categorie, '/')
                        ? trim(substr($categorie, strpos($categorie, '/') + 1))
                        : $categorie;
                    $bicicletaMap = [
                        'Suporturi biciclete cu prindere pe carligul de remorcare' => 'Pe Carligul De Remorcare',
                        'Suporturi biciclete cu prindere pe haion'                  => 'Pe Haion',
                        'Suporturi biciclete cu prindere pe barele transversale'    => 'Pe Barele Transversale',
                        'Suporturi biciclete cu prindere pe roata de rezerva'       => 'Pe Roata De Rezerva',
                        'Accesorii Suporturi Biciclete'                 => 'Accesorii Suporturi Biciclete',
                    ];
                    $row[$categoryIndex] = $bicicletaMap[$leaf] ?? $leaf;
                    $suportBiciclete[] = $row;
                } elseif ($parent === 'Cutii portbagaj') {
                    $leaf = str_contains($categorie, '/')
                        ? trim(substr($categorie, strpos($categorie, '/') + 1))
                        : $categorie;
                    if (str_starts_with($leaf, 'Cutii portbagaj ')) {
                        $leaf = ucfirst(trim(substr($leaf, strlen('Cutii portbagaj '))));
                    }
                    $leaf = strtr($leaf, [
                        'pe barele transversale' => 'pe bare transversale',
                    ]);
                    $row[$categoryIndex] = $leaf;
                    $cutiiPortbagaj[] = $row;
                } elseif ($parent === 'Suporturi schiuri') {
                    $suportSchiuri[] = $row;
                } elseif ($parent === 'Accesorii Cutii portbagaj') {
                    $accesoriiCutiiPortbagaj[] = $row;
                } elseif ($parent === 'Accesorii Suporturi bicicleta') {
                    $accesoriiSuporturiBicicleta[] = $row;
                }
            }
            fclose($handle);

            $this->saveCsv($mediaPath . 'suport_biciclete.csv', $suportBiciclete);
            $this->saveCsv($mediaPath . 'cutii_portbagaj.csv', $cutiiPortbagaj);
            $this->saveCsv($mediaPath . 'suport_schiuri.csv', $suportSchiuri);
            $this->saveCsv($mediaPath . 'accesorii_cutii_portbagaj.csv', $accesoriiCutiiPortbagaj);
            $this->saveCsv($mediaPath . 'accesorii_suporturi_bicicleta.csv', $accesoriiSuporturiBicicleta);

            $this->logger->info('SplitAleoFeed: CSV processed and split successfully.');
        } catch (\Exception $e) {
            $this->logger->error('SplitAleoFeed: Error: ' . $e->getMessage());
        }
    }

    protected function saveCsv($filePath, $data)
    {
        $fp = fopen($filePath, 'w');
        foreach ($data as $line) {
            fputcsv($fp, $line);
        }
        fclose($fp);
    }
}
