<?php
//require_once sfConfig::get('sf_lib_dir') . '/Classes/UnitPay.ru/UnitPay.php';

class bugFixesTask extends sfBaseTask
{
    protected function configure()
    {
        $this->addOptions(array(
            new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name', 'arm'),
            new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
            new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
        ));

        $this->namespace = 'bug';
        $this->name = 'fixes';
        $this->briefDescription = '';
        $this->detailedDescription = <<<EOF
The [bug:fixes|INFO] task does things.
Call it with:

  [php symfony bug:fixes|INFO]
EOF;
    }

    protected function execute($arguments = array(), $options = array())
    {
        $databaseManager = new sfDatabaseManager($this->configuration);
        $connection = $databaseManager->getDatabase($options['connection'])->getConnection();



        $q = Doctrine_Query::create()
            ->select("*, NOW()")
            ->from("Blocking")
            ->fetchArray();
        echo "<pre>";
        print_r($q);
        echo "</pre>";
        die();
        die();



        $this->log('ClientOrderItem problem_id is null..');
        Doctrine_Query::create()
            ->set("problem_id", "NULL")
            ->update("ClientOrderItem")
            ->execute();

        $this->log('CourierProblem delete..');
        Doctrine_Query::create()
            ->delete("CourierProblem")
            ->execute();

        $this->log('ClientProblem delete..');
        Doctrine_Query::create()
            ->delete("ClientProblem")
            ->execute();

        $this->log('CourierMoney delete..');
        Doctrine_Query::create()
            ->delete("CourierMoney")
            ->execute();

        $this->log('ClientOrderItem delete..');
        Doctrine_Query::create()
            ->delete("ClientOrderItem")
            ->execute();

        $this->log('Pay delete..');
        Doctrine_Query::create()
            ->delete("Pay")
            ->execute();

        $this->log('User total..');
        Doctrine_Query::create()
            ->set('courier_money_total', '0')
            ->set('courier_money_available', '0')
            ->update("User")
            ->execute();

        $this->log('Blocking delete..');
        Doctrine_Query::create()
            ->delete("Blocking")
            ->execute();

        $this->log('ClientOrder delete..');
        Doctrine_Query::create()
            ->delete("ClientOrder")
            ->execute();

        $this->log('clean completed');




        die();

//

        /*Запрос подтверждения на вынос мусора - работает*/
//        $a = json_decode('{"notification":{"title":"\u041a\u0443\u0440\u044c\u0435\u0440 \u0432\u044b\u043d\u0435\u0441\u0435\u0442 \u043c\u0443\u0441\u043e\u0440 \u0441\u0435\u0433\u043e\u0434\u043d\u044f \u0441 10:00 \u0434\u043e 12:00","body":"\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430 \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u0435 \u0430\u043a\u0442\u0443\u0430\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0432\u044b\u043d\u043e\u0441\u0430","sound":"default","show_in_foreground":true},"data":{"type":"route","route":"Learn","props":{"orderId":"60445"}},"content_available":true,"priority":"high"}', true);

        /*Курьер начал выполнять заказ - работает*/
//        $a = json_decode('{"notification":{"title":"\u041a\u0443\u0440\u044c\u0435\u0440 \u043d\u0430\u043f\u0440\u0430\u0432\u0438\u043b\u0441\u044f \u043a \u0432\u0430\u043c","body":"\u041f\u0440\u0438\u0433\u043e\u0442\u043e\u0432\u044c\u0442\u0435 \u0432\u0430\u0448\u0438 \u043c\u0443\u0441\u043e\u0440\u043d\u044b\u0435 \u043c\u0435\u0448\u043a\u0438.\r\n\u041c\u043e\u0436\u043d\u043e \u0432\u044b\u0441\u0442\u0430\u0432\u0438\u0442\u044c \u0438\u0445 \u0437\u0430 \u0434\u0432\u0435\u0440\u044c","sound":"default","show_in_foreground":true},"data":{"type":"message"},"content_available":true,"priority":"high"}', true);

        /*Заказ выполнен*/
        $a = json_decode('{"notification":{"title":"\u0412\u0430\u0448 \u0437\u0430\u043a\u0430\u0437 \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d!","body":"\u0412\u0430\u043c \u043f\u043e\u043d\u0440\u0430\u0432\u0438\u043b\u0441\u044f \u0432\u044b\u043d\u043e\u0441 \u043c\u0443\u0441\u043e\u0440\u0430? \u041e\u0446\u0435\u043d\u0438\u0442\u0435, \u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0443\u0441\u043b\u0443\u0433\u0443","sound":"default","show_in_foreground":true},"data":{"type":"route","route":"Main"},"content_available":true,"priority":"high"}', true);
//        echo "<pre>";
//        print_r($a);
//        echo "</pre>";
//        die();

        $a['registration_ids'] = array('duCMpNkjTVajwQE_n61-3s:APA91bF_VUalhcgPtovfGzfVvFMO5Rnmu2TlWCdziPb_NT7T-YGvRGQx6yF4DnNID-aJ41hdAKzEWbx54d8LGl3b2l3MZL0LjPwZ6YWFApxHNA7lFUV1vLwCLePPNhWUPEqEC9Awa2zn');

        $this->log(ProjectUtils::pushPost($a));
        die();


        die();

        $tokens = Doctrine_Query::create()
            ->select("u.id, s.id, s.token")
            ->from("User u")
            ->innerJoin("u.Session s INDEXBY s.token")
            ->where("s.user_id = " . 15)
            ->andWhere("u.deleted_at IS NULL")
            ->andWhere("u.is_push = 1")
            ->andWhere("s.token IS NOT NULL")
            ->groupBy("s.token")
            ->fetchArray();
        echo "<pre>";
        print_r($tokens);
        echo "</pre>";
        die();
        die();

        try {
            $this->log('before');

            throw new Exception('bad ip ');

            $this->log('after');

        } catch (Exception $e) {
            $this->log($e->getMessage());
        }

        die();

        $v = new sfWidgetFormSelect(array('choices' => array('ya', 'uni')));
        echo $v->render('a');
        die();


        $this->log('done');
        die();
        $cm = new CourierMoneyOut();


        $money_out = new CourierMoneyOut();
        $money_out['courier_id'] = 2;
        $money_out['status'] = 'wait';
        $money_out['created'] = date('Y-m-d H:i:s');
        $money_out['total'] = 1;
        $money_out->save();

        die();


// Project Data
        $domain = 'unitpay.money'; // Your working domain: unitpay.money or unitpay.ru
        $projectId  = sfConfig::get('app_unitpay_projectId');
        $secretKey  = sfConfig::get('app_unitpay_secretKeyTest');



        /*
         *

            $payment = $client->createPayment(
                array(
                    'amount' => array(
                        'value' => $pay->getTotal(),
                        'currency' => 'RUB',
                    ),
                    'confirmation' => array(
                        'type' => 'redirect',
                        'return_url' => url_for('@pay_complete?id=' . $pay->getId(), true),*/

        $unitPay = new UnitPay($domain, $secretKey);
        sfApplicationConfiguration::getActive()->loadHelpers(array('Url'));
        $response = $unitPay->api('initPayment', [
            'login'     => 'sergey@neftespecservis.ru',
            'test'     => '1',
            'ip'     => '109.195.148.246',



            'resultUrl'     => url_for('@pay_complete?id=' . 1, true),
            'backUrl'     => url_for('@pay_complete?id=' . 1, true),
            'account'     => 'id user',
            'desc'        => 'Оплата услуг по выносу мусора №',
            'sum'         => 1,
            'paymentType' => 'card',
            'currency'    => 'RUB',
            'projectId'   => $projectId
        ]);

// If need user redirect on Payment Gate
        if (isset($response->result->type)
            && $response->result->type == 'redirect') {
            // Url on PaymentGate
            $redirectUrl = $response->result->redirectUrl;
            // Payment ID in Unitpay (you can save it)
            $paymentId = $response->result->paymentId;
            // User redirect

            $this->log(1);
            $this->log($redirectUrl);



// If without redirect (invoice)
        } elseif (isset($response->result->type)
            && $response->result->type == 'invoice') {
            // Url on receipt page in Unitpay
            $receiptUrl = $response->result->receiptUrl;
            // Payment ID in Unitpay (you can save it)
            $paymentId = $response->result->paymentId;
            // Invoice Id in Payment Gate (you can save it)
            $invoiceId = $response->result->invoiceId;
            // User redirect


            $this->log(2);
            $this->log($receiptUrl);


// If error during api request
        } elseif (isset($response->error->message)) {
            $error = $response->error->message;
            print 'Error: '.$error;

            $this->log(3);
            $this->log($error);

        }




        die();

        $tokens = Doctrine_Query::create()
            ->select("id, token")
            ->from("Session INDEXBY token")
            ->where("token IS NOT NULL")
            ->groupBy("token")
            ->fetchArray();
        if(count($tokens) > 0){
            PushTemplate::send('clientOrderStarted', array_keys($tokens));
        }



        die();

        $addresses = Doctrine_Query::create()
            ->select("*")
            ->from("Address")
            ->where("user_id = 2")
            ->groupBy("street_home")
            ->fetchArray();
        $sub = Doctrine::getTable("Subscription")->findOneByPeriod("every_day");
        $user = Doctrine::getTable("User")->findOneByEmail("mur@atmapro.ru");
        if($sub){
            if(count($addresses) > 0){
                if($user){
                    $add_ids = array();
                    for($i = 0; $i < 100; $i++){
                        foreach (ClientOrder::$time_interval as $interval){
                            $h = explode('-', $interval)[0];
                            $h = strlen($h) === 1 ? '0' . $h : $h;

                            $start = date('Y-m-d ' . $h . ':00:00');
//                            $start = date('Y-m-d H:i:s', strtotime('+' . $i . ' days', strtotime($start)));

                            $address = $addresses[array_rand($addresses)];

                            $order = new ClientOrder();
                            $order->fromArray(array(
                                'address_street_home' => $address['street_home'],
                                'address_coords' => $address['coords'],
                                'address_doorway' => $address['doorway'],
                                'address_level' => $address['level'],
                                'address_flat' => $address['flat'],
                                'address_doorphone' => $address['doorphone'],
                                'address_comment' => $address['comment'],
                                'user_id' => $user['id'],
                                'is_payed' => true,
                                'subscription_id' => $sub['id'],
                                'start' => $start,
                                'total' => $sub->getPrice(),
                                'total_wh_discount' => $sub->getPrice()
                            ));
                            $order->save();

                            $add_ids[] = $order->getId();
                            $this->log('added order ' . $order->getId() . ' / ' . $i . '. COUNT items ' . Doctrine_Query::create()
                                    ->from("ClientOrderItem")
                                    ->where("client_order_id = ?", $order->getId())
                                    ->count());
                        }
                    }

                    if(count($add_ids) > 0){
                        Doctrine_Query::create()
                            ->update("ClientOrderItem")
                            ->set("is_confirm", "1")
                            ->whereIn("client_order_id", $add_ids)
                            ->execute();
                    }

                    $this->log('COMPLETED!!! created ' . count($add_ids) . ' orders');

                }else{
                    $this->log('!!! user empty !!!');
                }
            }else{
                $this->log('!!! addresses empty !!!');
            }
        }else{
            $this->log('!!! sub empty !!!');
        }
        die();

        $page = Doctrine::getTable("Page")->find(5);

//        $page = new Page();
//        $page['title'] = 'test';
//        $page['alias'] = 'test' . rand(1, 10000);
//        $page['body'] = 'test';
        $page['is_activated'] = true;
        $page->save();



        die();

        $this->log(rtrim(number_format(23, 2, ',', ' '), ',00'));
        die();

        $headers = array("To" => "someone@nowhere.net",
            "From" => "noone@somewhere.net",
            "Subject" => "A signed and encrypted message.");

// Sign the message first

        $message = sfConfig::get('sf_log_dir') . '/test.txt';
        $signed = sfConfig::get('sf_log_dir') . '/signed.txt';

        openssl_pkcs7_sign("msg.txt","signed.txt",
            "signing_cert.pem",array("private_key.pem",
                "password"),array());

// Get the public key certificate.
        $pubkey = file_get_contents("cert.pem");

//encrypt the message, now put in the headers.
        openssl_pkcs7_encrypt("signed.txt", "enc.txt",
            $pubkey,$headers,0,1);

        $data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
        $parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
        mail($mail, $subject, $parts[1], $parts[0]);

//        $pkcs7_pack




        die();



        if($response){

            $cert_path = ''/*путь к сертификату*/;
            $cert_pass = ''/*пароль*/;
            $filename = $out->getId() . '_' . ProjectUtils::generateUuid();
            $response_path = sfConfig::get('sf_data_dir') . '/ym/out/response/dirty/' . date('Y-m') . '/' . $filename;
            $dir = preg_replace('/(.*)\/.*$/', '$1', $response_path);
            if(!file_exists($dir)){
                mkdir($dir, 0755, true);
            }
            file_put_contents($response_path, $response);
            if(openssl_pkcs7_verify($response_path, false, false, array($cert_path)) === true){
                $clean_file = sfConfig::get('sf_data_dir') . '/ym/out/response/clean/' . $filename;
                if(openssl_pkcs7_decrypt($response_path, $clean_file, file_get_contents($cert_path), array($cert_path, sfConfig::get('app_ym_out_key'))) === true){



                }
            }
        }



        die();

        /*<testDepositionRequest agentId="123"
                         clientOrderId="12345"
                         requestDT="2011-07-01T20:38:00.000Z"
                         dstAccount="410011234567"
                         amount="10.00"
                         currency="643"
                         contract="Выигрыш в игре Сфера"/>*/




        $xw = new XMLWriter();
        $xw->openMemory();
        $xw->startDocument('1.0', 'UTF-8');

        $xw->startElement('testDepositionRequest');
        $xw->writeAttribute('agentId', sfConfig::get('app_ym_agentId'));
        $xw->writeAttribute('clientOrderId', ''/*уникальный id*/);
        $xw->writeAttribute('requestDT', date('c'));
        $xw->writeAttribute('dstAccount', '25700130535186');
        $xw->writeAttribute('amount', '100');
        $xw->writeAttribute('currency', '643');
        $xw->writeAttribute('contract', 'Вывод средств курьера в приложении Явынесу');

        $xw->startElement('paymentParams');
        $xw->writeElement('skr_destinationCardSynonim', '');
        $xw->writeElement('pof_offerAccepted', 1);
        $xw->writeElement('cps_ymAccount', '');
        $xw->endElement();

        $xw->endElement();
        $xw->endDocument();
//        $xw->outputMemory();



        file_put_contents(sfConfig::get('sf_log_dir') . '/money_out_test.xml', $xw->outputMemory());

        /*
$datetime = time();

      $xw = new XMLWriter();
      $xw->openMemory();
      $xw->startDocument('1.0', 'UTF-8');
      $xw->startElement('yml_catalog');
          $xw->writeAttribute('date', date('Y-m-d H:i', $datetime));
          $xw->startElement('shop');
              $xw->writeElement('name', $this->shop['name']);
              $xw->writeElement('company', $this->shop['company']);
              $xw->writeElement('url', sfConfig::get('app_host'));
              if($this->shop['agency']){
                  $xw->writeElement('agency', $this->shop['agency']);
              }
              if($this->shop['email']){
                  $xw->writeElement("email", $this->shop['email']);
              }

              $xw->startElement('currencies');
                  $xw->startElement('currency');
                      $xw->writeAttribute('id', 'RUR');
                      $xw->writeAttribute('rate', 1);
                  $xw->endElement();
              $xw->endElement();

              $xw->startElement('categories');
              $cats = Doctrine_Query::create()
                  ->select("id, parent_id, title, ym_type_prefix")
                  ->from("Cat INDEXBY id")
                  ->fetchArray();
              $cat_parents = Doctrine_Query::create()
                  ->select("*")
                  ->from("CatParent")
                  ->orderBy("order_id DESC")
                  ->fetchArray();
              foreach ($cats as $cat_key => $cat){
                  $cats[$cat_key]['Childrens'] = array();
                  $cats[$cat_key]['Parents'] = array();
                  $xw->startElement('category');
                  $xw->writeAttribute('id', $cat['id']);
                  if($cat['parent_id']){
                      $xw->writeAttribute('parentId', $cat['parent_id']);
                  }
                  $xw->text(trim($cat['title']));
                  $xw->endElement();
                  foreach ($cat_parents as $cat_parent){
                      if($cat_parent['parent_id'] === $cat['id']){
                          $cats[$cat_key]['Childrens'][] = $cat_parent['cat_id'];
                      }
                      if($cat_parent['cat_id'] === $cat['id']){
                          $cats[$cat_key]['Parents'][] = $cat_parent['parent_id'];
                      }
                  }
              }
              $xw->endElement();
              $xw->writeElement('pickup-options', 0);

              $price_types = Doctrine_Query::create()
                  ->select("id, title, is_default, IF(is_default = 1, 'default', 'markdown') AS index")
                  ->from("PriceType INDEXBY index")
                  ->where("is_default = 1")
                  ->orWhere("title = ?", "Уценка")
                  ->groupBy("index")
                  ->fetchArray();
              $price_types_ids = array();
              foreach ($price_types as $price_type){
                  $price_types_ids[] = $price_type['id'];
              }
              $discount_products = array();
              if(count($price_types) > 0 && isset($price_types['default'])){
                  $xw->writeElement('enable_auto_discounts', 'yes');
                  $xw->startElement('offers');
                  $products = Doctrine_Query::create()
                      ->select("p.id, p.title, p.alias, p.product_image, p.description, pv.id, pv.value, pr.id, pr.value, pr.price_type_id, c.id, c.title, c.ym_type_prefix, c.pseudo_branch, pp.id, pp.title, pp.isList, pl.id, pl.product_prop_id, pl.variant")
                      ->from("Product p")
                      ->innerJoin("p.ProductPropValue pv")
                      ->innerJoin("pv.ProductProp pp")
                      ->leftJoin("pp.ProductPropList pl WITH pl.id = IF(pp.isList = 1, pv.value, 'empty')")
                      ->innerJoin("p.ProductPrice pr WITH pr.price_type_id IN (" . implode(", ", $price_types_ids) . ") INDEXBY pr.price_type_id")
                      ->innerJoin("p.CatProducts c")
                      ->where("p.deleted_at IS NULL")
                      ->fetchArray();
                  foreach ($products as $product){
                      $brand = false;
                      $manufacturer = false;
                      $params = array();
                      if(count($product['ProductPropValue']) > 0){
                          foreach ($product['ProductPropValue'] as $prop_value){
                              if($prop_value['ProductProp']['isList']){
                                  if(in_array($prop_value['ProductProp']['title'], array('Брэнд', 'Бренд'))){
                                      $brand = trim($prop_value['ProductProp']['ProductPropList'][0]['variant']);
                                  }elseif ($prop_value['ProductProp']['title'] === 'Производитель'){
                                      $manufacturer = trim($prop_value['ProductProp']['ProductPropList'][0]['variant']);
                                  }else{
                                      $params[trim($prop_value['ProductProp']['title'])] = trim($prop_value['ProductProp']['ProductPropList'][0]['variant']);
                                      $params[trim($prop_value['ProductProp']['title'])] = str_replace('собак;кошек', 'собак и кошек', $params[trim($prop_value['ProductProp']['title'])]);
                                  }
                              }
                          }
                      }
                      if($brand !== false || $manufacturer !== false){
                          $default_price = (int)$product['ProductPrice'][$price_types['default']['id']]['value'];
                          $price = $default_price;
                          if(isset($price_types['markdown']) && isset($product['ProductPrice'][$price_types['markdown']['id']])){
                              $price = $product['ProductPrice'][$price_types['markdown']['id']]['value'];
                          }
                          $price = (int)$price;
                          if($price > 0){
                              $old_price = false;
                              $discounts = Page::getDiscount($product['id'], array('price' => $default_price, 'title' => $product['title'], 'brand' => $brand ? $brand : ''));
                              if(is_array($discounts) && count($discounts) > 0){
                                  $discount_percent = false;
                                  foreach ($discounts as $discount_id => $discount) {
                                      if ($discount['boole']) {
                                          $discount_percent = $discount['procent'];
                                          if(!isset($discount_products[$discount_id])){
                                              $discount_products[$discount_id] = array();
                                          }
                                          $discount_products[$discount_id][$product['id']] = (int)($price - ($price * $discount_percent / 100));
                                      }
                                  }
                                  if($discount_percent !== false){
                                      $old_price = $price;
                                      $price = (int)($price - ($price * $discount_percent / 100));
                                  }
                              }

                              $xw->startElement('offer');
                                  $xw->writeAttribute('id', $product['id']);
                                  $xw->writeAttribute('type', 'vendor.model');
                                  $cat = $product['CatProducts'][0];

                                  $type_prefix = trim($cat['ym_type_prefix']);
                                  if(!$type_prefix){
                                      if(count($cats[$cat['id']]['Parents']) > 0){
                                          foreach ($cats[$cat['id']]['Parents'] as $parent_id){
                                              if(trim($cats[$parent_id]['ym_type_prefix'])){
                                                  $type_prefix = trim($cats[$parent_id]['ym_type_prefix']);
                                              }
                                          }
                                      }
                                  }
                                  if(!$type_prefix){
                                      $type_prefix = trim($cat['pseudo_branch']);
                                  }

                                  static $count = 0;
                                  static $typePrefix = 0;
                                  $count++;
                                  if($type_prefix){
                                      $typePrefix++;
                                      if(in_array(trim($cat['title']), array('Игрушки', 'Туалеты')) && isset($params['Животное'])){
                                          $type_prefix .= ' ' . trim(mb_strtolower($params['Животное']));
                                      }
                                      $xw->writeElement('typePrefix', $type_prefix);
                                  }
                                  $xw->writeElement('vendor', $brand !== false ? $brand : $manufacturer);
                                  $xw->writeElement('model', $this->shortSwitch($product['title']));
                                  $xw->writeElement('url', $this->host . '/product/' . $product['alias'] . '/');
                                  $xw->writeElement('price', $price);
                                  if($old_price !== false){
                                      $xw->writeElement('oldprice', $old_price);
                                  }
                                  $xw->writeElement('currencyId', 'RUR');
                                  $xw->writeElement('categoryId', $cat['id']);
                                  foreach (explode(';', $product['product_image']) as $image){
                                      $image = trim($image);
                                      if(strlen($image) > 0 && $this->saveImage(sfConfig::get('sf_upload_dir') . '/i/' . $image)){
                                          $xw->writeElement('picture', $this->host . '/u/i/' . Page::replaceImageSize($image, 'YM'));
                                      }
                                  }
                                  $xw->writeElement('store', 'false');
                                  $xw->writeElement('pickup', 'true');
                                  $xw->writeElement('pickup-options', 0);
                                  $xw->writeElement('delivery', true);
                                  if($product['description']){
                                      $xw->startElement('description');
                                          $xw->writeCData(Page::strCut($product['description'], 2997));
                                      $xw->endElement();
                                  }
                                  foreach ($params as $name => $param){
                                      $xw->startElement('param');
                                          $xw->writeAttribute('name', $name);
                                          $xw->text($param);
                                      $xw->endElement();
                                  }
                              $xw->endElement();
                          }
                      }
                  }
                  $xw->endElement();
              }
          $xw->endElement();
      $xw->endElement();
      $xw->endDocument();



              $dirname = dirname($path);
              if(!file_exists($dirname)){
                  mkdir($dirname, 0755, true);
              }

              file_put_contents($path, $xw->outputMemory());
               */



        die();

        foreach (Doctrine::getTable("ClientOrderItem")->findAll() as $a){
            $a->save();
        }

        die();


        $dt = sfRUtils::dt();

        $this->log($dt->distanceOfTimeInWords(strtotime('2020-12-12 10:13:50'), time(), 5));

        die();

        foreach (unserialize('C:4:"City":455:{a:14:{s:3:"_id";a:1:{s:2:"id";s:1:"3";}s:5:"_data";a:2:{s:2:"id";s:1:"3";s:5:"title";s:7:"УФА.";}s:7:"_values";a:0:{}s:6:"_state";i:3;s:13:"_lastModified";a:1:{i:0;s:5:"title";}s:9:"_modified";a:0:{}s:10:"_oldValues";a:1:{s:5:"title";s:31:"Ютазинский район";}s:15:"_pendingDeletes";a:0:{}s:15:"_pendingUnlinks";a:0:{}s:20:"_serializeReferences";b:0;s:17:"_invokedSaveHooks";a:0:{}s:4:"_oid";i:9;s:8:"_locator";N;s:10:"_resources";a:0:{}}}') as $a){
            $this->log($a);
        }
        die();

        $this->log(date('Y-m-d H:i:s', strtotime('+1 sec', strtotime('2020-11-11 18:51:34'))));
        die();
        $type = 'courier';

        $active_end = Doctrine_Query::create()
            ->select("end")
            ->from("Blocking")
            ->where("user_id = ?", 2)
            ->andWhere("type = ?", $type)
            ->andWhere("end > NOW()")
            ->orderBy("end DESC")
            ->limit(1)
            ->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);

        echo "<pre>";
        print_r($problem_count);
        echo "</pre>";
        die();

        die();
        $start = time();
        $period = 'every_count_day';
        $every_count_day = 4;

        for($i = 0; $i < 30; $i++){

//            $this->log($i);
            $datetime = strtotime('+' . $i . ' days', $start);

            if($period === 'every_day'){
//                $this->genItem(date('Y-m-d H:i:s', $datetime));
            }elseif($period === 'weekday' && date('N', $datetime) <= 5){
//                $this->genItem(date('Y-m-d H:i:s', $datetime));
            }elseif($period === 'every_count_day' && ($i % $every_count_day) === 0){
//                $this->genItem(date('Y-m-d H:i:s', $datetime));
            }









        }

        die();
        $orders = Doctrine_Query::create()
            ->select("*")
            ->from("ClientOrder")
            ->execute();
        foreach ($orders as $order){
            $order->setIsPayed(true);
            $order->save();
        }
        die();

        $end = '2020-11-06 13:00:00';
        $completed = '2020-11-06 13:50:00';

        $this->log(strtotime($completed) >= strtotime('-30 min', strtotime($end)));

        die();

        $orders = Doctrine_Query::create()
            ->select("*")
            ->from("ClientOrder")
            ->where("total_wh_discount = 0")
            ->fetchArray();
        foreach ($orders as $order){
            Doctrine_Query::create()
                ->update("ClientOrder")
                ->set("total_wh_discount", "'" . $order['total'] . "'")
                ->where("id = " . $order['id'])
                ->execute();
            $this->log($order['id']);
        }


        die('COMPLETE');
    }
}
