<?php

namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\Entity\DirectCompany;
use App\Entity\DirectReport;
use App\Bundle\Infoclinica\Region;
use App\Bundle\Yandex\Direct;

class DirectCommand extends Command
{
    private $em;
    private $io;

    public function __construct(ContainerInterface $container)
    {
        parent::__construct();
        $this->em = $container->get('doctrine')->getManager();
    }

    protected static $defaultName = 'app:direct';
    protected static $defaultDescription = 'Add a short description for your command';

    protected function configure(): void
    {
        $this
            ->setDescription(self::$defaultDescription)
            // ->addArgument('file', InputArgument::OPTIONAL, 'variant update table')
            ->addArgument('regionId', InputArgument::OPTIONAL, 'variant update table')
        ;
    }

    //  php bin/console app:direct vlg.csv
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->io = new SymfonyStyle($input, $output);
        
        // $file = $input->getArgument('file');
        $regionId = $input->getArgument('regionId');

        $report = (new Direct($regionId))->getReport();

        foreach ($report as $item) {
            $this->addDirectReport($item);     
        }

        return Command::SUCCESS;
    }

    private function addDirectReport($item)
    {
        // $directReport = $this->em->getRepository(DirectReport::class)
        //     ->findOneBy(['companyId' => (int) $item['1']]);

        $directReport = new DirectReport();

        $date = \DateTime::createFromFormat(
            'Y-m-d',
            \date("Y-m-d", \strtotime($item['Date']))
        );

        $directReport
            ->setDate($date)
            ->setCampaignId($item['CampaignId'])
            ->setAdGroupId($item['AdGroupId'])
            ->setAdId($item['AdId'])
            ->setImpressions($item['Impressions'])
            ->setClicks($item['Clicks'])
            ->setCost($item['Cost'])
            ->setConversions($item['Conversions'])
        ;

        $this->em->persist($directReport);
        $this->em->flush();

        $this->io->success($directReport->getId());
    }

    private function uploadCSV($csv)
    {
        $city = Region::getCurrentName($regionId);

        $dir = dirname(__FILE__, 3) . '/var/direct/';
        
        $csv = $this->readCSV($dir. $file);

        if ($csv['success'] == true) {

            foreach ($csv['data'] as $item) {
                if ((int) $item['1'] == 0) {
                    $this->io->warning('companyId = 0');

                    continue;
                }

                $directCompany = $this->em->getRepository(DirectCompany::class)
                    ->findOneBy(['companyId' => (int) $item['1']]);
                
                if (!$directCompany) {
                    $directCompany = new DirectCompany;
                }

                $directCompany
                    ->setCompanyId((int) $item['1'])
                    ->setName($item['0'])
                    ->setCity($city);

                $this->em->persist($directCompany);
                $this->em->flush();
                $this->io->success('success: ' . $directCompany->getId());
            }

        } else {
            $this->io->error($csv['message']);
        }
    }

    private function readCSV($path = '')
    {
        $response = ['success' => false];

        if (! file_exists($path)) {
            $response['message'] = 'csv file not exists: ' . $path;   
            return $response;
        }

        $row = 1;
        
        if (($handle = fopen($path, "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
                $num = count($data);
                $row++;

                for ($c=0; $c < $num; $c++) {
                    $response['data'][$row][$c] = $data[$c];  
                }
            }

            fclose($handle);
            $response['success'] = true;
        }

        return $response;
    }
}
