Completed
Push — master ( e00620...73f050 )
by
unknown
16s queued 11s
created

WcPagantisGateway::getPromotedAmount()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 0
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
//namespace empty
4
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
5
use Pagantis\OrdersApiClient\Model\Order\User\Address;
6
use Pagantis\OrdersApiClient\Model\Order\User;
7
use Pagantis\OrdersApiClient\Model\Order\User\OrderHistory;
8
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details;
9
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart;
10
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product;
11
use Pagantis\OrdersApiClient\Model\Order\Metadata;
12
use Pagantis\OrdersApiClient\Model\Order\Configuration\Urls;
13
use Pagantis\OrdersApiClient\Model\Order\Configuration\Channel;
14
use Pagantis\OrdersApiClient\Model\Order\Configuration;
15
use Pagantis\OrdersApiClient\Client;
16
use Pagantis\OrdersApiClient\Model\Order;
17
use Pagantis\ModuleUtils\Model\Log\LogEntry;
18
19
if (!defined('ABSPATH')) {
20
    exit;
21
}
22
23
define('__ROOT__', dirname(dirname(__FILE__)));
24
25
26
class WcPagantisGateway extends WC_Payment_Gateway
0 ignored issues
show
Bug introduced by
The type WC_Payment_Gateway was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
{
28
    const METHOD_ID = "pagantis";
29
30
    /** Orders tablename */
31
    const ORDERS_TABLE = 'cart_process';
32
33
    /** Concurrency tablename */
34
    const LOGS_TABLE = 'pagantis_logs';
35
36
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
37
38
    const CONFIG_TABLE = 'pagantis_config';
39
40
    /** @var Array $extraConfig */
41
    public $extraConfig;
42
43
    /** @var string $language */
44
    public $language;
45
46
    /**
47
     * WcPagantisGateway constructor.
48
     */
49
    public function __construct()
50
    {
51
        //Mandatory vars for plugin
52
        $this->id = WcPagantisGateway::METHOD_ID;
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
53
        $this->has_fields = true;
0 ignored issues
show
Bug Best Practice introduced by
The property has_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
54
        $this->method_title = ucfirst($this->id);
0 ignored issues
show
Bug Best Practice introduced by
The property method_title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
55
56
        //Useful vars
57
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

57
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
Bug Best Practice introduced by
The property template_path does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
58
        $this->allowed_currencies = array("EUR");
0 ignored issues
show
Bug Best Practice introduced by
The property allowed_currencies does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
59
        $this->mainFileLocation = dirname(plugin_dir_path(__FILE__)) . '/WC_Pagantis.php';
0 ignored issues
show
Bug Best Practice introduced by
The property mainFileLocation does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
60
        $this->plugin_info = get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
0 ignored issues
show
Bug introduced by
The function get_file_data was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

60
        $this->plugin_info = /** @scrutinizer ignore-call */ get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
Loading history...
Bug Best Practice introduced by
The property plugin_info does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
61
        $this->language = strstr(get_locale(), '_', true);
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

61
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
62
63
        if ($this->language == 'es' || $this->language == '') {
64
            $this->icon = esc_url(plugins_url('../assets/images/logopagamastarde.png', __FILE__));
0 ignored issues
show
Bug Best Practice introduced by
The property icon does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
The function esc_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

64
            $this->icon = /** @scrutinizer ignore-call */ esc_url(plugins_url('../assets/images/logopagamastarde.png', __FILE__));
Loading history...
Bug introduced by
The function plugins_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

64
            $this->icon = esc_url(/** @scrutinizer ignore-call */ plugins_url('../assets/images/logopagamastarde.png', __FILE__));
Loading history...
65
        } else {
66
            $this->icon = esc_url(plugins_url('../assets/images/logo.png', __FILE__));
67
        }
68
69
        //Panel form fields
70
        $this->form_fields = include(plugin_dir_path(__FILE__).'../includes/settings-pagantis.php');//Panel options
0 ignored issues
show
Bug Best Practice introduced by
The property form_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
71
        $this->init_settings();
72
73
        $this->extraConfig = $this->getExtraConfig();
74
        $this->title = __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

74
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
75
76
        $this->settings['ok_url'] = ($this->extraConfig['PAGANTIS_URL_OK']!='')?$this->extraConfig['PAGANTIS_URL_OK']:$this->generateOkUrl();
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
77
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
78
        foreach ($this->settings as $setting_key => $setting_value) {
79
            $this->$setting_key = $setting_value;
80
        }
81
82
        //Hooks
83
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
0 ignored issues
show
Bug introduced by
The function add_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

83
        /** @scrutinizer ignore-call */ add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
Loading history...
84
        add_action('admin_notices', array($this, 'pagantisCheckFields'));                          //Check config fields
85
        add_action('woocommerce_receipt_'.$this->id, array($this, 'pagantisReceiptPage'));          //Pagantis form
86
        add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification'));      //Json Notification
87
        add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
0 ignored issues
show
Bug introduced by
The function add_filter was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

87
        /** @scrutinizer ignore-call */ add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
88
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
89
    }
90
91
    /**
92
     * @param $mofile
93
     * @param $domain
94
     *
95
     * @return string
96
     */
97
    public function loadPagantisTranslation($mofile, $domain)
98
    {
99
        if ('pagantis' === $domain) {
100
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

100
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
101
        }
102
        return $mofile;
103
    }
104
105
    /***********
106
     *
107
     * HOOKS
108
     *
109
     ***********/
110
111
    /**
112
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
113
     */
114
    public function admin_options()
115
    {
116
        $template_fields = array(
117
            'panel_description' => $this->method_description,
118
            'button1_label' => __('Login to your panel', 'pagantis'),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

118
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to your panel', 'pagantis'),
Loading history...
119
            'button2_label' => __('Documentation', 'pagantis'),
120
            'logo' => $this->icon,
121
            'settings' => $this->generate_settings_html($this->form_fields, false)
122
        );
123
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

123
        /** @scrutinizer ignore-call */ wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
124
    }
125
126
    /**
127
     * PANEL - Check admin panel fields -> Hook: admin_notices
128
     */
129
    public function pagantisCheckFields()
130
    {
131
        $error_string = '';
132
        if ($this->settings['enabled'] !== 'yes') {
133
            return;
134
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
135
            $error_string =  __(' is not compatible with your php and/or curl version', 'pagantis');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

135
            $error_string =  /** @scrutinizer ignore-call */ __(' is not compatible with your php and/or curl version', 'pagantis');
Loading history...
136
            $this->settings['enabled'] = 'no';
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
137
        } elseif ($this->settings['pagantis_public_key']=="" || $this->settings['pagantis_private_key']=="") {
138
            $error_string = __(' is not configured correctly, the fields Public Key and Secret Key are mandatory for use this plugin', 'pagantis');
139
            $this->settings['enabled'] = 'no';
140
        } elseif (!in_array(get_woocommerce_currency(), $this->allowed_currencies)) {
0 ignored issues
show
Bug introduced by
The function get_woocommerce_currency was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

140
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies)) {
Loading history...
141
            $error_string =  __(' only can be used in Euros', 'pagantis');
142
            $this->settings['enabled'] = 'no';
143
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']<'2'
144
                  || $this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']>'12') {
145
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
146
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']<'2'
147
                  || $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']>'12') {
148
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
149
        } elseif ($this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']<0) {
150
            $error_string = __(' can not have a minimum amount less than 0', 'pagantis');
151
        }
152
153
        if ($error_string!='') {
154
            $template_fields = array(
155
                'error_msg' => ucfirst(WcPagantisGateway::METHOD_ID).' '.$error_string,
156
            );
157
            wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

157
            /** @scrutinizer ignore-call */ 
158
            wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
158
        }
159
    }
160
161
162
    /**
163
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis
164
     * @param $order_id
165
     *
166
     * @throws Exception
167
     */
168
    public function pagantisReceiptPage($order_id)
169
    {
170
        try {
171
            require_once(__ROOT__.'/vendor/autoload.php');
172
            global $woocommerce;
173
            $order = new WC_Order($order_id);
0 ignored issues
show
Bug introduced by
The type WC_Order was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
174
            $order->set_payment_method(ucfirst($this->id));
175
            $order->save();
176
177
            if (!isset($order)) {
178
                throw new Exception(_("Order not found"));
179
            }
180
181
            $shippingAddress = $order->get_address('shipping');
182
            $billingAddress = $order->get_address('billing');
183
            if ($shippingAddress['address_1'] == '') {
184
                $shippingAddress = $billingAddress;
185
            }
186
187
            $national_id = $this->getNationalId($order);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $national_id is correct as $this->getNationalId($order) targeting WcPagantisGateway::getNationalId() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
188
            $tax_id = $this->getTaxId($order);
189
190
            $userAddress = new Address();
191
            $userAddress
192
                ->setZipCode($shippingAddress['postcode'])
193
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
194
                ->setCountryCode('ES')
195
                ->setCity($shippingAddress['city'])
196
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
197
            ;
198
            $orderShippingAddress = new Address();
199
            $orderShippingAddress
200
                ->setZipCode($shippingAddress['postcode'])
201
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
202
                ->setCountryCode('ES')
203
                ->setCity($shippingAddress['city'])
204
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
205
                ->setFixPhone($shippingAddress['phone'])
206
                ->setMobilePhone($shippingAddress['phone'])
207
                ->setNationalId($national_id)
208
                ->setTaxId($tax_id)
209
            ;
210
            $orderBillingAddress =  new Address();
211
            $orderBillingAddress
212
                ->setZipCode($billingAddress['postcode'])
213
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
214
                ->setCountryCode('ES')
215
                ->setCity($billingAddress['city'])
216
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
217
                ->setFixPhone($billingAddress['phone'])
218
                ->setMobilePhone($billingAddress['phone'])
219
                ->setNationalId($national_id)
220
                ->setTaxId($tax_id)
221
            ;
222
            $orderUser = new User();
223
            $orderUser
224
                ->setAddress($userAddress)
225
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
226
                ->setBillingAddress($orderBillingAddress)
227
                ->setEmail($billingAddress['email'])
228
                ->setFixPhone($billingAddress['phone'])
229
                ->setMobilePhone($billingAddress['phone'])
230
                ->setShippingAddress($orderShippingAddress)
231
                ->setNationalId($national_id)
232
                ->setTaxId($tax_id)
233
            ;
234
235
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
236
            foreach ($previousOrders as $previousOrder) {
237
                $orderHistory = new OrderHistory();
238
                $orderElement = wc_get_order($previousOrder);
0 ignored issues
show
Bug introduced by
The function wc_get_order was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

238
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
239
                $orderCreated = $orderElement->get_date_created();
240
                $orderHistory
241
                    ->setAmount(intval(100 * $orderElement->get_total()))
242
                    ->setDate(new \DateTime($orderCreated->date('Y-m-d H:i:s')))
0 ignored issues
show
Bug introduced by
new DateTime($orderCreated->date('Y-m-d H:i:s')) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

242
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
243
                ;
244
                $orderUser->addOrderHistory($orderHistory);
245
            }
246
247
            $metadataOrder = new Metadata();
248
            $metadata = array(
249
                'woocommerce' => WC()->version,
0 ignored issues
show
Bug introduced by
The function WC was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

249
                'woocommerce' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
250
                'pagantis'         => $this->plugin_info['Version'],
251
                'php'         => phpversion()
252
            );
253
            foreach ($metadata as $key => $metadatum) {
254
                $metadataOrder->addMetadata($key, $metadatum);
255
            }
256
257
            $details = new Details();
258
            $shippingCost = $order->shipping_total;
259
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
260
            $items = $woocommerce->cart->get_cart();
261
            $promotedAmount = 0;
262
            foreach ($items as $key => $item) {
263
                $product = new Product();
264
                $productDescription = sprintf(
265
                    '%s %s %s',
266
                    $item['data']->get_title(),
267
                    $item['data']->get_description(),
268
                    $item['data']->get_short_description()
269
                );
270
                $product
271
                    ->setAmount(intval(100 * $item['line_total']))
272
                    ->setQuantity($item['quantity'])
273
                    ->setDescription($productDescription)
274
                ;
275
                $details->addProduct($product);
276
277
                $promotedProduct = $this->isPromoted($item['product_id']);
278
                if ($promotedProduct == 'true') {
279
                    $promotedAmount+=$product->getAmount();
280
                    $promotedMessage = 'Promoted Item: ' . $product->getDescription() .
281
                                       ' Price: ' . $item['line_total'] .
282
                                       ' Qty: ' . $product->getQuantity() .
283
                                       ' Item ID: ' . $item['id_product'];
284
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
285
                }
286
            }
287
288
            $orderShoppingCart = new ShoppingCart();
289
            $orderShoppingCart
290
                ->setDetails($details)
291
                ->setOrderReference($order->get_id())
292
                ->setPromotedAmount($promotedAmount)
293
                ->setTotalAmount(intval(strval(100 * $order->total)))
294
            ;
295
            $orderConfigurationUrls = new Urls();
296
            $cancelUrl = $this->getKoUrl($order);
297
            $callback_arg = array(
298
                'wc-api'=>'wcpagantisgateway',
299
                'key'=>$order->get_order_key(),
300
                'order-received'=>$order->get_id());
301
            $callback_url = add_query_arg($callback_arg, home_url('/'));
0 ignored issues
show
Bug introduced by
The function home_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

301
            $callback_url = add_query_arg($callback_arg, /** @scrutinizer ignore-call */ home_url('/'));
Loading history...
Bug introduced by
The function add_query_arg was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

301
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, home_url('/'));
Loading history...
302
            $orderConfigurationUrls
303
                ->setCancel($cancelUrl)
304
                ->setKo($callback_url)
305
                ->setAuthorizedNotificationCallback($callback_url)
306
                ->setRejectedNotificationCallback($callback_url)
307
                ->setOk($callback_url)
308
            ;
309
            $orderChannel = new Channel();
310
            $orderChannel
311
                ->setAssistedSale(false)
312
                ->setType(Channel::ONLINE)
313
            ;
314
            $orderConfiguration = new Configuration();
315
316
            $orderConfiguration
317
                ->setChannel($orderChannel)
318
                ->setUrls($orderConfigurationUrls)
319
                ->setPurchaseCountry($this->language)
320
            ;
321
322
            $orderApiClient = new Order();
323
            $orderApiClient
324
                ->setConfiguration($orderConfiguration)
325
                ->setMetadata($metadataOrder)
326
                ->setShoppingCart($orderShoppingCart)
327
                ->setUser($orderUser)
328
            ;
329
330
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
331
                throw new \Exception('Public and Secret Key not found');
332
            }
333
            $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key);
334
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
335
            if ($pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$pagantisOrder is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
336
                $url = $pagantisOrder->getActionUrls()->getForm();
337
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
338
            } else {
339
                throw new OrderNotFoundException();
340
            }
341
342
            if ($url=="") {
343
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
344
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
345
                wp_redirect($url);
0 ignored issues
show
Bug introduced by
The function wp_redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

345
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
346
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
347
            } else {
348
                $template_fields = array(
349
                    'url' => $url,
350
                    'checkoutUrl'   => $cancelUrl
351
                );
352
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

352
                /** @scrutinizer ignore-call */ wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
353
            }
354
        } catch (\Exception $exception) {
355
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

355
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
Bug introduced by
The function wc_add_notice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

355
            /** @scrutinizer ignore-call */ 
356
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
356
            $this->insertLog($exception);
357
            $checkout_url = get_permalink(wc_get_page_id('checkout'));
0 ignored issues
show
Bug introduced by
The function wc_get_page_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

357
            $checkout_url = get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout'));
Loading history...
Bug introduced by
The function get_permalink was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

357
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
358
            wp_redirect($checkout_url);
359
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
360
        }
361
    }
362
363
    /**
364
     * NOTIFICATION - Endpoint for Json notification - Hook: woocommerce_api_wcpagantisgateway
365
     */
366
    public function pagantisNotification()
367
    {
368
        try {
369
            $origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notify' : 'Order';
370
371
            include_once('notifyController.php');
372
            $notify = new WcPagantisNotify();
373
            $notify->setOrigin($origin);
374
            /** @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result */
375
            $result = $notify->processInformation();
376
        } catch (Exception $exception) {
377
            $result['notification_message'] = $exception->getMessage();
378
            $result['notification_error'] = true;
379
        }
380
381
        $paymentOrder = new WC_Order($result->getMerchantOrderId());
382
        if ($paymentOrder instanceof WC_Order) {
383
            $orderStatus = strtolower($paymentOrder->get_status());
384
        } else {
385
            $orderStatus = 'cancelled';
386
        }
387
        $acceptedStatus = array('processing', 'completed');
388
        if (in_array($orderStatus, $acceptedStatus)) {
389
            $returnUrl = $this->getOkUrl($paymentOrder);
390
        } else {
391
            $returnUrl = $this->getKoUrl($paymentOrder);
392
        }
393
394
        wp_redirect($returnUrl);
0 ignored issues
show
Bug introduced by
The function wp_redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

394
        /** @scrutinizer ignore-call */ wp_redirect($returnUrl);
Loading history...
395
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
396
    }
397
398
    /**
399
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
400
     * @param $status
401
     * @param $order_id
402
     * @param $order
403
     *
404
     * @return string
405
     */
406
    public function pagantisCompleteStatus($status, $order_id, $order)
407
    {
408
        if ($order->get_payment_method() == WcPagantisGateway::METHOD_ID) {
409
            if ($order->get_status() == 'failed') {
410
                $status = 'processing';
411
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
412
                $status = 'processing';
413
            }
414
        }
415
416
        return $status;
417
    }
418
419
    /***********
420
     *
421
     * REDEFINED FUNCTIONS
422
     *
423
     ***********/
424
425
    /**
426
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps)
427
     * @return bool
428
     */
429
    public function is_available()
430
    {
431
        $locale = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

431
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
432
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
433
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
434
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
435
            (int)$this->get_order_total()>$this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] && $allowedCountry) {
436
            return true;
437
        }
438
439
        return false;
440
    }
441
442
    /**
443
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps)
444
     * @return string
445
     */
446
    public function get_title()
447
    {
448
        return __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

448
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
449
    }
450
451
    /**
452
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
453
     * @param $order_id
454
     * @return array
455
     */
456
    public function process_payment($order_id)
457
    {
458
        try {
459
            $order = new WC_Order($order_id);
460
461
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
462
            if (strpos($redirectUrl, 'order-pay=')===false) {
463
                $redirectUrl.="&order-pay=".$order_id;
464
            }
465
466
            return array(
467
                'result'   => 'success',
468
                'redirect' => $redirectUrl
469
            );
470
471
        } catch (Exception $e) {
472
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

472
            /** @scrutinizer ignore-call */ wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

472
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
473
            return array();
474
        }
475
    }
476
477
    /**
478
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
479
     */
480
    public function payment_fields()
481
    {
482
        $locale = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

482
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
483
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
484
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
485
        $promotedAmount = $this->getPromotedAmount();
486
487
        $template_fields = array(
488
            'public_key' => $this->pagantis_public_key,
489
            'total' => WC()->session->cart_totals['total'],
0 ignored issues
show
Bug introduced by
The function WC was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

489
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
490
            'enabled' =>  $this->settings['enabled'],
491
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
492
            'simulator_enabled' => $this->settings['pagantis_simulator'],
493
            'locale' => $locale,
494
            'allowedCountry' => $allowedCountry,
495
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
496
            'promoted_amount' => $promotedAmount
497
        );
498
        wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

498
        /** @scrutinizer ignore-call */ wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
499
    }
500
501
    /***********
502
     *
503
     * UTILS FUNCTIONS
504
     *
505
     ***********/
506
507
    /**
508
     * PANEL KO_URL FIELD
509
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
510
     */
511
    private function generateOkUrl()
512
    {
513
        return $this->generateUrl($this->get_return_url());
514
    }
515
516
    /**
517
     * PANEL OK_URL FIELD
518
     */
519
    private function generateKoUrl()
520
    {
521
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
Bug introduced by
The function get_permalink was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

521
        return $this->generateUrl(/** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout')));
Loading history...
Bug introduced by
The function wc_get_page_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

521
        return $this->generateUrl(get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout')));
Loading history...
522
    }
523
524
    /**
525
     * Replace empty space by {{var}}
526
     * @param $url
527
     *
528
     * @return string
529
     */
530
    private function generateUrl($url)
531
    {
532
        $parsed_url = parse_url($url);
533
        if ($parsed_url !== false) {
534
            $parsed_url['query'] = !isset($parsed_url['query']) ? '' : $parsed_url['query'];
535
            parse_str($parsed_url['query'], $arrayParams);
536
            foreach ($arrayParams as $keyParam => $valueParam) {
537
                if ($valueParam=='') {
538
                    $arrayParams[$keyParam] = '{{'.$keyParam.'}}';
539
                }
540
            }
541
            $parsed_url['query'] = http_build_query($arrayParams);
542
            $return_url = $this->unparseUrl($parsed_url);
543
            return urldecode($return_url);
544
        } else {
545
            return $url;
546
        }
547
    }
548
549
    /**
550
     * Replace {{}} by vars values inside ok_url
551
     * @param $order
552
     *
553
     * @return string
554
     */
555
    private function getOkUrl($order)
556
    {
557
        return $this->getKeysUrl($order, $this->ok_url);
558
    }
559
560
    /**
561
     * Replace {{}} by vars values inside ko_url
562
     * @param $order
563
     *
564
     * @return string
565
     */
566
    private function getKoUrl($order)
567
    {
568
        return $this->getKeysUrl($order, $this->ko_url);
569
    }
570
571
    /**
572
     * Replace {{}} by vars values
573
     * @param $order
574
     * @param $url
575
     *
576
     * @return string
577
     */
578
    private function getKeysUrl($order, $url)
579
    {
580
        $defaultFields = (get_class($order)=='WC_Order') ?
581
            array('order-received'=>$order->get_id(), 'key'=>$order->get_order_key()) :
582
            array();
583
584
        $parsedUrl = parse_url($url);
585
        if ($parsedUrl !== false) {
586
            //Replace parameters from url
587
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
588
589
            //Replace path from url
590
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
591
592
            $returnUrl = $this->unparseUrl($parsedUrl);
593
            return $returnUrl;
594
        }
595
        return $url;
596
    }
597
598
    /**
599
     * Replace {{}} by vars values inside parameters
600
     * @param $queryString
601
     * @param $defaultFields
602
     *
603
     * @return string
604
     */
605
    private function getKeysParametersUrl($queryString, $defaultFields)
606
    {
607
        parse_str(html_entity_decode($queryString), $arrayParams);
608
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
609
        if (count($commonKeys)) {
610
            $arrayResult = array_merge($arrayParams, $defaultFields);
611
        } else {
612
            $arrayResult = $arrayParams;
613
        }
614
        return urldecode(http_build_query($arrayResult));
615
    }
616
617
    /**
618
     * Replace {{}} by vars values inside path
619
     * @param $pathString
620
     * @param $defaultFields
621
     *
622
     * @return string
623
     */
624
    private function getKeysPathUrl($pathString, $defaultFields)
625
    {
626
        $arrayParams = explode("/", $pathString);
627
        foreach ($arrayParams as $keyParam => $valueParam) {
628
            preg_match('#\{{.*?}\}#', $valueParam, $match);
629
            if (count($match)) {
630
                $key = str_replace(array('{{','}}'), array('',''), $match[0]);
631
                $arrayParams[$keyParam] = $defaultFields[$key];
632
            }
633
        }
634
        return implode('/', $arrayParams);
635
    }
636
637
    /**
638
     * Replace {{var}} by empty space
639
     * @param $parsed_url
640
     *
641
     * @return string
642
     */
643
    private function unparseUrl($parsed_url)
644
    {
645
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
646
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
647
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
648
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
649
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
650
        $path     = $parsed_url['path'];
651
        return $scheme . $host . $port . $path . $query . $fragment;
652
    }
653
654
    /**
655
     * Get the orders of a customer
656
     * @param $current_user
657
     * @param $billingEmail
658
     *
659
     * @return mixed
660
     */
661
    private function getOrders($current_user, $billingEmail)
662
    {
663
        $sign_up = '';
664
        $total_orders = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_orders is dead and can be removed.
Loading history...
665
        $total_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_amt is dead and can be removed.
Loading history...
666
        $refund_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $refund_amt is dead and can be removed.
Loading history...
667
        $total_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_refunds is dead and can be removed.
Loading history...
668
        $partial_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $partial_refunds is dead and can be removed.
Loading history...
669
        if ($current_user->user_login) {
670
            $is_guest = "false";
0 ignored issues
show
Unused Code introduced by
The assignment to $is_guest is dead and can be removed.
Loading history...
671
            $sign_up = substr($current_user->user_registered, 0, 10);
0 ignored issues
show
Unused Code introduced by
The assignment to $sign_up is dead and can be removed.
Loading history...
672
            $customer_orders = get_posts(array(
0 ignored issues
show
Bug introduced by
The function get_posts was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

672
            $customer_orders = /** @scrutinizer ignore-call */ get_posts(array(
Loading history...
673
                'numberposts' => - 1,
674
                'meta_key'    => '_customer_user',
675
                'meta_value'  => $current_user->ID,
676
                'post_type'   => array( 'shop_order' ),
677
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded' ),
678
            ));
679
        } else {
680
            $is_guest = "true";
681
            $customer_orders = get_posts(array(
682
                'numberposts' => - 1,
683
                'meta_key'    => '_billing_email',
684
                'meta_value'  => $billingEmail,
685
                'post_type'   => array( 'shop_order' ),
686
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded'),
687
            ));
688
            foreach ($customer_orders as $customer_order) {
689
                if (trim($sign_up)=='' ||
690
                    strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)) {
691
                    $sign_up = substr($customer_order->post_date, 0, 10);
692
                }
693
            }
694
        }
695
696
        return $customer_orders;
697
    }
698
699
700
    /**
701
     * @param $orderId
702
     * @param $pagantisOrderId
703
     *
704
     * @throws Exception
705
     */
706
    private function insertRow($orderId, $pagantisOrderId)
707
    {
708
        global $wpdb;
709
        $this->checkDbTable();
710
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
711
712
        //Check if id exists
713
        $resultsSelect = $wpdb->get_results("select * from $tableName where id='$orderId'");
714
        $countResults = count($resultsSelect);
715
        if ($countResults == 0) {
716
            $wpdb->insert(
717
                $tableName,
718
                array('id' => $orderId, 'order_id' => $pagantisOrderId),
719
                array('%d', '%s')
720
            );
721
        } else {
722
            $wpdb->update(
723
                $tableName,
724
                array('order_id' => $pagantisOrderId),
725
                array('id' => $orderId),
726
                array('%s'),
727
                array('%d')
728
            );
729
        }
730
    }
731
732
    /**
733
     * Check if orders table exists
734
     */
735
    private function checkDbTable()
736
    {
737
        global $wpdb;
738
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
739
740
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
741
            $charset_collate = $wpdb->get_charset_collate();
742
            $sql             = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50),  
743
                  UNIQUE KEY id (id)) $charset_collate";
744
745
            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
0 ignored issues
show
Bug introduced by
The constant ABSPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
746
            dbDelta($sql);
0 ignored issues
show
Bug introduced by
The function dbDelta was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

746
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
747
        }
748
    }
749
750
    /**
751
     * @return array
752
     */
753
    private function getExtraConfig()
754
    {
755
        global $wpdb;
756
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
757
        $response = array();
758
        $dbResult = $wpdb->get_results("select config, value from $tableName", ARRAY_A);
0 ignored issues
show
Bug introduced by
The constant ARRAY_A was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
759
        foreach ($dbResult as $value) {
760
            $response[$value['config']] = $value['value'];
761
        }
762
763
        return $response;
764
    }
765
766
    /**
767
     * @param $order
768
     *
769
     * @return null
770
     */
771
    private function getNationalId($order)
772
    {
773
        foreach ((array)$order->get_meta_data() as $mdObject) {
774
            $data = $mdObject->get_data();
775
            if ($data['key'] == 'vat_number') {
776
                return $data['value'];
777
            }
778
        }
779
780
        return null;
781
    }
782
783
    /**
784
     * @param $order
785
     *
786
     * @return mixed
787
     */
788
    private function getTaxId($order)
789
    {
790
        foreach ((array)$order->get_meta_data() as $mdObject) {
791
            $data = $mdObject->get_data();
792
            if ($data['key'] == 'billing_cfpiva') {
793
                return $data['value'];
794
            }
795
        }
796
    }
797
798
    /**
799
     * @param null $exception
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $exception is correct as it would always require null to be passed?
Loading history...
800
     * @param null $message
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $message is correct as it would always require null to be passed?
Loading history...
801
     */
802
    private function insertLog($exception = null, $message = null)
803
    {
804
        global $wpdb;
805
        $this->checkDbLogTable();
806
        $logEntry     = new LogEntry();
807
        if ($exception instanceof \Exception) {
808
            $logEntry = $logEntry->error($exception);
809
        } else {
810
            $logEntry = $logEntry->info($message);
811
        }
812
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
813
        $wpdb->insert($tableName, array('log' => $logEntry->toJson()));
814
    }
815
    /**
816
     * Check if logs table exists
817
     */
818
    private function checkDbLogTable()
819
    {
820
        global $wpdb;
821
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
822
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
823
            $charset_collate = $wpdb->get_charset_collate();
824
            $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, 
825
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate";
826
            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
0 ignored issues
show
Bug introduced by
The constant ABSPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
827
            dbDelta($sql);
0 ignored issues
show
Bug introduced by
The function dbDelta was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

827
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
828
        }
829
        return;
830
    }
831
832
    /**
833
     * @param $product_id
834
     *
835
     * @return string
836
     */
837
    private function isPromoted($product_id)
838
    {
839
        $metaProduct = get_post_meta($product_id);
0 ignored issues
show
Bug introduced by
The function get_post_meta was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

839
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
840
        return ($metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
841
    }
842
843
    /**
844
     * @return int
845
     */
846
    private function getPromotedAmount()
847
    {
848
        global $woocommerce;
849
        $items = $woocommerce->cart->get_cart();
850
        $promotedAmount = 0;
851
        foreach ($items as $key => $item) {
852
            $promotedProduct = $this->isPromoted($item['product_id']);
853
            if ($promotedProduct == 'true') {
854
                $promotedAmount+=$item['line_total'];
855
            }
856
        }
857
858
        return $promotedAmount;
859
    }
860
}
861