<?php

namespace KupShop\PohodaBundle\Command;

use KupShop\PohodaBundle\Utils\PohodaBase;
use Query\Operator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class UserImportAddress extends command
{
    use PohodaBase;
    protected static $defaultName = 'shop:pohoda-import-address';
    protected $requestTpl = 'requests/usersIn.tpl';

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Starting import users pohoda id address');

        $request = $this->pohodaConnector->getRequestContent($this->requestTpl, ['full' => true]);
        $request = $this->replace($request);

        $xml = simplexml_load_string($this->pohodaConnector->sendRequest($request));

        if ($xml) {
            sqlQuery('UPDATE users SET pohoda_id_address=NULL');
            foreach ($xml->xpath('rsp:responsePackItem/lAdb:listAddressBook/lAdb:addressbook') as $item) {
                if (!empty($item->xpath('adb:addressbookHeader/adb:identity/typ:shipToAddress[last()]/typ:id'))) {
                    $user = [
                        'id' => strval($item->xpath('adb:addressbookHeader/adb:id')[0]),
                        'pohoda_id_address' => strval($item->xpath('adb:addressbookHeader/adb:identity/typ:shipToAddress[last()]/typ:id')[0]),
                    ];

                    sqlQueryBuilder()
                        ->update('users')
                        ->set('pohoda_id_address', ':addrid')
                        ->setParameter(':addrid', $user['pohoda_id_address'])
                        ->andWhere(Operator::equals(['pohoda_id' => $user['id']]))
                        ->execute();
                }
            }
        }

        $output->writeln('Inport address id completed.');

        return 0;
    }
}
