<?php
/**
 * Created by PhpStorm.
 * User: Alberto Pallotto
 * Date: 07/02/2019
 * Time: 09:48
 */

namespace Limesharp\Stockists\Console\Command\Import;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\App\Filesystem\DirectoryList;

class Stores extends Command
{

    const STORES_FILE = "/stores/stores.csv";
    const STORES_TABLE = "limesharp_stockists_stores";
    const CSV_DELIMITER = "|";

    private $pubDir = null;
    private $csvHeader = null;

    /**
     * @var \Magento\Framework\File\Csv
     */
    private $csv;
    /**
     * @var \Magento\Framework\Filesystem
     */
    private $filesystem;
    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    private $connection;
    /**
     * @var \Magento\Framework\App\Filesystem\DirectoryList
     */
    private $directoryList;
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    private $datetime;

    /**
     * Stores constructor.
     * @param \Magento\Framework\File\Csv $csv
     * @param \Magento\Framework\Filesystem $filesystem
     * @param \Magento\Framework\App\ResourceConnection $connection
     * @param DirectoryList $directoryList
     */
    public function __construct(
        \Magento\Framework\File\Csv $csv,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\App\ResourceConnection $connection,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
        \Magento\Framework\Stdlib\DateTime\DateTime $datetime
    )
    {
        $this->csv = $csv;
        $this->filesystem = $filesystem;
        $this->connection = $connection;
        $this->directoryList = $directoryList;
        $this->datetime = $datetime;

        $this->pubDir = $this->directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::PUB);

        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('stockists:import');
        $this->setDescription('Import stores');
        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("Begin import stores");


        $stores = $this->getStores();
        if (count($stores) == 0) {
            $output->writeln("There aren't any store");
            return;
        }

        $connection = $this->connection->getConnection();
        $tableName = $this->connection->getTableName(self::STORES_TABLE);

        // Truncate all stores
        $connection->query("TRUNCATE `{$tableName}`");

        $j = 0;
        foreach ($stores as $store):

            $fields = "`stockist_id`,`store_id`,`name`,`address`,`city`,`country`,`postcode`,`region`,`email`,`phone`,`link`,`image`,`latitude`,`longitude`,`status`,`updated_at`,
                    `created_at`,`schedule`,`station`,`description`,`intro`,`details_image`,`distance`,`external_link`,`wo_general_indication`,`wo_monday`,`wo_tuesday`,`wo_wednesday`,
                    `wo_thursday`,`wo_friday`,`wo_saturday`,`wo_sunday`
                    ";
            $values = "{$store["stockist_id"]}, '{$store["store_id"]}', '{$store["name"]}', '{$store["address"]}', '{$store["city"]}', '{$store["country"]}', '{$store["postcode"]}', '{$store["region"]}', 
                    '{$store["email"]}', '{$store["phone"]}', '{$store["link"]}', '{$store["image"]}', '{$store["latitude"]}', '{$store["longitude"]}', '{$store["status"]}', 
                    '{$store["updated_at"]}', '{$store["created_at"]}', '{$store["schedule"]}', '{$store["station"]}', '{$store["description"]}', '{$store["intro"]}', 
                    '{$store["image"]}', '{$store["distance"]}', '{$store["external_link"]}', '{$store["wo_general_indication"]}', '{$store["wo_monday"]}', '{$store["wo_tuesday"]}', 
                    '{$store["wo_wednesday"]}', '{$store["wo_thursday"]}', '{$store["wo_friday"]}', '{$store["wo_saturday"]}', '{$store["wo_sunday"]}'
                    ";

            $sql = "INSERT INTO `{$tableName}` ({$fields}) VALUES ({$values});";
            $connection->query($sql);
            $j++;
        endforeach;

        $output->writeln("Imported {$j} stores");
    }

    /**
     * @return string
     */
    private function getStoresFilePath()
    {
        return $this->pubDir . self::STORES_FILE;
    }

    /**
     * @param $string
     * @return null|string|string[]
     */
    private function clearText($string)
    {
        return $string = preg_replace("/[^a-zA-Z0-9\s\-\/\.]/", "", $string);
        //return utf8_encode($string);
    }

    /**
     * @return array
     */
    private function getStores()
    {
        $csvData = $this->readCsv();

        $stores = [];
        $i = 1;
        foreach ($csvData as $store):
            if ($this->checkIfRowisCompleted($store)) {
                continue;
            }
            $store['stockist_id'] = $i;
            $store['store_id'] = '0'; // di default assegno tutti i website
            $store['status'] = 1; // di default assegno sempre lo stato attivo
            $store['created_at'] = $this->datetime->gmtDate();
            $store['updated_at'] = $this->datetime->gmtDate();
            $stores[] = $store;
            $i++;
        endforeach;

        return $stores;
    }

    /**
     * @return array
     */
    private function readCsv()
    {
        // Get file path
        $filePath = $this->getStoresFilePath();

        // Read file
        $this->csv->setDelimiter(self::CSV_DELIMITER);

        // Load stores csv
        $data = $this->csv->getData($filePath);
        $this->csvHeader = array_shift($data);

        $i = 0;
        $formattedData = [];
        foreach ($data as $row) {
            foreach ($row as $key => $value) {
                if (!isset($this->csvHeader[$key])) {
                    continue;
                }

                $formattedData[$i][$this->csvHeader[$key]] = ($value == '0') ? '' : $this->clearText($value);
            }
            $i++;
        }

        return $formattedData;
    }

    /**
     * check if all required fields are completed
     * @param $store
     * @return bool
     */
    private function checkIfRowisCompleted($store)
    {
        $requiredFields = ['name', 'address', 'city', 'country', 'postcode', 'region', 'email', 'phone', 'link', 'image'];
        foreach ($requiredFields as $requiredField):
            if (trim($store[$requiredField]) == '' || empty($store[$requiredField])):
                return false;
            endif;
        endforeach;

        return true;
    }
}