<?php

class userActions extends sfActions
{
    private function getAddBid($user_id, $cat_id, $weight, $export_id = null)
    {
        $resp = false;
        $body_mail = array();

        $cat = Doctrine::getTable("Cat")->findOneById($cat_id);

        if($cat) {
            if(!($export_id != null && $export_id != '')){

                $export_q = Doctrine_Query::create()
                    ->select("e.*")
                    ->from("Export e")
                    ->where("e.logic_type = 'wait'")
                    ->andWhere("e.cat_id = ?", $cat->getId())
                    ->andWhere("e.user_id = ?", $user_id)
                    ->orderBy("e.weight DESC")
                    ->fetchOne();

                if(!$export_q){
                    $newExport = new Export();
                    $logic_type = 'bid';
                    if($weight < $cat->getMinWeight()){
                        $logic_type = 'wait';
                    }
                    $newExport->setLogicType($logic_type);
                    $newExport->setCatId($cat_id);
                    $newExport->setWeight($weight);
                    $newExport->setSum($weight * $cat->getPrice());
                    $newExport->setUserId($user_id);
                    $newExport->save();

                    $this->getUser()->setAttribute('cat_id', '');
                    $this->getUser()->setAttribute('weight', '');

                    if($newExport){
                        $resp = true;

                        if($newExport->getLogicType() != 'wait'){
                            $thisUser = $newExport->getUser();
                            $body_mail = array(
                                'cat' => $cat->getTitle(),
                                'weight' => Yavinesu::weightFormat($weight),
                                'sum' => Yavinesu::priceFormat($weight * $cat->getPrice()),
                                'name' => $thisUser->getName(),
                                'phone' => Page::maskPhone($thisUser->getUsername()),
                                'email' => $thisUser->getEmail(),
                            );
                        }
                    }
                } else {
                    $total_weight = $export_q->getWeight() + $weight;

                    $logic_type = 'bid_after_wait';
                    if($total_weight < $cat->getMinWeight()){
                        $logic_type = 'wait';
                    } else{
                        $thisUser = $export_q->getUser();
                        $body_mail = array(
                            'cat' => $cat->getTitle(),
                            'weight' => Yavinesu::weightFormat($total_weight),
                            'sum' => Yavinesu::priceFormat($total_weight * $cat->getPrice()),
                            'name' => $thisUser->getName(),
                            'phone' => Page::maskPhone($thisUser->getUsername()),
                            'email' => $thisUser->getEmail(),
                        );
                    }
                    $export_q->setLogicType($logic_type);
                    $export_q->setWeight($total_weight);
                    $export_q->setSum($total_weight * $cat->getPrice());
                    $export_q->save();

                    $resp = true;
                }

            } else {
                $export = Doctrine::getTable("Export")->findOneById($export_id);

                if($export){
                    if($weight >= $cat->getMinWeight() && $export->getLogicType() == 'wait'){
                        $export->setLogicType('bid_after_wait');

                        $thisUser = $export->getUser();
                        $body_mail = array(
                            'cat' => $cat->getTitle(),
                            'weight' => Yavinesu::weightFormat($weight),
                            'sum' => Yavinesu::priceFormat($weight * $cat->getPrice()),
                            'name' => $thisUser->getName(),
                            'phone' => Page::maskPhone($thisUser->getUsername()),
                            'email' => $thisUser->getEmail(),
                        );
                    }
                    $export->setWeight($weight);
                    $export->setSum($weight * $cat->getPrice());
                    $export->save();

                    $resp = true;
                }

                $this->getUser()->setAttribute('cat_id', '');
                $this->getUser()->setAttribute('weight', '');
            }

        }

        if(count($body_mail) > 0){
            $theme_mail = array();
            $body_mail['logo'] = sfConfig::get('app_logo_mail');
            MailTemplate::sendMailUser("bidExport", $body_mail, $theme_mail, csSettings::get('bid_email'));
        }

        return $resp;
    }

    public function executeAddBid(sfWebRequest $request)
    {
        $data = array('state' => 'error');

        $cat_id = $request->getParameter('cat_id');
        $weight = $request->getParameter('weight');
        $bid_id = $request->getParameter('bid_id');

        if($this->getUser()->isAuthenticated()){
            $addBid = $this->getAddBid($this->getUser()->getAccount()->getId(), $cat_id, $weight, $bid_id);

            if($addBid === true){
                $data['state'] = 'ok';
            }
        } else {
            $data['msg'] = 'Ошибка при добавлении заявки';
        }

        echo json_encode($data);
        return sfView::NONE;
    }

    public function executeRemoveBid(sfWebRequest $request)
    {
        $data = array('state' => 'error');

        $id = $request->getParameter('id');

        if($id != null && $id != ''){
            $export = Doctrine::getTable("Export")->findOneById($id);

            if($export){
                $export->delete();

                $data['state'] = 'ok';
            } else {
                $data['msg'] = 'Запись не найдена';
            }

        } else {
            $data['msg'] = 'Ошибка при удалении записи';
        }

        echo json_encode($data);
        return sfView::NONE;
    }

    public function executeRecoveryForm(sfWebRequest $request)
    {
        $data = array('state' => 'error');

        $email = trim($request->getParameter('email'));

        if($email != null && $email != ''){
            $user = Doctrine::getTable("User")->findOneByEmail($email);

            if($user){

                $user->setPasswordRecovery(ProjectUtils::generateUuid());
                $user->save();

                $link_part = 'change_psw=1&id=' . $user->getId() . '&secret=' . $user->getPasswordRecovery();

                $message = Swift_Message::newInstance()
                    ->setFrom(sfConfig::get('app_email_sender'))
                    ->setTo($user->getEmail())
                    ->setSubject("Восстановление пароля от личного кабинета " . sfConfig::get('app_www_title', false));

                $message->setContentType('text/html; charset=UTF-8');

                $mail_template = Doctrine::getTable('MailTemplate')->findOneByEvent('userRemindPassword');

                if($mail_template){
                    $body = $mail_template->getBody();

                    $body = str_replace('#link_remid#', '<a href="https://' . $request->getHost() . '/?' . $link_part . '">https://' . $request->getHost() . '/?' . $link_part . '</a>', $body);
                    $body = str_replace('#logo#', sfConfig::get('app_logo_mail') , $body);
                    $message->setBody($body);
                }

                $this->getMailer()->send($message);

                $data['state'] = 'ok';
            } else {
                $data['msg'] = 'Пользователь с таким электронным адресом не найден';
            }

        } else {
            $data['msg'] = 'Укажите электронную почту';
        }

        echo json_encode($data);
        return sfView::NONE;
    }

    public function executeChangePswForm(sfWebRequest $request)
    {
        $data = array('state' => 'error');

        $psw = trim($request->getParameter('psw'));
        $id = trim($request->getParameter('id'));
        $secret = trim($request->getParameter('secret'));

        if($psw != null && $psw != ''){
            if($id != null && $id != '' && $secret != null && $secret != ''){
                $user = Doctrine::getTable("User")->findOneByIdAndPasswordRecovery($id, $secret);

                if($user){

                    $user->setPassword($psw);
                    $user->save();

                    $data['state'] = 'ok';
                } else {
                    $data['msg'] = 'Не удалось найти пользователя';
                }
            } else {
                $data['msg'] = 'Ссылка на восстановление неверная, попробуйте еще раз оправить письмо';
            }

        } else {
            $data['msg'] = 'Укажите пароль';
        }

        echo json_encode($data);
        return sfView::NONE;
    }

    public function executeEditProfile(sfWebRequest $request)
    {
        $data = array('state' => 'error');

        $name = $request->getParameter('name');
        $phone = preg_replace("/[^,.0-9]/", '', $request->getParameter('phone'));
        $email = $request->getParameter('email');
        $address = $request->getParameter('address');
        $psw = $request->getParameter('psw');

        if($this->getUser()->isAuthenticated()){
            $user = Doctrine::getTable("User")->findOneById($this->getUser()->getAccount()->getId());

            if($user){
                $msg = '';
                if($user->getName() != $name && $name != '' && $name != null){
                    $user->setName($name);
                }
                if($user->getPhone() != $phone && $phone != '' && $phone != null){
                    $user->setPhone($phone);
                }
                if($user->getUsername() != $phone && $phone != '' && $phone != null){
                    $user_count = Doctrine_Query::create()
                        ->select("u.*")
                        ->from("User u")
                        ->where("u.username = ?", $phone)
                        ->andWhere("u.id != ?", $user->getId())
                        ->count();

                    if($user_count > 0){
                        $msg = 'Пользователь с таким номером телефона уже существует';
                    } else {
                        $user->setUsername($phone);
                    }
                }
                if($user->getEmail() != $email && $email != '' && $email != null){
                    $user->setEmail($email);
                }
                if($psw != '' && $psw != null){
                    $user->setPassword($psw);
                }
                if($user->getAddress() != $address && $address != '' && $address != null){
                    $user->setAddress($address);
                }

                if($msg == ''){
                    $user->save();

                    $data['state'] = 'ok';
                }
            } else {
                $data['msg'] = 'Пользователь не найден';
            }

        } else {
            $data['msg'] = 'Ошибка при добавлении заявки';
        }

        echo json_encode($data);
        return sfView::NONE;
    }

    public function executeSignout(sfWebRequest $request)
    {
        if ($session = $this->getUser()->getSession()) {
            $session->setUserId(null);
            $session->save();
        }
        $this->getUser()->signOut();
        $this->redirect('@homepage');
    }

    public function executeSignup(sfWebRequest $request)
    {
        if($request->hasParameter('cat_id') && $request->getParameter('cat_id') != '' && $request->getParameter('cat_id') != null){
            $this->getUser()->setAttribute('cat_id', $request->getParameter('cat_id'));
        }
        if($request->hasParameter('weight') && $request->getParameter('weight') != '' && $request->getParameter('weight') != null){
            $this->getUser()->setAttribute('weight', $request->getParameter('weight'));
        }

        if ($this->getUser()->isAuthenticated()) {
            $this->redirect('@homepage');
        }
        
        if ($request->isMethod('post')) {
            $cat_id = $this->getUser()->getAttribute('cat_id');
            $weight = $this->getUser()->getAttribute('weight');

            $name = $request->getParameter('name');
            $phone = preg_replace("/[^,.0-9]/", '', $request->getParameter('phone'));
            $psw = $request->getParameter('psw');
            $email = $request->getParameter('email');
            $address = $request->getParameter('address');


            $user = Doctrine::getTable("User")->findOneByUsername($phone);

            $msg = '';
            if(!$user){
                $newUser = new User();
                $newUser->setUsername($phone);
                $newUser->setPhone($phone);
                $newUser->setName($name);
                $newUser->setEmail($email);
                $newUser->setAddress($address);
                $newUser->setPassword($psw);
                $newUser->setPasswordRecovery($psw);
                $newUser->save();

                if($newUser){
                    if($cat_id != '' && $cat_id != null && $weight != '' && $weight != null){
                        $addBid = $this->getAddBid($newUser->getId(), $cat_id, $weight);
                    }
                    $this->getUser()->signIn($newUser);
                } else {
                    $msg = 'Ошибка регистрации';
                }
            } else {
                $msg = 'Пользователь с таким номером уже существует';
            }
            $json = array();
            if($msg != ''){
                $json['state'] = 'error';
                $json['msg'] = $msg;
            } else {
                $json['state'] = 'ok';
            }

            echo json_encode($json);
            return sfView::NONE;
        }
    }

    public function executeSignin(sfWebRequest $request)
    {
        if($request->hasParameter('cat_id') && $request->getParameter('cat_id') != '' && $request->getParameter('cat_id') != null){
            $this->getUser()->setAttribute('cat_id', $request->getParameter('cat_id'));
        }
        if($request->hasParameter('weight') && $request->getParameter('weight') != '' && $request->getParameter('weight') != null){
            $this->getUser()->setAttribute('weight', $request->getParameter('weight'));
        }

        if ($this->getUser()->isAuthenticated()) {
            $this->redirect('@homepage');
        }

        if ($request->hasParameter('ok') && sfConfig::get('sf_environment') === 'dev') {
            $ok_user = Doctrine::getTable("User")->find($request->getParameter('ok'));
            if ($ok_user) {
                if($this->getUser()->isAuthenticated()){
                    $this->getUser()->signOut();
                }
                $this->getUser()->signIn($ok_user);
                die('success');
            } else {
                die('no_user');
            }
        }

        $this->form = new cashSigninForm();

        if ($request->isMethod('post')) {
            $json = array();

            if($request->hasParameter('is_json')){
                $params = array(
                    '_csrf_token' => $request->getParameter('_csrf_token'),
                    'username' => $request->getParameter('phone'),
                    'password' => $request->getParameter('psw')
                );
            } else {
                $params = $request->getparameter($this->form->getName());
                //$tuser = Doctrine::getTable("User")->findOneByUsername($request->getParameter('phone'));
            }

            $this->form->bind($params);
            if ($this->form->isValid()) {
            //$this->getUser()->signIn($tuser);
                $this->getUser()->signIn($this->form->getValue('user'));

                if($this->getUser()->isAuthenticated()){
                    $cat_id = $this->getUser()->getAttribute('cat_id');
                    $weight = $this->getUser()->getAttribute('weight');

                    if($cat_id != '' && $cat_id != null && $weight != '' && $weight != null){
                        $addBid = $this->getAddBid($this->getUser()->getAccount()->getId(), $cat_id, $weight);
                    }

                    if($request->hasParameter('is_json')){
                        $json['state'] = 'ok';

                    } else {
                        $this->redirect('@homepage');
                    }

                } else {
                    if($request->hasParameter('is_json')){
                        $json['state'] = 'error';
                        $json['msg'] = 'Не удалось авторизоваться';
                    }
                }

                if($request->hasParameter('is_json')){
                    $json['state'] = 'ok';
                } else {
                    $this->redirect('@homepage');
                }
            } else {
                if($request->hasParameter('is_json')){
                    $json['state'] = 'error';
                    $json['msg'] = 'Неверный логин или пароль';
                }
            }

            if($request->hasParameter('is_json') && count($json) > 0){
                echo json_encode($json);
                return sfView::NONE;
            }
        }
    }
}