/*
@params OrderEvent $order
Checks if order payment module is paypal and if order new status is paid, send an email to the customer.
766769
public function updateStatus(OrderEvent $event)
    {
        $order = $event->getOrder();

        if ($order->isPaid() && $order->getPaymentModuleId() == Atos::getModuleId()) {
            if (Atos::getConfigValue('send_payment_confirmation_message')) {
                $this->mailer->sendEmailToCustomer(
                    Atos::CONFIRMATION_MESSAGE_NAME,
                    $order->getCustomer(),
                    [
                        'order_id'  => $order->getId(),
                        'order_ref' => $order->getRef()
                    ]
                );
            }

            // Send confirmation email if required.
            if (Atos::getConfigValue('send_confirmation_message_only_if_paid')) {
                $event->getDispatcher()->dispatch(TheliaEvents::ORDER_SEND_CONFIRMATION_EMAIL, $event);
            }

            Tlog::getInstance()->debug("Confirmation email sent to customer " . $order->getCustomer()->getEmail());
        }
    }
471448
public function saveOrder(OrderOnCreatedEvent $event)
    {
        $order = $event->getOrder();

        $this->orderObjectManager->persist($order);
        $this->orderObjectManager->flush($order);
    }
626072
private function addPaymentMethods(Order $order, ElementInterface $radioGroup)
    {
        $paymentMethods = $this->getPaymentMethodProvider()->getPaymentMethodsForOrder($order);
        
        $paymentMethods->map(function (PaymentMethod $paymentMethod) use ($radioGroup) {
            $radioGroup->addOptionToSelect($paymentMethod->getId(), $paymentMethod->translate()->getName());
        });
    }
801149
public function dispatchOrderLineOnCreatedEvent(
        OrderInterface $order,
        CartLineInterface $cartLine,
        OrderLineInterface $orderLine
    ) {
        $orderLineOnCreatedEvent = new OrderLineOnCreatedEvent(
            $order,
            $cartLine,
            $orderLine
        );

        $this->eventDispatcher->dispatch(
            ElcodiCartEvents::ORDERLINE_ONCREATED,
            $orderLineOnCreatedEvent
        );

        return $this;
    }
191618
public function onCallbackSuccess($order, $data = null)
    {
        $paymentId  = is_array($data) ? $data['paymentId'] : $data->paymentId;

        $payerId    = is_array($data) ? $data['PayerID'] : $data->PayerID;

        $this->statusCode = 'failed';

        $this->detail = sprintf('Payment failed. Ref: %s', $paymentId);

        // Begin paypal
        try {

            $this->setContext();

            $payment = Payment::get($paymentId, $this->apiContext);
            
            $execution = new PaymentExecution();

            $execution->setPayerId($payerId);

            $payment->execute($execution, $this->apiContext);

            $payment = Payment::get($paymentId, $this->apiContext);

            $this->statusCode = 'completed';

            $this->transactionId = $payment->id;

            $this->detail = 'Success';

        } catch (PayPalConnectionException $e) {

            $response = json_decode($e->getData());

            throw new GatewayException(
                sprintf(
                    '%s: %s',
                    $response->name,
                    isset($response->message) ? $response->message : 'Paypal payment Failed.'
                ),
                1001,
                $e
            );

        } catch (\Exception $e) {

            throw new GatewayException(
                $e->getMessage(),
                1000,
                $e
            );

        }
    }
1330078
public function onPostStateChange(OrderEvent $event)
    {
        $order = $event->getOrder();
        $cart  = $this->provider->getCart();
        if ($order->getId() === $cart->getId() && $order->getType() !== OrderTypes::TYPE_CART) {
            $this->provider->clearCart();
        }
    }
137019
public function addPayment(\OxidEsales\PayPalModule\Model\OrderPayment $payment)
    {
        $paymentList = $this->getPaymentList();
        $paymentList->addPayment($payment);
        $this->setPaymentList(null);
    }
603227
public function onPostDelete(OrderEvent $event)
    {
        $order = $event->getOrder();
        if ($order->getType() === OrderTypes::TYPE_CART) {
            $this->provider->clearCart();
        }
    }
755850
public function sendConfirmationEmail(OrderEvent $event)
    {
        if (Atos::getConfigValue('send_confirmation_message_only_if_paid')) {
            // We send the order confirmation email only if the order is paid
            $order = $event->getOrder();

            if (! $order->isPaid() && $order->getPaymentModuleId() == Atos::getModuleId()) {
                $event->stopPropagation();
            }
        }
    }
153705
public function check(SpySalesOrderItem $orderItem)
    {
        return $this->getFacade()
            ->isPaymentOverpaid($orderItem->getFkSalesOrder(), $orderItem->getIdSalesOrderItem());
    }
60336
public function sendNotification($order)
    {
        // Deal with customer email
        if ($order->Email && ($this->SendNotificationTo == 'Customer' || $this->SendNotificationTo == "Both")) {
            if ($this->CustomSubject) {
                $subject = $this->CustomSubject;
            } else {
                $subject = _t('Orders.Order', 'Order') . " {$order->FullRef} {$order->Status}";
            }

            $email = Email::create()
                ->setSubject($subject)
                ->setTo($order->Email)
                ->setHTMLTemplate("\\SilverCommerce\\OrdersAdmin\\Email\\OrderNotificationEmail_Customer")
                ->setData([
                    "Order" => $order,
                    "SiteConfig" => $this->Parent(),
                    "Notification" => $this
                ]);

            if ($this->FromEmail) {
                $email->setFrom($this->FromEmail);
            }
            
            $this->extend("augmentEmailCustomer", $email, $order);
            
            $email->send();
        }

        // Deal with vendor email
        if ($this->VendorEmail && ($this->SendNotificationTo == 'Vendor' || $this->SendNotificationTo == "Both")) {
            if ($this->CustomSubject) {
                $subject = $this->CustomSubject;
            } else {
                $subject = _t('Orders.Order', 'Order') . " {$order->FullRef} {$order->Status}";
            }
            
            $email = Email::create()
                ->setSubject($subject)
                ->setTo($this->VendorEmail)
                ->setHTMLTemplate("\\SilverCommerce\\OrdersAdmin\\Email\\OrderNotificationEmail_Vendor")
                ->setData([
                    "Order" => $order,
                    "Notification" => $this
                ]);

            if ($this->FromEmail) {
                $email->setFrom($this->FromEmail);
            }
            
            $this->extend("augmentEmailVendor", $email, $order);
            
            $email->send();
        }
        
        $this->extend("augmentSend", $order);
    }
382018
public function setPaymentStatus($status, \OxidEsales\Eshop\Application\Model\Order $order = null)
    {
        $this->setValue('oepaypal_paymentstatus', $status);

        // if payment completed, set order paid
        if ($status == \OxidEsales\PayPalModule\Model\PayPalOrder::PAYPAL_ORDER_STATE_COMPLETED) {
            if (is_null($order)) {
                $order = oxNew(\OxidEsales\Eshop\Application\Model\Order::class);
                $order->load($this->getOrderId());
            }
            $order->markOrderPaid();
        }
    }
1059842
public function sendStatusMail( $order, $user = null ) {

		$fromEmail 	= $this->mailProperties->getSenderEmail();
		$fromName 	= $this->mailProperties->getSenderName();
		$status		= $order->getStatusStr();
		$user		= isset( $user ) ? $user : $order->creator;
		$toEmail	= $user->email;

		$this->getMailer()->compose( self::MAIL_STATUS, [ 'coreProperties' => $this->coreProperties, 'order' => $order, 'user' => $user ] )
			->setTo( $toEmail )
			->setFrom( [ $fromEmail => $fromName ] )
			->setSubject( "Order $status | " . $this->coreProperties->getSiteName() )
			->send();
	}
1305789
public function dispatchOrderOnCreatedEvent(
        CartInterface $cart,
        OrderInterface $order
    ) {
        $orderPreCreatedEvent = new OrderOnCreatedEvent($cart, $order);
        $this->eventDispatcher->dispatch(
            ElcodiCartEvents::ORDER_ONCREATED,
            $orderPreCreatedEvent
        );

        return $this;
    }
894469
public function check(SpySalesOrderItem $orderItem)
    {
        return $this->getFacade()
            ->isPaymentPaid($orderItem->getFkSalesOrder(), $orderItem->getIdSalesOrderItem());
    }
3291
function after_process() {
    global $insert_id, $db, $order;
    if ($_SESSION['paypal_transaction_PDT_passed'] != true) {
      $_SESSION['order_created'] = '';
      unset($_SESSION['paypal_transaction_PDT_passed']);
      return false;
    } else {
    // PDT found order to be approved, so add a new OSH record for this order's PP details
      unset($_SESSION['paypal_transaction_PDT_passed']);
      $sql_data_array= array(array('fieldName'=>'orders_id', 'value'=>$insert_id, 'type'=>'integer'),
                             array('fieldName'=>'orders_status_id', 'value'=>$this->order_status, 'type'=>'integer'),
                             array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'),
                             array('fieldName'=>'customer_notified', 'value'=>0, 'type'=>'integer'),
                             array('fieldName'=>'comments', 'value'=>'PayPal status: ' . $this->pdtData['payment_status'] . ' ' . ' @ ' . $this->pdtData['payment_date'] . "\n" . ' Trans ID:' . $this->pdtData['txn_id'] . "\n" . ' Amount: ' . $this->pdtData['mc_gross'] . ' ' . $this->pdtData['mc_currency'] . '.', 'type'=>'string'));
      $db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
      ipn_debug_email('PDT NOTICE :: Order added: ' . $insert_id . "\n" . 'PayPal status: ' . $this->pdtData['payment_status'] . ' ' . ' @ ' . $this->pdtData['payment_date'] . "\n" . ' Trans ID:' . $this->pdtData['txn_id'] . "\n" . ' Amount: ' . $this->pdtData['mc_gross'] . ' ' . $this->pdtData['mc_currency']);

      // store the PayPal order meta data -- used for later matching and back-end processing activities
      $sql_data_array = array('order_id' => $insert_id,
                          'txn_type' => $this->pdtData['txn_type'],
                          'module_name' => $this->code . ' ' . $this->codeVersion,
                          'module_mode' => 'PDT',
                          'reason_code' => $this->pdtData['reasoncode'],
                          'payment_type' => $this->pdtData['payment_type'],
                          'payment_status' => $this->pdtData['payment_status'],
                          'pending_reason' => $this->pdtData['pendingreason'],
                          'invoice' => $this->pdtData['invoice'],
                          'first_name' => $this->pdtData['first_name'],
                          'last_name' => $this->pdtData['last_name'],
                          'payer_business_name' => $order->billing['company'],
                          'address_name' => $order->billing['name'],
                          'address_street' => $order->billing['street_address'],
                          'address_city' => $order->billing['city'],
                          'address_state' => $order->billing['state'],
                          'address_zip' => $order->billing['postcode'],
                          'address_country' => $this->pdtData['residence_country'], // $order->billing['country']
                          'address_status' => $this->pdtData['address_status'],
                          'payer_email' => $this->pdtData['payer_email'],
                          'payer_id' => $this->pdtData['payer_id'],
                          'payer_status' => $this->pdtData['payer_status'],
                          'payment_date' => datetime_to_sql_format($this->pdtData['payment_date']),
                          'business' => $this->pdtData['business'],
                          'receiver_email' => $this->pdtData['receiver_email'],
                          'receiver_id' => $this->pdtData['receiver_id'],
                          'txn_id' => $this->pdtData['txn_id'],
                          'parent_txn_id' => $this->pdtData['parent_txn_id'],
                          'num_cart_items' => (float)$this->pdtData['num_cart_items'],
                          'mc_gross' => (float)$this->pdtData['mc_gross'],
                          'mc_fee' => (float)$this->pdtData['mc_fee'],
                          'mc_currency' => $this->pdtData['mc_currency'],
                          'settle_amount' => (float)$this->pdtData['settle_amount'],
                          'settle_currency' => $this->pdtData['settle_currency'],
                          'exchange_rate' => ($this->pdtData['exchange_rate'] > 0 ? $this->pdtData['exchange_rate'] : 1.0),
                          'notify_version' => (float)$this->pdtData['notify_version'],
                          'verify_sign' => $this->pdtData['verify_sign'],
                          'date_added' => 'now()',
                          'memo' => '{Successful PDT Confirmation - Record auto-generated by payment module}'
                         );
//TODO: $db->perform vs zen_db_perform
      zen_db_perform(TABLE_PAYPAL, $sql_data_array);
      ipn_debug_email('PDT NOTICE :: paypal table updated: ' . print_r($sql_data_array, true));
    }
  }
465210
public function confirmPayment($orderId)
    {
        try {
            $orderId = \intval($orderId);

            if (null !== $order = $this->getOrder($orderId)) {
                $this->getLog()->addInfo(
                    $this->getTranslator()->trans(
                        "Processing confirmation of order ref. %ref, ID %id",
                        array('%ref' => $order->getRef(), '%id' => $order->getId())
                    )
                );

                $event = new OrderEvent($order);

                $event->setStatus(OrderStatusQuery::getPaidStatus()->getId());

                $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);

                $this->getLog()->addInfo(
                    $this->getTranslator()->trans(
                        "Order ref. %ref, ID %id has been successfully paid.",
                        array('%ref' => $order->getRef(), '%id' => $order->getId())
                    )
                );
            }
        } catch (\Exception $ex) {
            $this->getLog()->addError(
                $this->getTranslator()->trans(
                    "Error occured while processing order ref. %ref, ID %id: %err",
                    array(
                        '%err' => $ex->getMessage(),
                        '%ref' => !isset($order) ? "?" : $order->getRef(),
                        '%id' => !isset($order) ? "?" : $order->getId()
                    )
                )
            );

            throw $ex;
        }
    }