<?php

namespace App\Command;

use App\Entity\Interval;
use App\Entity\Filial;
use App\Entity\Department;
use App\Entity\Specialist;
use App\Entity\Location;
use App\Entity\Review;
use App\Entity\Schedule;
use App\Entity\Idoctor;
use App\Entity\Price;
use App\Bundle\Infoclinica\Rest;
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\Bundle\Bitrix\Request as Bitrix;

class DiffDoctorsCommand extends Command
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        parent::__construct();
        $this->container = $container;
    }

    protected static $defaultName = 'app:DiffDoctors';
    protected static $defaultDescription = 'различие Врачей';
    protected $io = null;
    protected $bitrix = null;
    protected $entityManager = null;
    
    protected function configure(): void
    {
        $this
            ->setDescription(self::$defaultDescription)
            ->addArgument('regionId', InputArgument::OPTIONAL, 'region id')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $infoclinica = new Rest();
        $this->entityManager = $this->container->get('doctrine')->getManager();
        $this->io = new SymfonyStyle($input, $output);
        $regionId = $input->getArgument('regionId');
        $this->bitrix = (\App\Bundle\Bitrix\Request::init())->setRegionId($regionId);
        $doctors = $this->bitrix->getDoctors(false); 

        foreach ($doctors as $doctor) {
            $params = $this->loadInfoclinicaIds($doctor);

            if($this->ioError($params['docIds'], 'INFOCLINICA_ID_DOC is NULL', $doctor['ID'])) {
                $params['docIds'][] = 0;
            }
            
            if($this->ioError($params['docDeps'], 'INFOCLINICA_ID_DEP is NULL', $doctor['ID'])) {
                $params['docDeps'][] = 0;
            }

            if($this->ioError($params['docFilials'], 'INFOCLINICA_ID_FILIAL is NULL', $doctor['ID'])) {
                $params['docFilials'][] = 0;
            }

            $this->addFile($doctor);

            if ($this->bitrix->docPropsCode($doctor['ID'], 'HIDE_TIMETABLE', false)) {
                $this->io->warning('infoclinica false');

                var_dump($this->createUpdateForiDoctor($doctor, $params));
            } else {    
                var_dump($this->createUpdateForiDoctor($doctor, $params));
            }
            
            $this->io->warning('end:' . $doctor['ID']);
        }

        return Command::SUCCESS;
    }

    private function addFile($data = '')
    {
          $file = dirname(__DIR__, 2)
            . DIRECTORY_SEPARATOR .'var'
            . DIRECTORY_SEPARATOR. 'report'
            . DIRECTORY_SEPARATOR . \date('Y-m-d') . '.csv';
        $current = '';

        if (file_exists($file)) {
            $current = file_get_contents($file);
            $current .= "\n";
        } else {
            $current .= "ID;NAME;DCODE;DEPARTMENT;FILIAL;B_ACTIVE;I_ACTIVE;C_ACTIVE;\n";
        }

        $current .= $data . "\n";

        file_put_contents($file, $current);
    }

    private function createUpdateForiDoctor($doctor, $params)
    {
        $getIdoc = function($dcode, $deps) {
            $iDoctors = [];

            foreach ($deps as $departmentId) {
                $iDoctors[] = $this->entityManager->getRepository(Idoctor::class)
                    ->findOneBy([
                        'dcode' => $dcode,
                        'departmentId' => $departmentId
                    ]);
            }

            return $iDoctors;
        };

        foreach ($params['docIds'] as $dcode) {
            foreach ($getIdoc($dcode, $params['docDeps']) as $iDoctor) {
                if (!empty($iDoctor)) {
                    $attrs = [
                        'name' => $iDoctor->getName(),
                        'dcode' => $iDoctor->getDcode(),
                        'department' => $iDoctor->getDepartmentId(),
                        'filial' => $iDoctor->getFilialId(),
                        'onlineMode' => $iDoctor->getOnlineMode(),
                        'nearestDate' => $iDoctor->getNearestDate(),
                        'infoclinica' => true
                    ];

                    return ['doctor' => $doctor, 'params' => $params, 'attrs' => $attrs];
                } else {
                    $this->io->error('not found iDoctor:' . $dcode);
                }        
            }
        }
    }

    private function ioError($prop, $msg, $id, $continue = true)
    {
        if (empty($prop[0])) {
            $this->io->error($msg. ': '. $id);
            
            return true;
        }
        
        return false;
    }

    private function loadInfoclinicaIds($doctor)
    {        
        $this->io->success($doctor['NAME']. ' bitrix id: '. $doctor['ID']);
        $data = [
            'docIds' => [], 
            'docDeps' => [],
            'docFilials' => []
        ];

        if (trim($doctor['XML_ID']) !== trim($doctor['ID'])) {
            $data['docIds'][] = preg_replace( '/[^0-9]/', '', $doctor['XML_ID']);
        }

        foreach ($this->bitrix->docPropsCode($doctor['ID'], 'INFOCLINICA_ID') as $prop) {
            $data['docIds'][] = preg_replace( '/[^0-9]/', '', $prop['VALUE']);
        }

        foreach ($this->bitrix->docPropsCode($doctor['ID'], 'DEPARTMENT_INFO') as $prop) {
            $data['docDeps'][] = preg_replace( '/[^0-9]/', '', $prop['VALUE']);
        }
        
        foreach ($this->bitrix->docPropsCode($doctor['ID'], 'INFOCLINICA_ID_DEP') as $prop) {
            $data['docDeps'][] = preg_replace( '/[^0-9]/', '', $prop['VALUE']);
        }

        foreach ($this->bitrix->docPropsCode($doctor['ID'], 'FILIAL_INFO') as $prop) {
            $data['docFilials'][] = preg_replace( '/[^0-9]/', '', $prop['VALUE']);
        }

        $data['docFilials'] = array_diff(array_unique($data['docFilials']), ['']);
        $data['docIds'] = array_diff(array_unique($data['docIds']), ['', 0, '0', '00']);
        $data['docDeps'] = array_diff(array_unique($data['docDeps']), ['']);

        $this->io->info('FILIALS_INFO:'. implode(',', $data['docFilials']));
        $this->io->info('INFOCLINICA_IDS:'. implode(',', $data['docIds']));
        $this->io->info('INFOCLINICA_ID_DEPS:'. implode(',', $data['docDeps']));
       
        return $data;
    }
}
