<?php
if (!defined("ROOT_PATH"))
{
    header("HTTP/1.1 403 Forbidden");
    exit;
}
class pjExtraPayments extends pjExtraPaymentsAppController
{
    public function pjActionIndex()
    {
        $this->setLayout('pjActionEmpty');
        
        $params = $this->getParams();
        
        $arr = pjExtraPaymentModel::factory()->where('foreign_id', $params['foreign_id'])->findAll()->getData();
        
        $this->set('params', $params);
        $this->set('arr', $arr);
    }
    
    public function pjActionCreatePayment()
    {
        $this->setLayout('pjActionEmpty');
        $this->setAjax(true);
        if(self::isPost())
        {
            $post = $this->_post->raw();
            $data = array();
            $data['created'] = date('Y-m-d H:i:s');
            $data['uuid'] = $this->uuid();
            $id = pjExtraPaymentModel::factory(array_merge($post, $data))->insert()->getInsertId();
            if ($id !== false && (int) $id > 0)
            {
                pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'foreign_id' => $post['foreign_id'], 'text' => ''));
            }else{
                pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
            }
        }
    }
    
    public function pjActionUpdatePayment()
    {
        $this->setLayout('pjActionEmpty');
        $this->setAjax(true);
        if(self::isPost() && $this->_post->check('id'))
        {
            $id = $this->_post->toInt('id');
            $post = $this->_post->raw();
            pjExtraPaymentModel::factory()->set('id', $id)->modify($post);
            $arr = pjExtraPaymentModel::factory()->find($id)->getData();
            pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'foreign_id' => $arr['foreign_id'], 'text' => ''));
        }
        exit;
    }
    
    public function pjActionGetExtraPayments()
    {
        $this->setLayout('pjActionEmpty');
        $this->setAjax(true);
        if(self::isGet() && $this->_get->check('foreign_id'))
        {
            $arr = pjExtraPaymentModel::factory()->where('foreign_id', $this->_get->toInt('foreign_id'))->findAll()->getData();
            $this->set('arr', $arr);
        }
    }
    
    public function pjActionGetExtraPaymentDetails()
    {
        $this->setLayout('pjActionEmpty');
        $this->setAjax(true);
        if(self::isGet() && $this->_get->check('id'))
        {
            $arr = pjExtraPaymentModel::factory()->find($this->_get->toInt('id'))->getData();
            $hash = sha1($arr['id'].$arr['created'].PJ_SALT);
            $payment_url = $this->option_arr['o_extra_payment_url'];
            $payment_url .= '#!/Payments/id:' . $arr['id'] . '/hash:' . $hash;
            $payment_url = '<a href="'.$payment_url.'" target="_blank">'.$payment_url.'</a>';
            pjAppController::jsonResponse(array('status' => 'ERR', 'arr' => $arr, 'text' => '', 'url' => $payment_url));
        }else{
            pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
        }
    }
    
    public function pjActionGetEmailContent()
    {
        $this->setAjax(true);
        
        if ($this->isXHR())
        {
            if (self::isGet())
            {
                if($id = $this->_get->toInt('id'))
                {
                    if (class_exists('pjNotificationModel'))
                    {
                        $pjNotificationModel = pjNotificationModel::factory();
                        $notification = $pjNotificationModel->reset()->where('recipient', 'client')->where('transport', 'email')->where('variant', 'extra_payments')->findAll()->getDataIndex(0);
                        if((int) $notification['id'] > 0 && $notification['is_active'] == 1)
                        {
                            $arr = pjExtraPaymentModel::factory()->find($id)->getData();
                            $locale_id = isset($arr['locale_id']) && (int) $arr['locale_id'] > 0 ? (int) $arr['locale_id'] : $this->getLocaleId();
                            $resp = pjFront::pjActionGetSubjectMessage($notification, $locale_id, $this->getForeignId());
                            $tokens = pjExtraPayments::pjActionTokenizer($arr['client_id'], $arr, $locale_id, $this->option_arr);
                            $lang_message = $resp['lang_message'];
                            $lang_subject = $resp['lang_subject'];
                            $subject_client = str_replace($tokens['search'], $tokens['replace'], $lang_subject[0]['content']);
                            $message_client = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
                            $this->set('arr', array(
                                'id' => $id,
                                'to' => $tokens['user']['email'],
                                'message' => $message_client,
                                'subject' => $subject_client
                            ));
                        }
                    }
                }
            }
        }
    }
    public function pjActionSendPaymentEmail()
    {
        $this->setAjax(true);
        
        if ($this->isXHR())
        {
            if (self::isPost())
            {
                if($this->_post->toInt('send_email') && $this->_post->toString('to') && $this->_post->toString('subject') && $this->_post->toString('message') && $this->_post->toInt('id'))
                {
                    $Email = self::getMailer($this->option_arr);
                    $r = $Email
                    ->setTo($this->_post->toString('to'))
                    ->setSubject($this->_post->toString('subject'))
                    ->send($this->_post->toString('message'));
                    if (isset($r) && $r)
                    {
                        pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
                    }
                    pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
                }
            }
        }
    }
    public function pjActionDelete()
    {
        $this->setAjax(true);
        
        if (!$this->isXHR())
        {
            self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
        }
        
        if (!self::isGet() && !$this->_get->check('id') && $this->_get->toInt('id') < 0)
        {
            self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
        }
        
        $response = array();
        if (pjExtraPaymentModel::factory()->set('id', $this->_get->toInt('id'))->erase()->getAffectedRows() == 1)
        {
            $response = array('status' => 'OK');
        } else {
            $response = array('status' => 'ERR');
        }
        self::jsonResponse($response);
    }
    public function pjActionGetPayments()
    {
        $this->setAjax(true);
        $this->setLayout('pjActionEmpty');
        
        $response = array();
        if(self::isGet() && $this->_get->check('id') && $this->_get->check('hash') && $this->_get->toInt('id') > 0 && !$this->_get->isEmpty('hash'))
        {
            $id = $this->_get->toInt('id');
            $hash = $this->_get->toString('hash');
            $pjExtraPaymentModel = pjExtraPaymentModel::factory();
            $arr = $pjExtraPaymentModel->reset()->find($id)->getData();
            if(!empty($arr))
            {
                $check_hash = sha1($id.$arr['created'].PJ_SALT);
                if($check_hash == $hash)
                {
                    $locale_id = $this->getLocaleId();
                    $this->set('arr', $arr);
                    $this->set('client_id', $arr['client_id']);
                    $this->set('locale_id', $locale_id);
                    if(pjObject::getPlugin('pjPayments') !== NULL)
                    {
                        $this->set('payment_option_arr', pjPaymentOptionModel::factory()->getOptions($this->getForeignId()));
                        $this->set('payment_titles', pjPayments::getPaymentTitles($this->getForeignId(), $locale_id));
                    }else{
                        $this->set('payment_titles', __('payment_methods', true));
                    }
                    $response = array('status' => 'OK', 'code' => '200');
                }else{
                    $response = array('status' => 'ERR', 'code' => '103');
                }
            }else{
                $response = array('status' => 'ERR', 'code' => '102');
            }
        }else{
            $response = array('status' => 'ERR', 'code' => '100');
        }
        $this->set('response', $response);
    }
    
    public function pjActionPaymentForm()
    {
        $this->setAjax(true);
        $this->setLayout('pjActionEmpty');
        if(self::isPost() && $this->_post->check('id') && $this->_post->check('client_id') && $this->_post->check('payment_method'))
        {
            if(pjObject::getPlugin('pjPayments') !== NULL)
            {
                $id = $this->_post->toInt('id');
                $client_id = $this->_post->toInt('client_id');
                $locale_id = $this->_post->toInt('locale_id');
                $client = pjClientModel::factory()->find($client_id)->getData();
                $user = pjAuthUserModel::factory()->find($client['foreign_id'])->getData();
                $arr = pjExtraPaymentModel::factory()->find($id)->getData();
                
                $payment_method = $this->_post->toString('payment_method');
                $pjPlugin = pjPayments::getPluginName($payment_method);
                if(pjObject::getPlugin($pjPlugin) !== NULL)
                {
                    $params = $pjPlugin::getFormParams(array('payment_method' => $payment_method), array(
                        'locale_id'	    => $locale_id,
                        'return_url'	=> $this->option_arr['o_thankyou_page'],
                        'id'			=> $id,
                        'foreign_id'	=> NULL,
                    	'uuid'		    => $arr['uuid'],
                        'name'		    => @$user['name'],
                        'email'		    => @$user['email'],
                        'phone'		    => @$user['phone'],
                        'amount'		=> $this->_post->toFloat('amount'),
                    	'cancel_hash'   => sha1($arr['uuid'].$arr['created'].PJ_SALT),
                        'currency_code' => $this->option_arr['o_currency'],
                    ));
                    $this->set('params', $params);
                }
                if ($payment_method == 'bank')
                {
                    $bank_account = pjMultiLangModel::factory()->select('t1.content')
                    ->where('t1.model','pjOption')
                    ->where('t1.locale', $locale_id)
                    ->where('t1.field', 'o_bank_account')
                    ->limit(1)
                    ->findAll()->getDataIndex(0);
                    $this->set('bank_account', $bank_account['content']);
                }
                $this->set('payment_method', $payment_method);
            }
        }
    }
    
    public function pjActionConfirm()
    {
        $this->setAjax(true);
        
        if (pjObject::getPlugin('pjPayments') === NULL)
        {
            $this->log('pjPayments plugin not installed');
            exit;
        }
        
        $pjPayments = new pjPayments();
        $post = $this->_post->raw();
        $get = $this->_get->raw();
        $request = array();
        if(isset($get['payment_method']))
        {
            $request = $get;
        }
        if(isset($post['payment_method']))
        {
            $request = $post;
        }
        $foreign_id = NULL;
    	if(isset($get['foreign_id']) && (int)$get['foreign_id'] > 0) {
            $foreign_id = (int)$get['foreign_id'];
        } elseif(isset($post['foreign_id']) && (int)$post['foreign_id'] > 0) {
             $foreign_id = (int)$post['foreign_id'];
        }
        if($pjPlugin = $pjPayments->getPaymentPlugin($request))
        {
            if($uuid = $this->requestAction(array('controller' => $pjPlugin, 'action' => 'pjActionGetCustom', 'params' => $request), array('return')))
            {
                $pjExtraPaymentModel = pjExtraPaymentModel::factory();
                $arr = $pjExtraPaymentModel->where('t1.uuid', $uuid)->limit(1)->findAll()->getDataIndex(0);
                if (!empty($arr))
                {
                    $amount = $arr['amount'];
                    $params = array(
                        'request'        => $request,
                        'payment_method' => $request['payment_method'],
                        'foreign_id'     => $foreign_id,
                        'amount'         => $amount,
                        'txn_id'         => NULL,
                        'order_id'       => $uuid,
                    	'cancel_hash'    => sha1($uuid.$arr['created'].PJ_SALT),
                        'key'            => md5($this->option_arr['private_key'] . PJ_SALT)
                    );
                    $response = $this->requestAction(array('controller' => $pjPlugin, 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
                    if($response['status'] == 'OK')
                    {
                        $this->log("Payments | {$pjPlugin} plugin<br>Extra payment was confirmed. UUID: {$uuid}");
                        $pjExtraPaymentModel->reset()->set('id', $arr['id'])->modify(array('payment_status' => 'paid'));
                        echo $this->option_arr['o_thankyou_page'];
                        exit;
                    }elseif($response['status'] == 'CANCEL'){
                        $this->log("Payments | {$pjPlugin} plugin<br>Extra payment was cancelled. UUID: {$uuid}");
                        echo $this->option_arr['o_thankyou_page'];
                        exit;
                    }else{
                        $this->log("Payments | {$pjPlugin} plugin<br>Extra payment confirmation was failed. UUID: {$uuid}");
                    }
                    if(isset($response['redirect']) && $response['redirect'] == true)
                    {
                        echo $this->option_arr['o_thankyou_page'];
                        exit;
                    }
                }else{
                    $this->log("Payments | {$pjPlugin} plugin<br>Extra payment with UUID {$uuid} not found.");
                }
            }
        }
        echo $this->option_arr['o_thankyou_page'];
        exit;
    }
    
    public static function pjActionTokenizer($client_id, $data, $locale_id, $option_arr)
    {
        $client = pjClientModel::factory()
        ->select("t1.*, t2.content as country_name")
        ->join('pjBaseMultiLang', "t2.model='pjBaseCountry' AND t2.foreign_id=t1.c_country AND t2.field='name' AND t2.locale='".$locale_id."'", 'left outer')
        ->find($client_id)->getData();
        $user_id = $client['foreign_id'];
        $user = pjAuthUserModel::factory()->find($user_id)->getData();
        
        $personal_titles = __('personal_titles', true);
        $hash = sha1($data['id'].$data['created'].PJ_SALT);
        $payment_url = $option_arr['o_extra_payment_url'];
        $payment_url .= '#!/Payments/id:' . $data['id'] . '/hash:' . $hash;
        $payment_url = '<a href="'.$payment_url.'">'.$payment_url.'</a>';
        $search = array(
            '{PaymentTitle}',
            '{PaymentAmount}',
            '{PaymentDescription}',
            '{PaymentURL}',
            '{Title}',
            '{Name}',
            '{Phone}',
            '{Email}',
            '{Notes}',
            '{Company}',
            '{Address}',
            '{City}',
            '{State}',
            '{Zip}',
            '{Country}'
        );
        $replace = array(
            $data['title'],
            pjCurrency::formatPrice($data['amount']),
            nl2br($data['description']),
            $payment_url,
            $personal_titles[$client['c_title']],
            $user['name'],
            $user['phone'],
            $user['email'],
            $client['c_notes'],
            $client['c_company'],
            $client['c_address'],
            $client['c_city'],
            $client['c_state'],
            $client['c_zip'],
            $client['country_name']
        );
        return compact('search', 'replace', 'user');
    }
    
	protected function uuid()
	{
		return chr(rand(65,90)) . chr(rand(65,90)) . time();
	}
}
?>