<?php
class userActions extends sfActions
{
  private $profile = null;
  public function executeGen_xls($request)
  {
    $client_order = new ClientOrder();
    $client_order->setUserId(1);
    $client_order->setOrderStatusId(1);
    $client_order->setComment('tmp');
    $client_order->save();
    
    if($request->hasParameter('json'))
    {
      $ids = array();
      $order_items = json_decode($request->getParameter('json'), true);
      foreach($order_items as $item)
      {
        if(isset($item['code']))
        {
          $product = Doctrine::getTable('Product')->findOneByProductCode($item['code']);
          if($product)
          {
            $ids[$product->getId()] = $item['count'];
          }
        }
      }
    }
    else
    {
      $ids = $request->getParameter('id');
    }
    if(is_array($ids))
    {
      foreach($ids as $code => $count)
      {
        $product = $request->hasParameter('code') ? Doctrine::getTable('Product')->findOneByProductCode($code) : Doctrine::getTable('Product')->find($code);
        if($product)
        {
          $order_item = new OrderItem();
          $order_item->setProductId($product->getId());
          $order_item->setClientOrderId($client_order->getId());
          $order_item->setProductCount($count);
          $order_item->save();
        }
      }
    }
    
    if($request->hasParameter('json'))
    {
      $email_order = sfConfig::get('app_email_order', false);
      if($email_order)
      {
        $tempnam = tempnam('/tmp', 'ie');
        $objWriter = PHPExcel_IOFactory::createWriter($client_order->getExcel(), 'Excel5');
        $objWriter->save($tempnam);
        $second_level = implode('.', array_reverse(array_slice(array_reverse(explode('.', $request->getHost())), 0, 2)));
  
        $order_user = $client_order->getUser();
        
        $message = Swift_Message::newInstance()
          ->setFrom('app@' . $second_level)
          ->setTo($email_order)
          ->setSubject('Новый быстрый заказ от ' . $request->getParameter('phone'))
        ;
        $message->setContentType('text/html; charset=UTF-8');
        
        $body_lines = array();

        if($request->getParameter('comment'))
        {
          $body_lines[] = '<b>Комментарий к заказу</b><br /><i>' . $request->getParameter('comment') . '</i>';
        }
        
        $body = file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_header.php') . implode('<br />', $body_lines) . file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_footer.php');

        $message->setBody($body);
        
        $attachment = Swift_Attachment::newInstance()
          ->setFilename('Быстрый заказ.xls')
          ->setContentType('application/vnd.ms-excel')
          ->setBody(file_get_contents($tempnam))
        ;
        
        $message->attach($attachment);
        
        //$this->getMailer()->send($message);
        
      }
      
      echo json_encode(array(
        'state' => 'success',
        'text' => 'Спасибо! Ваш заказ принят в обработку.',
      ));
    }
    else
    {
      $objWriter = PHPExcel_IOFactory::createWriter($client_order->getExcel(true), 'Excel5');
      $objWriter->save('php://output');
      $this->getResponse()->setHttpHeader('Content-type', 'application/octet-stream');
      $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="Заказ.xls"');
    }
    $client_order->delete();
    
    
    
    return sfView::NONE;
  }
  public function executeGet_profile($request)
  {
    $this->setLayout(false);
  }
  public function returnProfile($values, $user)
  {
    if(!$this->profile)
    {
      $profile = array();
      $manager = $user->getManager();
         
      $user_id = $user->getId();
      $orders = array();
      
      $user_order = Doctrine_Query::create()
        ->select("co.*, oi.*, os.*, p.*, pp.*, psc.*")
        ->from("ClientOrder co")
        ->leftJoin("co.OrderStatus os")
        ->innerJoin("co.OrderItems oi")
        ->leftJoin("oi.Product p")
        ->leftJoin("p.ProductPrice pp")
        ->innerJoin("p.ProductStockCount psc")
        ->where("co.user_id = ?", $user_id)
        ->andWhere("pp.price_type_id = 1")
        ->orderBy("co.created_at DESC")
        ->fetchArray()
      ;

      foreach ($user_order as $order)
        {
          $goods = array();
          $price = 0;
          $count = 0;
          foreach($order['OrderItems'] as $order_item)
          {
            $order_item_price = 0;
            
            foreach($order_item['Product']['ProductPrice'] as $product_price)
            {
              $order_item_price = $product_price['value'];
            }


            foreach($order_item['Product']['ProductStockCount'] as $product_stock_count)
            {
              $order_item_stock_count = $product_stock_count['value'];
            }

            $goods[] = array(
              'product_id' => $order_item['Product']['product_code'],
              'product' => $order_item['Product']['title'],
              'title' => $order_item['Product']['title'],
              'count' => $order_item['product_count'],
              'price' => ($user->getCurrentDiscount() > 0 ? round($order_item_price - ($order_item_price * $user->getCurrentDiscount() / 100), 2) : $order_item_price),
              'code' => $order_item['Product']['product_code'],
              'stock_count' => $order_item_stock_count,
              'min_order' => $order_item['Product']['min_order'],
            );
            $price += $order_item_price * $order_item['product_count'];
            $count += $order_item['product_count'];
          }
          $orders[] = array(
            'id' => $order['id'],
            'count' => $count,
            'date' => ProjectUlils::rusDate($order['created_at'], false),
            'price' => ($user->getCurrentDiscount() > 0 ? round($price - ($price * $user->getCurrentDiscount() / 100), 2) : $price),
            'status' => $order['OrderStatus']['title'],
            'goods' => $goods
          );
        }
      $user_corr = Doctrine_Query::create()
          ->select("c.*, uf.*, ut.*")
          ->from("Correspondence c")
          ->leftJoin("c.UserFrom uf")
          ->leftJoin("c.UserTo ut")
          ->where("c.user_id_from = ?", $user_id)
          ->orWhere("c.user_id_to = ?", $user_id)
          ->orderBy("c.created_at", "ASC")
          ->fetchArray()
          ;

          $correspondence = array();
          foreach ($user_corr as $message) 
          {

            if ($message['status'] == 'out')
            {
              $correspondence[] = array(
                'name' => $message['UserFrom']['fname'] . ' ' . $message['UserFrom']['iname'],
                'text' => $message['body'],
                'date' => ProjectUlils::rusDate($message['created_at'], false, true),
                'status' => 'in' 
              );
            }
            elseif ($message['status'] == 'in')
            {
               $correspondence[] = array(
                'name' => $message['UserFrom']['organization'],
                'text' => $message['body'],
                'date' => ProjectUlils::rusDate($message['created_at'], false, true),
                'status' => 'out' 
              );
            }
          }
      $user_debt = Doctrine_Query::create()
          ->select("d.debt_sum, d.deadline")
          ->from("Debt d")
          ->where("d.user_id = ?", $user_id)
          ->fetchArray()
          ;
      $debt_detail = array();
      $overdue = 0;
      foreach ($user_debt as $debt) 
      {

        if ($debt['deadline'] < date('Y-m-d'))
        {
          $overdue += $debt['debt_sum'];
        }
        $debt_detail[] = array(
          'debt_sum' => $debt['debt_sum'],
          'deadline' => $debt['deadline'],
        );
      }
      // $banners = array();
      // $banners_q = Doctrine_Query::create()
      //     ->select("b.*")
      //     ->from("Banner b")
      //     ->where("b.is_activated = 1")
      //     ->fetchArray()
      //     ;

      // foreach ($banners_q as $banner) 
      // {
      //   if(file_exists(sfConfig::get('sf_upload_dir') . '/' . $banner['file']))
      //   {
      //     $banners[] = array(
      //         'cat_id' => $banner['cat_id']
      //         'img' => base64_encode(file_get_contents(sfConfig::get('sf_upload_dir') . '/' . $banner['file']))
      //     );
      //   }
      // }

      $profile = array(
          'auth' => 'true',
          'username' => $values['user']['username'],
          'organization' => $values['user']['organization'],
          'phone' => $values['user']['phone_number'],
          'city' => $values['user']['city'],
          'address' => $values['user']['address'],
          'email' => $values['user']['email'],
          'orders_sum_last_month' => (isset($values['user']['orders_sum_last_month']) && $values['user']['orders_sum_last_month'] ? $values['user']['orders_sum_last_month'] : '0'),
          'orders_sum_current' => (isset($values['user']['orders_sum_current']) && $values['user']['orders_sum_current'] ? $values['user']['orders_sum_current'] : '0'),
          'sum_limit' => (isset($values['user']['limit_by_sum']) && $values['user']['limit_by_sum'] ? $values['user']['limit_by_sum'] : '0'),
          'sum_discount' => str_replace(',', '.', isset($values['user']['current_discount']) && $values['user']['current_discount'] ? $values['user']['current_discount']: '0'),
          'debt' => (isset($values['user']['current_debt']) && $values['user']['current_debt'] ? $values['user']['current_debt'] : '0'),
          'manager' => $manager ? array(
            'name' => $manager->getFname() . ' ' . $manager->getIname(),
            'phone' => $manager->getPhoneNumber() ? $manager->getPhoneNumber() : 'отдел продаж',
          ) : 'null',
          'debt_detail' => (empty($debt_detail)? 'null' : $debt_detail),
          'overdue_payment' => $overdue,
          'orders' => $orders,
          'feedback' => $correspondence,
          'cat_images_idx' => ($user->getCatIndx() == '') ? 'null' : unserialize($user->getCatIndx())
        );
       $this->profile = $profile;
    }
    return $this->profile;
  }
  public function executeFeedback($request)
  {
    if($request->hasParameter('text') && trim($request->getParameter('text')) != '')
    {
      $user = $this->getUser()->getAccount();
      $feedback = new Correspondence();
      $feedback->setUserIdFrom($user->getId());
      if($user->getManagerId())
      {
        $feedback->setUserIdTo($user->getManagerId());
      }
      else
      {
        $feedback->setUserIdTo(1);
      }
      $feedback->setStatus('in');

      $feedback->setBody(trim($request->getParameter('text')));

      $second_level = implode('.', array_reverse(array_slice(array_reverse(explode('.', $request->getHost())), 0, 2)));
      $email_order = sfConfig::get('app_email_order', false);
      if($email_order)
      {

        $message = Swift_Message::newInstance()
          ->setFrom('app@' . $second_level)
          ->setTo($email_order)
          ->setSubject('Новое сообщение из формы обратной связи от ' . $user->getOrganization() . ' ИНН ' . $user->getUsername())
        ;
        $message->setContentType('text/html; charset=UTF-8');
        
        $body_lines = array();

        if ($user->getEmail())
        {
          $body_lines[] = 'Эл. почта <b>' . $user->getEmail() . '</b>';
        }
        if ($user->getPhoneNumber())
        {
          $body_lines[] = 'Телефон <b>' . $user->getPhoneNumber() . '</b>';
        }
        $body_lines[] = '<b>Комментарий: <b><br /><i>' . trim($request->getParameter('text')) . '</i>';

        $body = file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_header.php') . implode('<br />', $body_lines) . file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_footer.php');
        $message->setBody($body);
        $this->getMailer()->send($message);
      }
      try
      {
        $feedback->save();
        $values['user'] = $user;

        $profile = $this->returnProfile($values, $user);
        echo json_encode(array(
          'state' => 'success',
          'profile' => $profile,
          'text' => 'Ваше сообщение успешно отправлено'
      ));

      }
      catch (Doctrine_Validator_Exception $e)
      {
        $errorStack = $feedback->getErrorStack();
        foreach ($errorStack as $field => $errors)
        {
          $message .= "$field (" . implode(", ", $errors) . "), ";
        }
        $message = trim($message, ', ');
        echo json_encode(array(
          'state' => 'error',
          'errorText' => $message
        ));
      }
      
    }
    $this->setLayout(false);
    return sfView::NONE;
  }
  public function executeUpman($request)
  {
    $manifest = sfConfig::get('sf_web_dir') . '/.manifest';
    if (file_exists($manifest))
    {

      $man = file($manifest);
      $ver = preg_replace('/[^0-9]/', '', $man[1]);
      if ($ver > 1000)
      {
        $ver = 1;
      }
      else
      {
        $ver += 1;  
      }
      
      $to_change = preg_replace('/[0-9]{1,}/',$ver, $man[1]);

      $man[1] = $to_change;
      $current = '';
      foreach ($man as $row) 
      {
        $current .= $row;
      }
      file_put_contents($manifest, $current);
    }

    $this->setLayout(false);
    return sfView::NONE;
  }
  public function executeOrder($request)
  {

    if($request->hasParameter('json'))
    {
      
      $order_items = json_decode($request->getParameter('json'), true);

      if(is_array($order_items))
      {
        if($request->hasParameter('comment'))
        {
          $comment = $request->getParameter('comment');
          
        }

        $user_id = $this->getUser()->getUserId();

        $client_order = new ClientOrder();
        $client_order->setUserId($user_id);
        $client_order->setOrderStatusId('1');
        $client_order->setComment($comment);
        
        
        if($this->getUser()->getAccount()->getCurrentDiscount())
        {
          $client_order->setDiscount($this->getUser()->getAccount()->getCurrentDiscount());
        }
        
        $client_order->save();
        
        $c = 0;
       
        $items_count = count($order_items);
        $result_arr = array();
        $product_err = array(
          'state' => 'error',
          'errorText' => 'Невозможно обработать заказ',
          'errorCode' => 'o500',
          'json' => array(),
          'bitrix' => array(),
          );
        $json = array();
        $bitrix = array();
        $count_error = array();
        $error = false;
        
        
        $returndata = array();
 
        foreach($order_items as $item)
        {
          $item['article'] = preg_replace('/[^0-9]/', '', $item['article']);
          if(isset($item['code']))
          {
            $product = Doctrine::getTable('Product')->findOneByProductCode($item['code']);
            if($product)
            {
              $item['id'] = $product->getId();
            }
          }
          
          $q_prod = Doctrine_Query::create()
            ->select('p.*, (SELECT SUM(psc.value) FROM ProductStockCount psc WHERE psc.product_id = p.id) AS pcountv')
            ->from('Product p')
            ->where('p.id = ?', $item['id'])
            ->limit(1);

          $product = $q_prod->execute();

          if (count($product) == 0)
          {
            $returndata[$item['id']] = 0;
          }
          else
          {
            if($item['count'] > $product[0]['pcountv'])
            {
              $returndata[$item['id']] = intval($product[0]['pcountv']);
              $bitrix[$product[0]['product_code']] = intval($product[0]['pcountv']);
              $count_error[] = $product[0]['title'] . ', в наличии: ' . intval($product[0]['pcountv']);
            }
            else
            {
              $result_arr[$c] = array(
                'product_id' => $product[0]['id'],
                'product_art' => $product[0]['product_code'],
                'product_descr' => $product[0]['title'],
                'client_order_id' => $client_order->getId(),
                'product_count' => $item['count']
              );
              $c++;
            }
          }
        }
     

        if (count($returndata) == 0)
        {
          foreach ($result_arr as $el) 
          {
            $order_item = new OrderItem();
            $order_item->setProductId($el['product_id']);
            $order_item->setClientOrderId($el['client_order_id']);
            $order_item->setProductCount($el['product_count']);
            $order_item->save();
          }
          
          $email_order = sfConfig::get('app_email_order', false);
          if($email_order)
          {
            
            $tempnam = tempnam('/tmp', 'ie');
  
  
            $objWriter = PHPExcel_IOFactory::createWriter($client_order->getExcel(), 'Excel5');
            $objWriter->save($tempnam);
            $second_level = implode('.', array_reverse(array_slice(array_reverse(explode('.', $request->getHost())), 0, 2)));
            
            $order_user = $client_order->getUser();
            
            $message = Swift_Message::newInstance()
              ->setFrom('app@' . $second_level)
              ->setTo($email_order)
              ->setSubject('Новый заказ №' . $client_order->getId() . ' от ' . $order_user->getOrganization() . ' ИНН ' . $order_user->getUsername())
            ;
            if($this->getUser()->getAccount()->getEmail() != '')
            {
              $message->setReplyTo(array($this->getUser()->getAccount()->getEmail()));
            }
            $message->setContentType('text/html; charset=UTF-8');
            
            $body_lines = array();
            
            
            
            $body_lines[] = 'ИНН <b>' . $order_user->getUsername() . '</b>';
            
            $body_lines[] = 'Заказ от <b>' . $order_user->getOrganization() . '</b>';
            
            if($order_user->getEmail())
            {
              $body_lines[] = 'Эл. почта <a href="mailto:' . $order_user->getEmail() . '"><b>' . $order_user->getEmail() . '</b></a>';
            }
            if($order_user->getPhoneNumber())
            {
              $body_lines[] = 'Телефон <b>' . $order_user->getPhoneNumber() . '</b>';
            }
            if($client_order->getComment())
            {
              $body_lines[] = '<b>Комментарий к заказу</b><br /><i>' . $client_order->getComment() . '</i>';
            }
            
            $body = file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_header.php') . implode('<br />', $body_lines) . file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_footer.php');

            $body = str_replace('#TITLE#', 'Новый заказ №' . $client_order->getId() . ' ' . $order_user->getUsername(), $body);
            
            $message->setBody($body);
            
            $attachment = Swift_Attachment::newInstance()
              ->setFilename('Заказ №' . $client_order->getId() . '.xls')
              ->setContentType('application/vnd.ms-excel')
              ->setBody(file_get_contents($tempnam))
            ;
            
            $message->attach($attachment);
            
            //$this->getMailer()->send($message);
            
          }
          $user = $this->getUser()->getAccount();
          $profile = $this->returnProfile(array('user' => $user), $user);
      
          echo json_encode(array(
            'state' => 'success',
            'profile' => $profile,
            'text' => 'Спасибо! Ваш заказ принят в обработку.<br /> Номер вашего заказа: ' . $client_order->getId(),
          ));
        }
        else
        {
          $client_order->delete();
          echo json_encode(array(
            'state' => 'error',
            'errorText' => 'Невозможно обработать заказ. Превышено количество товара. ' . '<br />' . implode('<br />', $count_error),
            'json' => $returndata,
            'bitrix' => $bitrix,
          ));
        }
      }
    }

    $this->setLayout(false);
    return sfView::NONE;
  }
  public function executePing($request)
  {
    echo time();
    return sfView::NONE;
  }
  public function executeProfile($request)
  {
    $result = array('state' => 'redirect', 'hash' => $request->getParameter('back_hash') ? $request->getParameter('back_hash') : 'list');
    if ($request->getHttpHeader('authorization'))
    {
      $authorization_str = base64_decode(str_replace('Basic ', '', $request->getHttpHeader('Authorization')));
      $authorization_arr = explode(':', $authorization_str);     
      $user = PluginUserTable::getInstance()->getAuthenticatedUser($authorization_arr[0], $authorization_arr[1]);
      if (!$user)
      {
        echo json_encode($result);
        return sfView::NONE;
      }
      $user->setOpenPassword($authorization_arr[1]);
      $user->save();
      $this->getUser()->signIn($user, true);
      $profile = $this->returnProfile(array('user' => $user), $user);

      $result = array('profile' => $profile);
      echo json_encode($result);
    }
    else
    {
      echo json_encode($result);
    }
    return sfView::NONE;
  }
  public function executeSignup($request)
  {
    if($request->isMethod('post') && $request->hasParameter('signup'))
    {
      $signup = $request->getParameter('signup');
 
      $chars = "1234567890";
      $max = 8;
      $password = null; 
      $size = strLen($chars) - 1;
      while($max--) 
      {
        $password .= $chars[rand(0, $size)]; 
      }
      $signup['password'] = $password;
      $signup['is_active'] = 1;

      $form = false;
      if (!empty($signup['username']))
      {
        $user = Doctrine::getTable('User')->findOneByUsername($signup['username']);
        if($user)
        {
          $form = new CustomRegisterUserForm($user);
        }
        else
        {
          $form = new CustomRegisterUserForm();
        }
      }
      if(!$form)
      {
        echo json_encode(array(
          'state' => 'error',
          'errorText' => 'Данный ИНН уже зарегистрирован'
        ));
      }
      else
      {
        $form->bind($signup, $request->getFiles('signup'));
        
        if ($form->isValid())
        { 
          $values = $form->getValues();
          $user = $form->save();
          $user->setRecoverySecret('/' . md5($values['username'] . $values['password'] . $values['email'] . '/'));
          $user->save();
         



          $second_level = implode('.', array_reverse(array_slice(array_reverse(explode('.', $request->getHost())), 0, 2)));




          sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');

          get_component('pages', 'emailSender',
              array(
                  'type' => 'userRegistration',
                  'emailTo' => $values['email'],
                  'param' => array(
                      'organization' => $values['organization'],
                      'username' => $values['username'],
                      'password' => $password
                  )
              )
          );

//          $message = Swift_Message::newInstance()
//            ->setFrom('app@' . $second_level)
//            ->setTo($values['email'])
//            ->setSubject('Регистрационные данные для входа в систему Имидж-электро')
//          ;
//
//          $message->setContentType('text/html; charset=UTF-8');
//
//          $body = file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_header.php') . '<b>' . $values['organization'] . "</b><br /><br />Вы успешно прошли регистрацию на сайте компании Имидж-Электро.<br />Для входа в систему используйте учетные данные:<br />Логин: " . $values['username'] . "<br />Пароль: " . $password . file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_footer.php');
//
//          $body = str_replace('#TITLE#', 'Регистрационные данные для входа в систему Имидж-электро', $body);
//
//          $message->setBody($body);
          
          //$this->getMailer()->send($message);
          echo json_encode(array(
              'state' => 'success',
              'text' => 'Регистрация прошла успешно. Пароль отправлен на указанный Вами адрес электронной почты',
          ));
        }
        else
        {
          $errors = array();
          if($form->hasGlobalErrors())
          {
            foreach($form->getGlobalErrors() as $error)
            {
              $errors[] = $error->__toString();
              
            }
          }
          foreach($form as $field)
          {
            if($field->hasError())
            {
              $errors[] = $field->getError()->__toString();
            }
          }
          echo json_encode(array(
            'state' => 'error',
            'errorText' => implode('<br />', $errors)
          ));
        }
      }
    }
    $this->setLayout(false);
    return sfView::NONE;
  }
  public function executeSignout($request)
  {
    $this->getUser()->signOut();
    echo json_encode(array(
      'state' => 'redirect',
      'hash' => $request->getParameter('back_hash') ? $request->getParameter('back_hash') : 'list'
    ));
    $this->setLayout(false);
    return sfView::NONE;
  }
  public function executeSignin($request) 
  {
    if (($request->isMethod('post') && $request->hasParameter('signin')) || isset($_SERVER['PHP_AUTH_USER']))
    {
      $fields = $request->hasParameter('signin') ? $request->getParameter('signin') : array('username' => $_SERVER['PHP_AUTH_USER'], 'password' => $_SERVER['PHP_AUTH_PW']);
      
      $form = new SigninForm();
      $form->bind($fields, array());
      
      $route = sfContext::getInstance()->getRouting()->findRoute($request->getPathInfo());
      
      if ($form->isValid()) 
      {
        
        $values = $form->getValues();
        
        $user = $values['user'];
        $user->setOpenPassword($fields['password']);
        $user->save();
      
        $this->getUser()->signIn($values['user'], true);
        
        
        
        if(isset($_SERVER['PHP_AUTH_USER']) && $route !== false && $route['parameters']['action'] != 'signin')
        {
          $route = sfContext::getInstance()->getRouting()->findRoute($request->getPathInfo());
          if($route !== false && $route['parameters']['action'] != 'signin')
          {
            $this->forward($route['parameters']['module'], $route['parameters']['action']);
          }
        }
        else
        {
          $user = $this->getUser()->getAccount();
          $profile = $this->returnProfile(array('user' => $user), $user);
          echo json_encode(array(
            'state' => 'redirect',
            'profile' => $profile,
            'hash' => $request->getParameter('back_hash') ? $request->getParameter('back_hash') : 'list'
          ));
          die();
        }
      }
      else
      {
        if($route['parameters']['action'] == 'signin')
        {
          echo json_encode(array(
            'state' => 'error',
            'errorText' => 'Неправильная пара логин-пароль! Авторизоваться не удалось.'
          ));
        } 
        else
        {
          echo json_encode(array(
            'state' => 'redirect',
            'hash' => $this->getUser()->isAuthenticated() ? 'profile' : 'overlay/authorization'
          ));
        }
      }
    }
    else
    {
      echo json_encode(array(
        'state' => 'redirect',
        'hash' => $this->getUser()->isAuthenticated() ? 'profile' : 'overlay/authorization'
      ));
    }
    
    $this->setLayout(false);
    return sfView::NONE;
  }
  public function executeCheckinn($request)
  {

    if($request->isMethod('post') && $request->hasParameter('signup'))
    {
      $checkinn = $request->getParameter('signup');
      if (isset($checkinn['username']) && !empty($checkinn['username']))
      {
        $q = Doctrine::getTable('User')->findOneByUsername($checkinn['username']);
        if (!empty($q['organization']) && empty($q['email']))
        {
          echo json_encode(array(
            'state' => 'success_inn',
            'organization' => $q['organization'],
          ));
        }
        elseif (!empty($q['organization']) && !empty($q['email']))
        {
          echo json_encode(array(
            'state' => 'error',
            'errorText' => 'Данный клиент уже зарегистрирован в базе данных'
          ));
        }
        else
        {
            echo json_encode(array(
                'state' => 'error_inn_in_db'
            ));
        }
      }
    }
    $this->setLayout(false);
    return sfView::NONE;
  }
  public function executeSettings($request)
  {
    if($request->isMethod('post') && $request->hasParameter('settings'))
    {
      $settings = $request->getParameter('settings');
      $settings['is_active'] = 1;

      $user = $this->getUser()->getAccount();
      $settings['username'] = $user->getUsername();
      $settings['password'] = $user->getPassword();

      $form = new CustomRegisterUserForm($user);
      $form->bind($settings, $request->getFiles('settings'));
      
      if ($form->isValid())
      {
        $form->save();

        $values['user'] = $form->getValues();
        
        $user = $this->getUser()->getAccount();
        
        $profile = $this->returnProfile(array('user' => $user), $user);
          echo json_encode(array(
            'state' => 'success',
            'profile' => $profile,
            'text' => 'Данные профиля изменены'
          ));
    
      }
      else
      {
        $errors = array();
        if($form->hasGlobalErrors())
        {
          foreach($form->getGlobalErrors() as $error)
          {
            $errors[] = $error->__toString();
            
          }
        }
        foreach($form as $field)
        {
          if($field->hasError())
          {
            $errors[] = $field->getError()->__toString();
          }
        }
        echo json_encode(array(
          'state' => 'error',
          'errorText' => implode('<br />', $errors)
        ));
      }
    }
    $this->setLayout(false);
    return sfView::NONE;    
  }
  public function executeRemindpassword($request)
  {
    if($request->isMethod('post') && $request->hasParameter('remind'))
    {
      $param = $request->getParameter('remind');
      $user = Doctrine::getTable('User')->findOneByUsername($param['username']);
      if ($user)
      {
        $user->setRecoverySecret(ProjectUlils::generateUuid());
        $user->save();
        
        $link_part = '/' . $user->getId() . '/' . $user->getRecoverySecret();
        
        $second_level = implode('.', array_reverse(array_slice(array_reverse(explode('.', $request->getHost())), 0, 2)));

        $message = Swift_Message::newInstance()
          ->setFrom('app@' . $second_level)
          ->setTo($user->getEmail())
          ->setSubject("Восстановление пароля от личного кабинета Имидж-Электро")
        ;
        
        $message->setContentType('text/html; charset=UTF-8');
        
        $body = file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_header.php');
        
        $body .= 'Вы отправили запрос на восстановление пароля от личного кабинета на сайте Имидж-Электро.<br />Для того чтобы задать новый пароль, перейдите по ссылке: http://' . $request->getHost() . '/index.html#overlay/recovery_password' . $link_part . '<br /><br />Пожалуйста, проигнорируйте данное письмо, если оно попало к Вам по ошибке.';
        
        $body .= file_get_contents(sfConfig::get('sf_app_template_dir') . '/mail_footer.php');

        $body = str_replace('#TITLE#', 'Восстановление пароля от личного кабинета Имидж-Электро', $body);
        
        $message->setBody($body);

        $this->getMailer()->send($message);
        
        $json = array(
          'state' => 'redirect',
          'back_hash' => 'list',
          'text' => 'Ссылка для восстановления пароля отправлена на указанный при регистрации E-mail',
        );
      }
      else
      {
        $json = array(
          'state' => 'error',
          'errorText' => 'Пользователь с данным E-mail не найден',
        );
      }
      
    }
    echo json_encode($json);
    $this->setLayout(false);
    return sfView::NONE;    
  }
  public function executeRecovery_password($request)
  {
    $user = Doctrine::getTable('User')->findOneByIdAndRecoverySecret($request->getParameter('id'), $request->getParameter('recovery_secret'));
    if ($user)
    {
      $json = array(
        'state' => 'success',
        'text' => 'user found',
      );
      if ($request->getParameter('password') && $request->getParameter('password_repeat'))
      {
        if ($request->getParameter('password') == $request->getParameter('password_repeat'))
        {
          $user->setPassword($request->getParameter('password'));
          $user->save();
          {
            $json = array(
              'state' => 'redirect',
              'back_hash' => 'list',
              'text' => 'Пароль успешно изменен',
            );
          }
          $user->setRecoverySecret('');
          $user->save();
        }
        else
        {
          $json = array(
            'state' => 'error',
            'errorText' => "Пароли не совпадают",
          );
        }
      }
      else
      {
         $json = array(
            'state' => 'error',
            'errorText' => 'Не все поля заполнены',
          ); 
      }
    }
    else
    {
      $json = array(
            'state' => 'error',
            'errorText' => 'Пользователь не найден',
          );
    }
    echo json_encode($json);
    $this->setLayout(false);
    return sfView::NONE; 
  }
  public function executeChangepassword($request)
  {

    if($request->isMethod('post') && $request->hasParameter('settings'))
    {
      
      
      
      $settings = $request->getParameter('settings');
      
      $json = array(
        'state' => 'error',
        'errorText' => 'Старый пароль указан не верно',
      );
      
      $usera = Doctrine::getTable('User')->find($this->getUser()->getAccount()->getId());

      
      $tmp_user = new User();
      $tmp_user->setSalt($usera->getSalt());
      $tmp_user->setPassword($settings['old_password']);

      if($tmp_user->getPassword() == $usera->getPassword())
      {
        $form = new ChangePasswordForm();
        $form->bind(array('password' => $settings['password']), array());
        if ($form->isValid()) 
        {

          $usera->setPassword($settings['password']);

          $usera->save();
          

          $profile = $this->returnProfile(array('user' => $usera), $usera);
          $json = array(
            'state' => 'success',
            'profile' => $profile,
            'text' => 'Пароль успешно изменен ' . $settings['password'],
          );
        }
        else
        {
          $errors = array();
          if($form->hasGlobalErrors())
          {
            foreach($form->getGlobalErrors() as $error)
            {
              $errors[] = $error->__toString();
            }
          }
          foreach($form as $key => $field)
          {
            if($field->hasError())
            {
              $errors[] = $field->getError()->__toString() . ': ' . $key;
            }
          }
          $json['errorText'] = implode('<br />', $errors);
        }
      }

      echo json_encode($json);
      die();
    }

    
    $this->setLayout(false);
    return sfView::NONE;
  }
  public function executeCat_images($request)
  {
    if($request->isMethod('post') && $request->hasParameter('cat_images'))
    {
      $cats = array_keys($request->getParameter('cat_images'));
      $cat_idx = serialize(array_values($request->getParameter('cat_images')));
      foreach ($cats as $cat)
      {
        $q = Doctrine_Query::create()
          ->select("cp.cat_id")
          ->from("CatParent cp")
          ->where("cp.parent_id = ?", $cat)
          ->fetchArray();
        foreach ($q as $inner_cat) 
        {
          $cats_arr[] = $inner_cat['cat_id'];
        }
      }

      $cats = serialize($cats_arr);
      $user = $this->getUser()->getAccount();
      if ($user && $user->getCatsWithImages())
      {
        $temp_cats = $user->getCatsWithImages();  
      }
      else
      {
        $temp_cats = ''; 
      }
      if ($temp_cats != $cats)
      {
        $user->setCatsWithImages($cats);
        $user->setCatIndx($cat_idx);
        $user->setManifestVersion($user->getManifestVersion() + 1);
        $user->save();  
      }
    }
    else
    {
      $user = $this->getUser()->getAccount();
      $user->setCatsWithImages('');
      $user->setCatIndx('');
      $user->setManifestVersion($user->getManifestVersion() + 1);
      $user->save();
    }
    
    
    $user = $this->getUser()->getAccount();
    $profile = $this->returnProfile(array('user' => $user), $user);

    $json = array(
            'state' => 'success',
            'profile' => $profile,
            'text' => 'Выбранные вами изображения успешно синхронизированы',
          );
    echo json_encode($json);
    $this->setLayout(false);
    return sfView::NONE;    
  }
  public function executeManifest($request)
  {

    $user = $this->getUser()->getAccount();
    $ver_num = ($user)? $user->getManifestVersion() : 0;
    $manifest = "CACHE MANIFEST" . "\n";
    $ver_text = "version ";
    $version = $ver_text . $ver_num . "\n";
    $manifest .= $version;
    $manifest .= "index.html" . "\n" .
                 "css/fonts.css" . "\n" .
                 "css/g.css" . "\n" .
                 "css/p.css" . "\n".
                 "\n".
                 "js/jquery-2.0.3.min.js" . "\n".
                 "js/xlsx.js" . "\n".
                 "js/jquery.plugins.js" . "\n".
                 "js/controllers.js" . "\n".
                 "js/profile.js" . "\n".
                 "js/lstorage.js" . "\n".
                 "js/db.js" . "\n".
                 "js/ielectro.js" . "\n".
                 "js/init.d.js" . "\n".
                 "\n".
                 "i/no_photo.png" . "\n".
                 "i/counter_elem.png" . "\n".
                 "\n".
                 "\n".
                 "NETWORK:" . "\n".
                 "*" . "\n".
                 "\n".
                 "FALLBACK:" . "\n"
    ;
    echo $manifest;
    $this->setLayout(false);
    return sfView::NONE;
  }
  //
    public function executeDetect_lang(sfWebRequest $request)
    {
        //$culture = $request->getPreferredCulture(array('ru', 'en'));
        $culture = $request->getPreferredCulture(array('ru'));

        $this->getUser()->setCulture($culture);
        $this->redirect('homepage');
        return sfView::NONE;
    }
}
