Completed
Branch BUG/failed-transactions-link (66327d)
by
unknown
09:26 queued 27s
created
admin_pages/transactions/Transactions_Admin_Page.core.php 1 patch
Indentation   +2485 added lines, -2485 removed lines patch added patch discarded remove patch
@@ -14,2489 +14,2489 @@
 block discarded – undo
14 14
 class Transactions_Admin_Page extends EE_Admin_Page
15 15
 {
16 16
 
17
-    /**
18
-     * @var EE_Transaction
19
-     */
20
-    private $_transaction;
21
-
22
-    /**
23
-     * @var EE_Session
24
-     */
25
-    private $_session;
26
-
27
-    /**
28
-     * @var array $_txn_status
29
-     */
30
-    private static $_txn_status;
31
-
32
-    /**
33
-     * @var array $_pay_status
34
-     */
35
-    private static $_pay_status;
36
-
37
-    /**
38
-     * @var array $_existing_reg_payment_REG_IDs
39
-     */
40
-    protected $_existing_reg_payment_REG_IDs = null;
41
-
42
-
43
-    /**
44
-     * @Constructor
45
-     * @access public
46
-     * @param bool $routing
47
-     * @throws EE_Error
48
-     * @throws InvalidArgumentException
49
-     * @throws ReflectionException
50
-     * @throws InvalidDataTypeException
51
-     * @throws InvalidInterfaceException
52
-     */
53
-    public function __construct($routing = true)
54
-    {
55
-        parent::__construct($routing);
56
-    }
57
-
58
-
59
-    /**
60
-     *    _init_page_props
61
-     *
62
-     * @return void
63
-     */
64
-    protected function _init_page_props()
65
-    {
66
-        $this->page_slug = TXN_PG_SLUG;
67
-        $this->page_label = esc_html__('Transactions', 'event_espresso');
68
-        $this->_admin_base_url = TXN_ADMIN_URL;
69
-        $this->_admin_base_path = TXN_ADMIN;
70
-    }
71
-
72
-
73
-    /**
74
-     *    _ajax_hooks
75
-     *
76
-     * @return void
77
-     */
78
-    protected function _ajax_hooks()
79
-    {
80
-        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
81
-        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
82
-        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
83
-    }
84
-
85
-
86
-    /**
87
-     *    _define_page_props
88
-     *
89
-     * @return void
90
-     */
91
-    protected function _define_page_props()
92
-    {
93
-        $this->_admin_page_title = $this->page_label;
94
-        $this->_labels = array(
95
-            'buttons' => array(
96
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
97
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
98
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
99
-            ),
100
-        );
101
-    }
102
-
103
-
104
-    /**
105
-     *        grab url requests and route them
106
-     *
107
-     * @access private
108
-     * @return void
109
-     * @throws EE_Error
110
-     * @throws InvalidArgumentException
111
-     * @throws InvalidDataTypeException
112
-     * @throws InvalidInterfaceException
113
-     */
114
-    public function _set_page_routes()
115
-    {
116
-
117
-        $this->_set_transaction_status_array();
118
-
119
-        $txn_id = ! empty($this->_req_data['TXN_ID'])
120
-                  && ! is_array($this->_req_data['TXN_ID'])
121
-            ? $this->_req_data['TXN_ID']
122
-            : 0;
123
-
124
-        $this->_page_routes = array(
125
-
126
-            'default' => array(
127
-                'func'       => '_transactions_overview_list_table',
128
-                'capability' => 'ee_read_transactions',
129
-            ),
130
-
131
-            'view_transaction' => array(
132
-                'func'       => '_transaction_details',
133
-                'capability' => 'ee_read_transaction',
134
-                'obj_id'     => $txn_id,
135
-            ),
136
-
137
-            'send_payment_reminder' => array(
138
-                'func'       => '_send_payment_reminder',
139
-                'noheader'   => true,
140
-                'capability' => 'ee_send_message',
141
-            ),
142
-
143
-            'espresso_apply_payment' => array(
144
-                'func'       => 'apply_payments_or_refunds',
145
-                'noheader'   => true,
146
-                'capability' => 'ee_edit_payments',
147
-            ),
148
-
149
-            'espresso_apply_refund' => array(
150
-                'func'       => 'apply_payments_or_refunds',
151
-                'noheader'   => true,
152
-                'capability' => 'ee_edit_payments',
153
-            ),
154
-
155
-            'espresso_delete_payment' => array(
156
-                'func'       => 'delete_payment',
157
-                'noheader'   => true,
158
-                'capability' => 'ee_delete_payments',
159
-            ),
160
-
161
-        );
162
-    }
163
-
164
-
165
-    protected function _set_page_config()
166
-    {
167
-        $this->_page_config = array(
168
-            'default'          => array(
169
-                'nav'           => array(
170
-                    'label' => esc_html__('Overview', 'event_espresso'),
171
-                    'order' => 10,
172
-                ),
173
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
174
-                'help_tabs'     => array(
175
-                    'transactions_overview_help_tab'                       => array(
176
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
177
-                        'filename' => 'transactions_overview',
178
-                    ),
179
-                    'transactions_overview_table_column_headings_help_tab' => array(
180
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
181
-                        'filename' => 'transactions_overview_table_column_headings',
182
-                    ),
183
-                    'transactions_overview_views_filters_help_tab'         => array(
184
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
185
-                        'filename' => 'transactions_overview_views_filters_search',
186
-                    ),
187
-                ),
188
-                'help_tour'     => array('Transactions_Overview_Help_Tour'),
189
-                /**
190
-                 * commented out because currently we are not displaying tips for transaction list table status but this
191
-                 * may change in a later iteration so want to keep the code for then.
192
-                 */
193
-                // 'qtips' => array( 'Transactions_List_Table_Tips' ),
194
-                'require_nonce' => false,
195
-            ),
196
-            'view_transaction' => array(
197
-                'nav'       => array(
198
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
199
-                    'order'      => 5,
200
-                    'url'        => isset($this->_req_data['TXN_ID'])
201
-                        ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
202
-                        : $this->_admin_base_url,
203
-                    'persistent' => false,
204
-                ),
205
-                'help_tabs' => array(
206
-                    'transactions_view_transaction_help_tab'                                              => array(
207
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
208
-                        'filename' => 'transactions_view_transaction',
209
-                    ),
210
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
-                        'filename' => 'transactions_view_transaction_transaction_details_table',
213
-                    ),
214
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
-                        'filename' => 'transactions_view_transaction_attendees_registered',
217
-                    ),
218
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
221
-                    ),
222
-                ),
223
-                'qtips'     => array('Transaction_Details_Tips'),
224
-                'help_tour' => array('Transaction_Details_Help_Tour'),
225
-                'metaboxes' => array('_transaction_details_metaboxes'),
226
-
227
-                'require_nonce' => false,
228
-            ),
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * The below methods aren't used by this class currently
235
-     */
236
-    protected function _add_screen_options()
237
-    {
238
-        // noop
239
-    }
240
-
241
-    protected function _add_feature_pointers()
242
-    {
243
-        // noop
244
-    }
245
-
246
-    public function admin_init()
247
-    {
248
-        // IF a registration was JUST added via the admin...
249
-        if (isset(
250
-            $this->_req_data['redirect_from'],
251
-            $this->_req_data['EVT_ID'],
252
-            $this->_req_data['event_name']
253
-        )) {
254
-            // then set a cookie so that we can block any attempts to use
255
-            // the back button as a way to enter another registration.
256
-            setcookie(
257
-                'ee_registration_added',
258
-                $this->_req_data['EVT_ID'],
259
-                time() + WEEK_IN_SECONDS,
260
-                '/'
261
-            );
262
-            // and update the global
263
-            $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
-        }
265
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
-            'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
-            'event_espresso'
268
-        );
269
-        EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
270
-            'An error occurred! Please refresh the page and try again.',
271
-            'event_espresso'
272
-        );
273
-        EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
274
-        EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
275
-        EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
276
-        EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
277
-            'This transaction has been overpaid ! Payments Total',
278
-            'event_espresso'
279
-        );
280
-    }
281
-
282
-    public function admin_notices()
283
-    {
284
-        // noop
285
-    }
286
-
287
-    public function admin_footer_scripts()
288
-    {
289
-        // noop
290
-    }
291
-
292
-
293
-    /**
294
-     * _set_transaction_status_array
295
-     * sets list of transaction statuses
296
-     *
297
-     * @access private
298
-     * @return void
299
-     * @throws EE_Error
300
-     * @throws InvalidArgumentException
301
-     * @throws InvalidDataTypeException
302
-     * @throws InvalidInterfaceException
303
-     */
304
-    private function _set_transaction_status_array()
305
-    {
306
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
-    }
308
-
309
-
310
-    /**
311
-     * get_transaction_status_array
312
-     * return the transaction status array for wp_list_table
313
-     *
314
-     * @access public
315
-     * @return array
316
-     */
317
-    public function get_transaction_status_array()
318
-    {
319
-        return self::$_txn_status;
320
-    }
321
-
322
-
323
-    /**
324
-     *    get list of payment statuses
325
-     *
326
-     * @access private
327
-     * @return void
328
-     * @throws EE_Error
329
-     * @throws InvalidArgumentException
330
-     * @throws InvalidDataTypeException
331
-     * @throws InvalidInterfaceException
332
-     */
333
-    private function _get_payment_status_array()
334
-    {
335
-        self::$_pay_status = EEM_Payment::instance()->status_array(true);
336
-        $this->_template_args['payment_status'] = self::$_pay_status;
337
-    }
338
-
339
-
340
-    /**
341
-     *    _add_screen_options_default
342
-     *
343
-     * @access protected
344
-     * @return void
345
-     * @throws InvalidArgumentException
346
-     * @throws InvalidDataTypeException
347
-     * @throws InvalidInterfaceException
348
-     */
349
-    protected function _add_screen_options_default()
350
-    {
351
-        $this->_per_page_screen_option();
352
-    }
353
-
354
-
355
-    /**
356
-     * load_scripts_styles
357
-     *
358
-     * @access public
359
-     * @return void
360
-     */
361
-    public function load_scripts_styles()
362
-    {
363
-        // enqueue style
364
-        wp_register_style(
365
-            'espresso_txn',
366
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
367
-            array(),
368
-            EVENT_ESPRESSO_VERSION
369
-        );
370
-        wp_enqueue_style('espresso_txn');
371
-        // scripts
372
-        wp_register_script(
373
-            'espresso_txn',
374
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
375
-            array(
376
-                'ee_admin_js',
377
-                'ee-datepicker',
378
-                'jquery-ui-datepicker',
379
-                'jquery-ui-draggable',
380
-                'ee-dialog',
381
-                'ee-accounting',
382
-                'ee-serialize-full-array',
383
-            ),
384
-            EVENT_ESPRESSO_VERSION,
385
-            true
386
-        );
387
-        wp_enqueue_script('espresso_txn');
388
-    }
389
-
390
-
391
-    /**
392
-     *    load_scripts_styles_view_transaction
393
-     *
394
-     * @access public
395
-     * @return void
396
-     */
397
-    public function load_scripts_styles_view_transaction()
398
-    {
399
-        // styles
400
-        wp_enqueue_style('espresso-ui-theme');
401
-    }
402
-
403
-
404
-    /**
405
-     *    load_scripts_styles_default
406
-     *
407
-     * @access public
408
-     * @return void
409
-     */
410
-    public function load_scripts_styles_default()
411
-    {
412
-        // styles
413
-        wp_enqueue_style('espresso-ui-theme');
414
-    }
415
-
416
-
417
-    /**
418
-     *    _set_list_table_views_default
419
-     *
420
-     * @access protected
421
-     * @return void
422
-     */
423
-    protected function _set_list_table_views_default()
424
-    {
425
-        $this->_views = array(
426
-            'all'       => array(
427
-                'slug'  => 'all',
428
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
429
-                'count' => 0,
430
-            ),
431
-            'abandoned' => array(
432
-                'slug'  => 'abandoned',
433
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
434
-                'count' => 0,
435
-            ),
436
-        );
437
-        if (
438
-            /**
439
-             * Filters whether a link to the "Failed Transactions" list table
440
-             * appears on the Transactions Admin Page list table.
441
-             * List display can be turned back on via the following:
442
-             * add_filter(
443
-             *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed',
444
-             *     '__return_true'
445
-             * );
446
-             *
447
-             * @since $VID:$
448
-             * @param boolean                 $display_failed_txns_list
449
-             * @param Transactions_Admin_Page $this
450
-             */
451
-        apply_filters(
452
-            'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
453
-            false,
454
-            $this
455
-        )
456
-        ) {
457
-            $this->_views['failed'] = array(
458
-                'slug'  => 'failed',
459
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
460
-                'count' => 0,
461
-            );
462
-        }
463
-    }
464
-
465
-
466
-    /**
467
-     * _set_transaction_object
468
-     * This sets the _transaction property for the transaction details screen
469
-     *
470
-     * @access private
471
-     * @return void
472
-     * @throws EE_Error
473
-     * @throws InvalidArgumentException
474
-     * @throws RuntimeException
475
-     * @throws InvalidDataTypeException
476
-     * @throws InvalidInterfaceException
477
-     * @throws ReflectionException
478
-     */
479
-    private function _set_transaction_object()
480
-    {
481
-        if ($this->_transaction instanceof EE_Transaction) {
482
-            return;
483
-        } //get out we've already set the object
484
-
485
-        $TXN_ID = ! empty($this->_req_data['TXN_ID'])
486
-            ? absint($this->_req_data['TXN_ID'])
487
-            : false;
488
-
489
-        // get transaction object
490
-        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
491
-        $this->_session = $this->_transaction instanceof EE_Transaction
492
-            ? $this->_transaction->get('TXN_session_data')
493
-            : null;
494
-        if ($this->_transaction instanceof EE_Transaction) {
495
-            $this->_transaction->verify_abandoned_transaction_status();
496
-        }
497
-
498
-        if (! $this->_transaction instanceof EE_Transaction) {
499
-            $error_msg = sprintf(
500
-                esc_html__(
501
-                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
502
-                    'event_espresso'
503
-                ),
504
-                $TXN_ID
505
-            );
506
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
507
-        }
508
-    }
509
-
510
-
511
-    /**
512
-     *    _transaction_legend_items
513
-     *
514
-     * @access protected
515
-     * @return array
516
-     * @throws EE_Error
517
-     * @throws InvalidArgumentException
518
-     * @throws ReflectionException
519
-     * @throws InvalidDataTypeException
520
-     * @throws InvalidInterfaceException
521
-     */
522
-    protected function _transaction_legend_items()
523
-    {
524
-        EE_Registry::instance()->load_helper('MSG_Template');
525
-        $items = array();
526
-
527
-        if (EE_Registry::instance()->CAP->current_user_can(
528
-            'ee_read_global_messages',
529
-            'view_filtered_messages'
530
-        )) {
531
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
532
-            if (is_array($related_for_icon)
533
-                && isset($related_for_icon['css_class'], $related_for_icon['label'])
534
-            ) {
535
-                $items['view_related_messages'] = array(
536
-                    'class' => $related_for_icon['css_class'],
537
-                    'desc'  => $related_for_icon['label'],
538
-                );
539
-            }
540
-        }
541
-
542
-        $items = apply_filters(
543
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
544
-            array_merge(
545
-                $items,
546
-                array(
547
-                    'view_details'          => array(
548
-                        'class' => 'dashicons dashicons-cart',
549
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
550
-                    ),
551
-                    'view_invoice'          => array(
552
-                        'class' => 'dashicons dashicons-media-spreadsheet',
553
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
554
-                    ),
555
-                    'view_receipt'          => array(
556
-                        'class' => 'dashicons dashicons-media-default',
557
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
558
-                    ),
559
-                    'view_registration'     => array(
560
-                        'class' => 'dashicons dashicons-clipboard',
561
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
562
-                    ),
563
-                    'payment_overview_link' => array(
564
-                        'class' => 'dashicons dashicons-money',
565
-                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
566
-                    ),
567
-                )
568
-            )
569
-        );
570
-
571
-        if (EE_Registry::instance()->CAP->current_user_can(
572
-            'ee_send_message',
573
-            'espresso_transactions_send_payment_reminder'
574
-        )) {
575
-            if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
576
-                $items['send_payment_reminder'] = array(
577
-                    'class' => 'dashicons dashicons-email-alt',
578
-                    'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
579
-                );
580
-            } else {
581
-                $items['blank*'] = array(
582
-                    'class' => '',
583
-                    'desc'  => '',
584
-                );
585
-            }
586
-        } else {
587
-            $items['blank*'] = array(
588
-                'class' => '',
589
-                'desc'  => '',
590
-            );
591
-        }
592
-        $more_items = apply_filters(
593
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
594
-            array(
595
-                'overpaid'   => array(
596
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
597
-                    'desc'  => EEH_Template::pretty_status(
598
-                        EEM_Transaction::overpaid_status_code,
599
-                        false,
600
-                        'sentence'
601
-                    ),
602
-                ),
603
-                'complete'   => array(
604
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
605
-                    'desc'  => EEH_Template::pretty_status(
606
-                        EEM_Transaction::complete_status_code,
607
-                        false,
608
-                        'sentence'
609
-                    ),
610
-                ),
611
-                'incomplete' => array(
612
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
613
-                    'desc'  => EEH_Template::pretty_status(
614
-                        EEM_Transaction::incomplete_status_code,
615
-                        false,
616
-                        'sentence'
617
-                    ),
618
-                ),
619
-                'abandoned'  => array(
620
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
621
-                    'desc'  => EEH_Template::pretty_status(
622
-                        EEM_Transaction::abandoned_status_code,
623
-                        false,
624
-                        'sentence'
625
-                    ),
626
-                ),
627
-                'failed'     => array(
628
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
629
-                    'desc'  => EEH_Template::pretty_status(
630
-                        EEM_Transaction::failed_status_code,
631
-                        false,
632
-                        'sentence'
633
-                    ),
634
-                ),
635
-            )
636
-        );
637
-
638
-        return array_merge($items, $more_items);
639
-    }
640
-
641
-
642
-    /**
643
-     *    _transactions_overview_list_table
644
-     *
645
-     * @access protected
646
-     * @return void
647
-     * @throws DomainException
648
-     * @throws EE_Error
649
-     * @throws InvalidArgumentException
650
-     * @throws InvalidDataTypeException
651
-     * @throws InvalidInterfaceException
652
-     * @throws ReflectionException
653
-     */
654
-    protected function _transactions_overview_list_table()
655
-    {
656
-        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
657
-        $event = isset($this->_req_data['EVT_ID'])
658
-            ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
659
-            : null;
660
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
661
-            ? sprintf(
662
-                esc_html__(
663
-                    '%sViewing Transactions for the Event: %s%s',
664
-                    'event_espresso'
665
-                ),
666
-                '<h3>',
667
-                '<a href="'
668
-                . EE_Admin_Page::add_query_args_and_nonce(
669
-                    array('action' => 'edit', 'post' => $event->ID()),
670
-                    EVENTS_ADMIN_URL
671
-                )
672
-                . '" title="'
673
-                . esc_attr__(
674
-                    'Click to Edit event',
675
-                    'event_espresso'
676
-                )
677
-                . '">' . $event->get('EVT_name') . '</a>',
678
-                '</h3>'
679
-            )
680
-            : '';
681
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
682
-        $this->display_admin_list_table_page_with_no_sidebar();
683
-    }
684
-
685
-
686
-    /**
687
-     *    _transaction_details
688
-     * generates HTML for the View Transaction Details Admin page
689
-     *
690
-     * @access protected
691
-     * @return void
692
-     * @throws DomainException
693
-     * @throws EE_Error
694
-     * @throws InvalidArgumentException
695
-     * @throws InvalidDataTypeException
696
-     * @throws InvalidInterfaceException
697
-     * @throws RuntimeException
698
-     * @throws ReflectionException
699
-     */
700
-    protected function _transaction_details()
701
-    {
702
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
703
-
704
-        $this->_set_transaction_status_array();
705
-
706
-        $this->_template_args = array();
707
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
708
-
709
-        $this->_set_transaction_object();
710
-
711
-        if (! $this->_transaction instanceof EE_Transaction) {
712
-            return;
713
-        }
714
-        $primary_registration = $this->_transaction->primary_registration();
715
-        $attendee = $primary_registration instanceof EE_Registration
716
-            ? $primary_registration->attendee()
717
-            : null;
718
-
719
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
720
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
721
-
722
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
723
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
724
-
725
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
726
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
727
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
728
-
729
-        $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
730
-        $this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
731
-
732
-        $amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
733
-        $this->_template_args['amount_due'] = EEH_Template::format_currency(
734
-            $amount_due,
735
-            true
736
-        );
737
-        if (EE_Registry::instance()->CFG->currency->sign_b4) {
738
-            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
739
-                                                  . $this->_template_args['amount_due'];
740
-        } else {
741
-            $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
742
-        }
743
-        $this->_template_args['amount_due_class'] = '';
744
-
745
-        if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
746
-            // paid in full
747
-            $this->_template_args['amount_due'] = false;
748
-        } elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
749
-            // overpaid
750
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
751
-        } elseif ($this->_transaction->get('TXN_total') > 0
752
-                  && $this->_transaction->get('TXN_paid') > 0
753
-        ) {
754
-            // monies owing
755
-            $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
756
-        } elseif ($this->_transaction->get('TXN_total') > 0
757
-                  && $this->_transaction->get('TXN_paid') == 0
758
-        ) {
759
-            // no payments made yet
760
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
761
-        } elseif ($this->_transaction->get('TXN_total') == 0) {
762
-            // free event
763
-            $this->_template_args['amount_due'] = false;
764
-        }
765
-
766
-        $payment_method = $this->_transaction->payment_method();
767
-
768
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
769
-            ? $payment_method->admin_name()
770
-            : esc_html__('Unknown', 'event_espresso');
771
-
772
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
773
-        // link back to overview
774
-        $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
775
-            ? $_SERVER['HTTP_REFERER']
776
-            : TXN_ADMIN_URL;
777
-
778
-
779
-        // next link
780
-        $next_txn = $this->_transaction->next(
781
-            null,
782
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
783
-            'TXN_ID'
784
-        );
785
-        $this->_template_args['next_transaction'] = $next_txn
786
-            ? $this->_next_link(
787
-                EE_Admin_Page::add_query_args_and_nonce(
788
-                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
789
-                    TXN_ADMIN_URL
790
-                ),
791
-                'dashicons dashicons-arrow-right ee-icon-size-22'
792
-            )
793
-            : '';
794
-        // previous link
795
-        $previous_txn = $this->_transaction->previous(
796
-            null,
797
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
798
-            'TXN_ID'
799
-        );
800
-        $this->_template_args['previous_transaction'] = $previous_txn
801
-            ? $this->_previous_link(
802
-                EE_Admin_Page::add_query_args_and_nonce(
803
-                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
804
-                    TXN_ADMIN_URL
805
-                ),
806
-                'dashicons dashicons-arrow-left ee-icon-size-22'
807
-            )
808
-            : '';
809
-
810
-        // were we just redirected here after adding a new registration ???
811
-        if (isset(
812
-            $this->_req_data['redirect_from'],
813
-            $this->_req_data['EVT_ID'],
814
-            $this->_req_data['event_name']
815
-        )) {
816
-            if (EE_Registry::instance()->CAP->current_user_can(
817
-                'ee_edit_registrations',
818
-                'espresso_registrations_new_registration',
819
-                $this->_req_data['EVT_ID']
820
-            )) {
821
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
822
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
823
-                    array(
824
-                        'page'     => 'espresso_registrations',
825
-                        'action'   => 'new_registration',
826
-                        'return'   => 'default',
827
-                        'TXN_ID'   => $this->_transaction->ID(),
828
-                        'event_id' => $this->_req_data['EVT_ID'],
829
-                    ),
830
-                    REG_ADMIN_URL
831
-                );
832
-                $this->_admin_page_title .= '">';
833
-
834
-                $this->_admin_page_title .= sprintf(
835
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
836
-                    htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
837
-                );
838
-                $this->_admin_page_title .= '</a>';
839
-            }
840
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
841
-        }
842
-        // grab messages at the last second
843
-        $this->_template_args['notices'] = EE_Error::get_notices();
844
-        // path to template
845
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
846
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
847
-            $template_path,
848
-            $this->_template_args,
849
-            true
850
-        );
851
-
852
-        // the details template wrapper
853
-        $this->display_admin_page_with_sidebar();
854
-    }
855
-
856
-
857
-    /**
858
-     *        _transaction_details_metaboxes
859
-     *
860
-     * @access protected
861
-     * @return void
862
-     * @throws EE_Error
863
-     * @throws InvalidArgumentException
864
-     * @throws InvalidDataTypeException
865
-     * @throws InvalidInterfaceException
866
-     * @throws RuntimeException
867
-     * @throws ReflectionException
868
-     */
869
-    protected function _transaction_details_metaboxes()
870
-    {
871
-
872
-        $this->_set_transaction_object();
873
-
874
-        if (! $this->_transaction instanceof EE_Transaction) {
875
-            return;
876
-        }
877
-        add_meta_box(
878
-            'edit-txn-details-mbox',
879
-            esc_html__('Transaction Details', 'event_espresso'),
880
-            array($this, 'txn_details_meta_box'),
881
-            $this->_wp_page_slug,
882
-            'normal',
883
-            'high'
884
-        );
885
-        add_meta_box(
886
-            'edit-txn-attendees-mbox',
887
-            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
888
-            array($this, 'txn_attendees_meta_box'),
889
-            $this->_wp_page_slug,
890
-            'normal',
891
-            'high',
892
-            array('TXN_ID' => $this->_transaction->ID())
893
-        );
894
-        add_meta_box(
895
-            'edit-txn-registrant-mbox',
896
-            esc_html__('Primary Contact', 'event_espresso'),
897
-            array($this, 'txn_registrant_side_meta_box'),
898
-            $this->_wp_page_slug,
899
-            'side',
900
-            'high'
901
-        );
902
-        add_meta_box(
903
-            'edit-txn-billing-info-mbox',
904
-            esc_html__('Billing Information', 'event_espresso'),
905
-            array($this, 'txn_billing_info_side_meta_box'),
906
-            $this->_wp_page_slug,
907
-            'side',
908
-            'high'
909
-        );
910
-    }
911
-
912
-
913
-    /**
914
-     * Callback for transaction actions metabox.
915
-     *
916
-     * @param EE_Transaction|null $transaction
917
-     * @throws DomainException
918
-     * @throws EE_Error
919
-     * @throws InvalidArgumentException
920
-     * @throws InvalidDataTypeException
921
-     * @throws InvalidInterfaceException
922
-     * @throws ReflectionException
923
-     * @throws RuntimeException
924
-     */
925
-    public function getActionButtons(EE_Transaction $transaction = null)
926
-    {
927
-        $content = '';
928
-        $actions = array();
929
-        if (! $transaction instanceof EE_Transaction) {
930
-            return $content;
931
-        }
932
-        /** @var EE_Registration $primary_registration */
933
-        $primary_registration = $transaction->primary_registration();
934
-        $attendee = $primary_registration instanceof EE_Registration
935
-            ? $primary_registration->attendee()
936
-            : null;
937
-
938
-        if ($attendee instanceof EE_Attendee
939
-            && EE_Registry::instance()->CAP->current_user_can(
940
-                'ee_send_message',
941
-                'espresso_transactions_send_payment_reminder'
942
-            )
943
-        ) {
944
-            $actions['payment_reminder'] =
945
-                EEH_MSG_Template::is_mt_active('payment_reminder')
946
-                && $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
947
-                && $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
948
-                    ? EEH_Template::get_button_or_link(
949
-                        EE_Admin_Page::add_query_args_and_nonce(
950
-                            array(
951
-                                'action'      => 'send_payment_reminder',
952
-                                'TXN_ID'      => $this->_transaction->ID(),
953
-                                'redirect_to' => 'view_transaction',
954
-                            ),
955
-                            TXN_ADMIN_URL
956
-                        ),
957
-                        esc_html__(' Send Payment Reminder', 'event_espresso'),
958
-                        'button secondary-button',
959
-                        'dashicons dashicons-email-alt'
960
-                    )
961
-                    : '';
962
-        }
963
-
964
-        if ($primary_registration instanceof EE_Registration
965
-            && EEH_MSG_Template::is_mt_active('receipt')
966
-        ) {
967
-            $actions['receipt'] = EEH_Template::get_button_or_link(
968
-                $primary_registration->receipt_url(),
969
-                esc_html__('View Receipt', 'event_espresso'),
970
-                'button secondary-button',
971
-                'dashicons dashicons-media-default'
972
-            );
973
-        }
974
-
975
-        if ($primary_registration instanceof EE_Registration
976
-            && EEH_MSG_Template::is_mt_active('invoice')
977
-        ) {
978
-            $actions['invoice'] = EEH_Template::get_button_or_link(
979
-                $primary_registration->invoice_url(),
980
-                esc_html__('View Invoice', 'event_espresso'),
981
-                'button secondary-button',
982
-                'dashicons dashicons-media-spreadsheet'
983
-            );
984
-        }
985
-        $actions = array_filter(
986
-            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
987
-        );
988
-        if ($actions) {
989
-            $content = '<ul>';
990
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
991
-            $content .= '</uL>';
992
-        }
993
-        return $content;
994
-    }
995
-
996
-
997
-    /**
998
-     * txn_details_meta_box
999
-     * generates HTML for the Transaction main meta box
1000
-     *
1001
-     * @return void
1002
-     * @throws DomainException
1003
-     * @throws EE_Error
1004
-     * @throws InvalidArgumentException
1005
-     * @throws InvalidDataTypeException
1006
-     * @throws InvalidInterfaceException
1007
-     * @throws RuntimeException
1008
-     * @throws ReflectionException
1009
-     */
1010
-    public function txn_details_meta_box()
1011
-    {
1012
-        $this->_set_transaction_object();
1013
-        $this->_template_args['TXN_ID'] = $this->_transaction->ID();
1014
-        $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1015
-            ? $this->_transaction->primary_registration()->attendee()
1016
-            : null;
1017
-        $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1018
-            'ee_edit_payments',
1019
-            'apply_payment_or_refund_from_registration_details'
1020
-        );
1021
-        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1022
-            'ee_delete_payments',
1023
-            'delete_payment_from_registration_details'
1024
-        );
1025
-
1026
-        // get line table
1027
-        EEH_Autoloader::register_line_item_display_autoloaders();
1028
-        $Line_Item_Display = new EE_Line_Item_Display(
1029
-            'admin_table',
1030
-            'EE_Admin_Table_Line_Item_Display_Strategy'
1031
-        );
1032
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1033
-            $this->_transaction->total_line_item()
1034
-        );
1035
-        $this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration')
1036
-                                                               ->get('REG_code');
1037
-
1038
-        // process taxes
1039
-        $taxes = $this->_transaction->get_many_related(
1040
-            'Line_Item',
1041
-            array(array('LIN_type' => EEM_Line_Item::type_tax))
1042
-        );
1043
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1044
-
1045
-        $this->_template_args['grand_total'] = EEH_Template::format_currency(
1046
-            $this->_transaction->get('TXN_total'),
1047
-            false,
1048
-            false
1049
-        );
1050
-        $this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1051
-        $this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID');
1052
-
1053
-        // process payment details
1054
-        $payments = $this->_transaction->get_many_related('Payment');
1055
-        if (! empty($payments)) {
1056
-            $this->_template_args['payments'] = $payments;
1057
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1058
-        } else {
1059
-            $this->_template_args['payments'] = false;
1060
-            $this->_template_args['existing_reg_payments'] = array();
1061
-        }
1062
-
1063
-        $this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1064
-        $this->_template_args['delete_payment_url'] = add_query_arg(
1065
-            array('action' => 'espresso_delete_payment'),
1066
-            TXN_ADMIN_URL
1067
-        );
1068
-
1069
-        if (isset($txn_details['invoice_number'])) {
1070
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1071
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1072
-                'Invoice Number',
1073
-                'event_espresso'
1074
-            );
1075
-        }
1076
-
1077
-        $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1078
-            ->get_first_related('Registration')
1079
-            ->get('REG_session');
1080
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1081
-            'Registration Session',
1082
-            'event_espresso'
1083
-        );
1084
-
1085
-        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1086
-            ? $this->_session['ip_address']
1087
-            : '';
1088
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1089
-            'Transaction placed from IP',
1090
-            'event_espresso'
1091
-        );
1092
-
1093
-        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1094
-            ? $this->_session['user_agent']
1095
-            : '';
1096
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1097
-            'Registrant User Agent',
1098
-            'event_espresso'
1099
-        );
1100
-
1101
-        $reg_steps = '<ul>';
1102
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1103
-            if ($reg_step_status === true) {
1104
-                $reg_steps .= '<li style="color:#70cc50">'
1105
-                              . sprintf(
1106
-                                  esc_html__('%1$s : Completed', 'event_espresso'),
1107
-                                  ucwords(str_replace('_', ' ', $reg_step))
1108
-                              )
1109
-                              . '</li>';
1110
-            } elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1111
-                $reg_steps .= '<li style="color:#2EA2CC">'
1112
-                              . sprintf(
1113
-                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1114
-                                  ucwords(str_replace('_', ' ', $reg_step)),
1115
-                                  date(
1116
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1117
-                                      ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1118
-                                  )
1119
-                              )
1120
-                              . '</li>';
1121
-            } else {
1122
-                $reg_steps .= '<li style="color:#E76700">'
1123
-                              . sprintf(
1124
-                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1125
-                                  ucwords(str_replace('_', ' ', $reg_step))
1126
-                              )
1127
-                              . '</li>';
1128
-            }
1129
-        }
1130
-        $reg_steps .= '</ul>';
1131
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1132
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1133
-            'Registration Step Progress',
1134
-            'event_espresso'
1135
-        );
1136
-
1137
-
1138
-        $this->_get_registrations_to_apply_payment_to();
1139
-        $this->_get_payment_methods($payments);
1140
-        $this->_get_payment_status_array();
1141
-        $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1142
-
1143
-        $this->_template_args['transaction_form_url'] = add_query_arg(
1144
-            array(
1145
-                'action'  => 'edit_transaction',
1146
-                'process' => 'transaction',
1147
-            ),
1148
-            TXN_ADMIN_URL
1149
-        );
1150
-        $this->_template_args['apply_payment_form_url'] = add_query_arg(
1151
-            array(
1152
-                'page'   => 'espresso_transactions',
1153
-                'action' => 'espresso_apply_payment',
1154
-            ),
1155
-            WP_AJAX_URL
1156
-        );
1157
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(
1158
-            array(
1159
-                'page'   => 'espresso_transactions',
1160
-                'action' => 'espresso_delete_payment',
1161
-            ),
1162
-            WP_AJAX_URL
1163
-        );
1164
-
1165
-        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1166
-
1167
-        // 'espresso_delete_payment_nonce'
1168
-
1169
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1170
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1171
-    }
1172
-
1173
-
1174
-    /**
1175
-     * _get_registration_payment_IDs
1176
-     *    generates an array of Payment IDs and their corresponding Registration IDs
1177
-     *
1178
-     * @access protected
1179
-     * @param EE_Payment[] $payments
1180
-     * @return array
1181
-     * @throws EE_Error
1182
-     * @throws InvalidArgumentException
1183
-     * @throws InvalidDataTypeException
1184
-     * @throws InvalidInterfaceException
1185
-     * @throws ReflectionException
1186
-     */
1187
-    protected function _get_registration_payment_IDs($payments = array())
1188
-    {
1189
-        $existing_reg_payments = array();
1190
-        // get all reg payments for these payments
1191
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(
1192
-            array(
1193
-                array(
1194
-                    'PAY_ID' => array(
1195
-                        'IN',
1196
-                        array_keys($payments),
1197
-                    ),
1198
-                ),
1199
-            )
1200
-        );
1201
-        if (! empty($reg_payments)) {
1202
-            foreach ($payments as $payment) {
1203
-                if (! $payment instanceof EE_Payment) {
1204
-                    continue;
1205
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1206
-                    $existing_reg_payments[ $payment->ID() ] = array();
1207
-                }
1208
-                foreach ($reg_payments as $reg_payment) {
1209
-                    if ($reg_payment instanceof EE_Registration_Payment
1210
-                        && $reg_payment->payment_ID() === $payment->ID()
1211
-                    ) {
1212
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1213
-                    }
1214
-                }
1215
-            }
1216
-        }
1217
-
1218
-        return $existing_reg_payments;
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * _get_registrations_to_apply_payment_to
1224
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1225
-     * which allows the admin to only apply the payment to the specific registrations
1226
-     *
1227
-     * @access protected
1228
-     * @return void
1229
-     * @throws \EE_Error
1230
-     */
1231
-    protected function _get_registrations_to_apply_payment_to()
1232
-    {
1233
-        // we want any registration with an active status (ie: not deleted or cancelled)
1234
-        $query_params = array(
1235
-            array(
1236
-                'STS_ID' => array(
1237
-                    'IN',
1238
-                    array(
1239
-                        EEM_Registration::status_id_approved,
1240
-                        EEM_Registration::status_id_pending_payment,
1241
-                        EEM_Registration::status_id_not_approved,
1242
-                    ),
1243
-                ),
1244
-            ),
1245
-        );
1246
-        $registrations_to_apply_payment_to = EEH_HTML::br()
1247
-                                             . EEH_HTML::div(
1248
-                                                 '',
1249
-                                                 'txn-admin-apply-payment-to-registrations-dv',
1250
-                                                 '',
1251
-                                                 'clear: both; margin: 1.5em 0 0; display: none;'
1252
-                                             );
1253
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1254
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1255
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1256
-            EEH_HTML::tr(
1257
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1258
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1259
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1260
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1261
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1262
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1263
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1264
-            )
1265
-        );
1266
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1267
-        // get registrations for TXN
1268
-        $registrations = $this->_transaction->registrations($query_params);
1269
-        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1270
-        foreach ($registrations as $registration) {
1271
-            if ($registration instanceof EE_Registration) {
1272
-                $attendee_name = $registration->attendee() instanceof EE_Attendee
1273
-                    ? $registration->attendee()->full_name()
1274
-                    : esc_html__('Unknown Attendee', 'event_espresso');
1275
-                $owing = $registration->final_price() - $registration->paid();
1276
-                $taxable = $registration->ticket()->taxable()
1277
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1278
-                    : '';
1279
-                $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1280
-                    ? ' checked="checked"'
1281
-                    : '';
1282
-                $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1283
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1284
-                    EEH_HTML::td($registration->ID()) .
1285
-                    EEH_HTML::td($attendee_name) .
1286
-                    EEH_HTML::td(
1287
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1288
-                    ) .
1289
-                    EEH_HTML::td($registration->event_name()) .
1290
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1291
-                    EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1292
-                    EEH_HTML::td(
1293
-                        '<input type="checkbox" value="' . $registration->ID()
1294
-                        . '" name="txn_admin_payment[registrations]"'
1295
-                        . $checked . $disabled . '>',
1296
-                        '',
1297
-                        'jst-cntr'
1298
-                    ),
1299
-                    'apply-payment-registration-row-' . $registration->ID()
1300
-                );
1301
-            }
1302
-        }
1303
-        $registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1304
-        $registrations_to_apply_payment_to .= EEH_HTML::tablex();
1305
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1306
-        $registrations_to_apply_payment_to .= EEH_HTML::p(
1307
-            esc_html__(
1308
-                'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1309
-                'event_espresso'
1310
-            ),
1311
-            '',
1312
-            'clear description'
1313
-        );
1314
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1315
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * _get_reg_status_selection
1321
-     *
1322
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1323
-     *         instead of events.
1324
-     * @access protected
1325
-     * @return void
1326
-     * @throws EE_Error
1327
-     */
1328
-    protected function _get_reg_status_selection()
1329
-    {
1330
-        // first get all possible statuses
1331
-        $statuses = EEM_Registration::reg_status_array(array(), true);
1332
-        // let's add a "don't change" option.
1333
-        $status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1334
-        $status_array = array_merge($status_array, $statuses);
1335
-        $this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1336
-            'txn_reg_status_change[reg_status]',
1337
-            $status_array,
1338
-            'NAN',
1339
-            'id="txn-admin-payment-reg-status-inp"',
1340
-            'txn-reg-status-change-reg-status'
1341
-        );
1342
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1343
-            'delete_txn_reg_status_change[reg_status]',
1344
-            $status_array,
1345
-            'NAN',
1346
-            'delete-txn-admin-payment-reg-status-inp',
1347
-            'delete-txn-reg-status-change-reg-status'
1348
-        );
1349
-    }
1350
-
1351
-
1352
-    /**
1353
-     *    _get_payment_methods
1354
-     * Gets all the payment methods available generally, or the ones that are already
1355
-     * selected on these payments (in case their payment methods are no longer active).
1356
-     * Has the side-effect of updating the template args' payment_methods item
1357
-     *
1358
-     * @access private
1359
-     * @param EE_Payment[] to show on this page
1360
-     * @return void
1361
-     * @throws EE_Error
1362
-     * @throws InvalidArgumentException
1363
-     * @throws InvalidDataTypeException
1364
-     * @throws InvalidInterfaceException
1365
-     * @throws ReflectionException
1366
-     */
1367
-    private function _get_payment_methods($payments = array())
1368
-    {
1369
-        $payment_methods_of_payments = array();
1370
-        foreach ($payments as $payment) {
1371
-            if ($payment instanceof EE_Payment) {
1372
-                $payment_methods_of_payments[] = $payment->get('PMD_ID');
1373
-            }
1374
-        }
1375
-        if ($payment_methods_of_payments) {
1376
-            $query_args = array(
1377
-                array(
1378
-                    'OR*payment_method_for_payment' => array(
1379
-                        'PMD_ID'    => array('IN', $payment_methods_of_payments),
1380
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1381
-                    ),
1382
-                ),
1383
-            );
1384
-        } else {
1385
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1386
-        }
1387
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1388
-    }
1389
-
1390
-
1391
-    /**
1392
-     * txn_attendees_meta_box
1393
-     *    generates HTML for the Attendees Transaction main meta box
1394
-     *
1395
-     * @access public
1396
-     * @param WP_Post $post
1397
-     * @param array   $metabox
1398
-     * @return void
1399
-     * @throws DomainException
1400
-     * @throws EE_Error
1401
-     */
1402
-    public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1403
-    {
1404
-
1405
-        /** @noinspection NonSecureExtractUsageInspection */
1406
-        extract($metabox['args']);
1407
-        $this->_template_args['post'] = $post;
1408
-        $this->_template_args['event_attendees'] = array();
1409
-        // process items in cart
1410
-        $line_items = $this->_transaction->get_many_related(
1411
-            'Line_Item',
1412
-            array(array('LIN_type' => 'line-item'))
1413
-        );
1414
-        if (! empty($line_items)) {
1415
-            foreach ($line_items as $item) {
1416
-                if ($item instanceof EE_Line_Item) {
1417
-                    switch ($item->OBJ_type()) {
1418
-                        case 'Event':
1419
-                            break;
1420
-                        case 'Ticket':
1421
-                            $ticket = $item->ticket();
1422
-                            // right now we're only handling tickets here.
1423
-                            // Cause its expected that only tickets will have attendees right?
1424
-                            if (! $ticket instanceof EE_Ticket) {
1425
-                                continue;
1426
-                            }
1427
-                            try {
1428
-                                $event_name = $ticket->get_event_name();
1429
-                            } catch (Exception $e) {
1430
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1431
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1432
-                            }
1433
-                            $event_name .= ' - ' . $item->get('LIN_name');
1434
-                            $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1435
-                            // now get all of the registrations for this transaction that use this ticket
1436
-                            $registrations = $ticket->get_many_related(
1437
-                                'Registration',
1438
-                                array(array('TXN_ID' => $this->_transaction->ID()))
1439
-                            );
1440
-                            foreach ($registrations as $registration) {
1441
-                                if (! $registration instanceof EE_Registration) {
1442
-                                    continue;
1443
-                                }
1444
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1445
-                                    = $registration->status_ID();
1446
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1447
-                                    = $registration->count();
1448
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1449
-                                    = $event_name;
1450
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1451
-                                    = $ticket_price;
1452
-                                // attendee info
1453
-                                $attendee = $registration->get_first_related('Attendee');
1454
-                                if ($attendee instanceof EE_Attendee) {
1455
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1456
-                                        = $attendee->ID();
1457
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1458
-                                        = $attendee->full_name();
1459
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1460
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1461
-                                          . esc_html__(
1462
-                                              ' Event',
1463
-                                              'event_espresso'
1464
-                                          )
1465
-                                          . '">' . $attendee->email() . '</a>';
1466
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1467
-                                        = EEH_Address::format($attendee, 'inline', false, false);
1468
-                                } else {
1469
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1470
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1471
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1472
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1473
-                                }
1474
-                            }
1475
-                            break;
1476
-                    }
1477
-                }
1478
-            }
1479
-
1480
-            $this->_template_args['transaction_form_url'] = add_query_arg(
1481
-                array(
1482
-                    'action'  => 'edit_transaction',
1483
-                    'process' => 'attendees',
1484
-                ),
1485
-                TXN_ADMIN_URL
1486
-            );
1487
-            echo EEH_Template::display_template(
1488
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1489
-                $this->_template_args,
1490
-                true
1491
-            );
1492
-        } else {
1493
-            echo sprintf(
1494
-                esc_html__(
1495
-                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1496
-                    'event_espresso'
1497
-                ),
1498
-                '<p class="important-notice">',
1499
-                '</p>'
1500
-            );
1501
-        }
1502
-    }
1503
-
1504
-
1505
-    /**
1506
-     * txn_registrant_side_meta_box
1507
-     * generates HTML for the Edit Transaction side meta box
1508
-     *
1509
-     * @access public
1510
-     * @return void
1511
-     * @throws DomainException
1512
-     * @throws EE_Error
1513
-     * @throws InvalidArgumentException
1514
-     * @throws InvalidDataTypeException
1515
-     * @throws InvalidInterfaceException
1516
-     * @throws ReflectionException
1517
-     */
1518
-    public function txn_registrant_side_meta_box()
1519
-    {
1520
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1521
-            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1522
-            : null;
1523
-        if (! $primary_att instanceof EE_Attendee) {
1524
-            $this->_template_args['no_attendee_message'] = esc_html__(
1525
-                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1526
-                'event_espresso'
1527
-            );
1528
-            $primary_att = EEM_Attendee::instance()->create_default_object();
1529
-        }
1530
-        $this->_template_args['ATT_ID'] = $primary_att->ID();
1531
-        $this->_template_args['prime_reg_fname'] = $primary_att->fname();
1532
-        $this->_template_args['prime_reg_lname'] = $primary_att->lname();
1533
-        $this->_template_args['prime_reg_email'] = $primary_att->email();
1534
-        $this->_template_args['prime_reg_phone'] = $primary_att->phone();
1535
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1536
-            array(
1537
-                'action' => 'edit_attendee',
1538
-                'post'   => $primary_att->ID(),
1539
-            ),
1540
-            REG_ADMIN_URL
1541
-        );
1542
-        // get formatted address for registrant
1543
-        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1544
-        echo EEH_Template::display_template(
1545
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1546
-            $this->_template_args,
1547
-            true
1548
-        );
1549
-    }
1550
-
1551
-
1552
-    /**
1553
-     * txn_billing_info_side_meta_box
1554
-     *    generates HTML for the Edit Transaction side meta box
1555
-     *
1556
-     * @access public
1557
-     * @return void
1558
-     * @throws DomainException
1559
-     * @throws EE_Error
1560
-     */
1561
-    public function txn_billing_info_side_meta_box()
1562
-    {
1563
-
1564
-        $this->_template_args['billing_form'] = $this->_transaction->billing_info();
1565
-        $this->_template_args['billing_form_url'] = add_query_arg(
1566
-            array('action' => 'edit_transaction', 'process' => 'billing'),
1567
-            TXN_ADMIN_URL
1568
-        );
1569
-
1570
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1571
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1572
-    }
1573
-
1574
-
1575
-    /**
1576
-     * apply_payments_or_refunds
1577
-     *    registers a payment or refund made towards a transaction
1578
-     *
1579
-     * @access public
1580
-     * @return void
1581
-     * @throws EE_Error
1582
-     * @throws InvalidArgumentException
1583
-     * @throws ReflectionException
1584
-     * @throws RuntimeException
1585
-     * @throws InvalidDataTypeException
1586
-     * @throws InvalidInterfaceException
1587
-     */
1588
-    public function apply_payments_or_refunds()
1589
-    {
1590
-        $json_response_data = array('return_data' => false);
1591
-        $valid_data = $this->_validate_payment_request_data();
1592
-        $has_access = EE_Registry::instance()->CAP->current_user_can(
1593
-            'ee_edit_payments',
1594
-            'apply_payment_or_refund_from_registration_details'
1595
-        );
1596
-        if (! empty($valid_data) && $has_access) {
1597
-            $PAY_ID = $valid_data['PAY_ID'];
1598
-            // save  the new payment
1599
-            $payment = $this->_create_payment_from_request_data($valid_data);
1600
-            // get the TXN for this payment
1601
-            $transaction = $payment->transaction();
1602
-            // verify transaction
1603
-            if ($transaction instanceof EE_Transaction) {
1604
-                // calculate_total_payments_and_update_status
1605
-                $this->_process_transaction_payments($transaction);
1606
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1607
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1608
-                // apply payment to registrations (if applicable)
1609
-                if (! empty($REG_IDs)) {
1610
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1611
-                    $this->_maybe_send_notifications();
1612
-                    // now process status changes for the same registrations
1613
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1614
-                }
1615
-                $this->_maybe_send_notifications($payment);
1616
-                // prepare to render page
1617
-                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1618
-                do_action(
1619
-                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1620
-                    $transaction,
1621
-                    $payment
1622
-                );
1623
-            } else {
1624
-                EE_Error::add_error(
1625
-                    esc_html__(
1626
-                        'A valid Transaction for this payment could not be retrieved.',
1627
-                        'event_espresso'
1628
-                    ),
1629
-                    __FILE__,
1630
-                    __FUNCTION__,
1631
-                    __LINE__
1632
-                );
1633
-            }
1634
-        } else {
1635
-            if ($has_access) {
1636
-                EE_Error::add_error(
1637
-                    esc_html__(
1638
-                        'The payment form data could not be processed. Please try again.',
1639
-                        'event_espresso'
1640
-                    ),
1641
-                    __FILE__,
1642
-                    __FUNCTION__,
1643
-                    __LINE__
1644
-                );
1645
-            } else {
1646
-                EE_Error::add_error(
1647
-                    esc_html__(
1648
-                        'You do not have access to apply payments or refunds to a registration.',
1649
-                        'event_espresso'
1650
-                    ),
1651
-                    __FILE__,
1652
-                    __FUNCTION__,
1653
-                    __LINE__
1654
-                );
1655
-            }
1656
-        }
1657
-        $notices = EE_Error::get_notices(
1658
-            false,
1659
-            false,
1660
-            false
1661
-        );
1662
-        $this->_template_args = array(
1663
-            'data'    => $json_response_data,
1664
-            'error'   => $notices['errors'],
1665
-            'success' => $notices['success'],
1666
-        );
1667
-        $this->_return_json();
1668
-    }
1669
-
1670
-
1671
-    /**
1672
-     * _validate_payment_request_data
1673
-     *
1674
-     * @return array
1675
-     * @throws EE_Error
1676
-     */
1677
-    protected function _validate_payment_request_data()
1678
-    {
1679
-        if (! isset($this->_req_data['txn_admin_payment'])) {
1680
-            return false;
1681
-        }
1682
-        $payment_form = $this->_generate_payment_form_section();
1683
-        try {
1684
-            if ($payment_form->was_submitted()) {
1685
-                $payment_form->receive_form_submission();
1686
-                if (! $payment_form->is_valid()) {
1687
-                    $submission_error_messages = array();
1688
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1689
-                        if ($validation_error instanceof EE_Validation_Error) {
1690
-                            $submission_error_messages[] = sprintf(
1691
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1692
-                                $validation_error->get_form_section()->html_label_text(),
1693
-                                $validation_error->getMessage()
1694
-                            );
1695
-                        }
1696
-                    }
1697
-                    EE_Error::add_error(
1698
-                        implode('<br />', $submission_error_messages),
1699
-                        __FILE__,
1700
-                        __FUNCTION__,
1701
-                        __LINE__
1702
-                    );
1703
-
1704
-                    return array();
1705
-                }
1706
-            }
1707
-        } catch (EE_Error $e) {
1708
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1709
-
1710
-            return array();
1711
-        }
1712
-
1713
-        return $payment_form->valid_data();
1714
-    }
1715
-
1716
-
1717
-    /**
1718
-     * _generate_payment_form_section
1719
-     *
1720
-     * @return EE_Form_Section_Proper
1721
-     * @throws EE_Error
1722
-     */
1723
-    protected function _generate_payment_form_section()
1724
-    {
1725
-        return new EE_Form_Section_Proper(
1726
-            array(
1727
-                'name'        => 'txn_admin_payment',
1728
-                'subsections' => array(
1729
-                    'PAY_ID'          => new EE_Text_Input(
1730
-                        array(
1731
-                            'default'               => 0,
1732
-                            'required'              => false,
1733
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1734
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1735
-                        )
1736
-                    ),
1737
-                    'TXN_ID'          => new EE_Text_Input(
1738
-                        array(
1739
-                            'default'               => 0,
1740
-                            'required'              => true,
1741
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1742
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1743
-                        )
1744
-                    ),
1745
-                    'type'            => new EE_Text_Input(
1746
-                        array(
1747
-                            'default'               => 1,
1748
-                            'required'              => true,
1749
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1750
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1751
-                        )
1752
-                    ),
1753
-                    'amount'          => new EE_Text_Input(
1754
-                        array(
1755
-                            'default'               => 0,
1756
-                            'required'              => true,
1757
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1758
-                            'validation_strategies' => array(new EE_Float_Normalization()),
1759
-                        )
1760
-                    ),
1761
-                    'status'          => new EE_Text_Input(
1762
-                        array(
1763
-                            'default'         => EEM_Payment::status_id_approved,
1764
-                            'required'        => true,
1765
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1766
-                        )
1767
-                    ),
1768
-                    'PMD_ID'          => new EE_Text_Input(
1769
-                        array(
1770
-                            'default'               => 2,
1771
-                            'required'              => true,
1772
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1773
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1774
-                        )
1775
-                    ),
1776
-                    'date'            => new EE_Text_Input(
1777
-                        array(
1778
-                            'default'         => time(),
1779
-                            'required'        => true,
1780
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1781
-                        )
1782
-                    ),
1783
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1784
-                        array(
1785
-                            'default'               => '',
1786
-                            'required'              => false,
1787
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1788
-                            'validation_strategies' => array(
1789
-                                new EE_Max_Length_Validation_Strategy(
1790
-                                    esc_html__('Input too long', 'event_espresso'),
1791
-                                    100
1792
-                                ),
1793
-                            ),
1794
-                        )
1795
-                    ),
1796
-                    'po_number'       => new EE_Text_Input(
1797
-                        array(
1798
-                            'default'               => '',
1799
-                            'required'              => false,
1800
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1801
-                            'validation_strategies' => array(
1802
-                                new EE_Max_Length_Validation_Strategy(
1803
-                                    esc_html__('Input too long', 'event_espresso'),
1804
-                                    100
1805
-                                ),
1806
-                            ),
1807
-                        )
1808
-                    ),
1809
-                    'accounting'      => new EE_Text_Input(
1810
-                        array(
1811
-                            'default'               => '',
1812
-                            'required'              => false,
1813
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1814
-                            'validation_strategies' => array(
1815
-                                new EE_Max_Length_Validation_Strategy(
1816
-                                    esc_html__('Input too long', 'event_espresso'),
1817
-                                    100
1818
-                                ),
1819
-                            ),
1820
-                        )
1821
-                    ),
1822
-                ),
1823
-            )
1824
-        );
1825
-    }
1826
-
1827
-
1828
-    /**
1829
-     * _create_payment_from_request_data
1830
-     *
1831
-     * @param array $valid_data
1832
-     * @return EE_Payment
1833
-     * @throws EE_Error
1834
-     */
1835
-    protected function _create_payment_from_request_data($valid_data)
1836
-    {
1837
-        $PAY_ID = $valid_data['PAY_ID'];
1838
-        // get payment amount
1839
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1840
-        // payments have a type value of 1 and refunds have a type value of -1
1841
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1842
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1843
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1844
-        $date = $valid_data['date']
1845
-            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1846
-            : date('Y-m-d g:i a', current_time('timestamp'));
1847
-        $payment = EE_Payment::new_instance(
1848
-            array(
1849
-                'TXN_ID'              => $valid_data['TXN_ID'],
1850
-                'STS_ID'              => $valid_data['status'],
1851
-                'PAY_timestamp'       => $date,
1852
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1853
-                'PMD_ID'              => $valid_data['PMD_ID'],
1854
-                'PAY_amount'          => $amount,
1855
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1856
-                'PAY_po_number'       => $valid_data['po_number'],
1857
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1858
-                'PAY_details'         => $valid_data,
1859
-                'PAY_ID'              => $PAY_ID,
1860
-            ),
1861
-            '',
1862
-            array('Y-m-d', 'g:i a')
1863
-        );
1864
-
1865
-        if (! $payment->save()) {
1866
-            EE_Error::add_error(
1867
-                sprintf(
1868
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1869
-                    $payment->ID()
1870
-                ),
1871
-                __FILE__,
1872
-                __FUNCTION__,
1873
-                __LINE__
1874
-            );
1875
-        }
1876
-
1877
-        return $payment;
1878
-    }
1879
-
1880
-
1881
-    /**
1882
-     * _process_transaction_payments
1883
-     *
1884
-     * @param \EE_Transaction $transaction
1885
-     * @return void
1886
-     * @throws EE_Error
1887
-     * @throws InvalidArgumentException
1888
-     * @throws ReflectionException
1889
-     * @throws InvalidDataTypeException
1890
-     * @throws InvalidInterfaceException
1891
-     */
1892
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1893
-    {
1894
-        /** @type EE_Transaction_Payments $transaction_payments */
1895
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1896
-        // update the transaction with this payment
1897
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1898
-            EE_Error::add_success(
1899
-                esc_html__(
1900
-                    'The payment has been processed successfully.',
1901
-                    'event_espresso'
1902
-                ),
1903
-                __FILE__,
1904
-                __FUNCTION__,
1905
-                __LINE__
1906
-            );
1907
-        } else {
1908
-            EE_Error::add_error(
1909
-                esc_html__(
1910
-                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1911
-                    'event_espresso'
1912
-                ),
1913
-                __FILE__,
1914
-                __FUNCTION__,
1915
-                __LINE__
1916
-            );
1917
-        }
1918
-    }
1919
-
1920
-
1921
-    /**
1922
-     * _get_REG_IDs_to_apply_payment_to
1923
-     * returns a list of registration IDs that the payment will apply to
1924
-     *
1925
-     * @param \EE_Payment $payment
1926
-     * @return array
1927
-     * @throws EE_Error
1928
-     */
1929
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1930
-    {
1931
-        $REG_IDs = array();
1932
-        // grab array of IDs for specific registrations to apply changes to
1933
-        if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1934
-            $REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1935
-        }
1936
-        // nothing specified ? then get all reg IDs
1937
-        if (empty($REG_IDs)) {
1938
-            $registrations = $payment->transaction()->registrations();
1939
-            $REG_IDs = ! empty($registrations)
1940
-                ? array_keys($registrations)
1941
-                : $this->_get_existing_reg_payment_REG_IDs($payment);
1942
-        }
1943
-
1944
-        // ensure that REG_IDs are integers and NOT strings
1945
-        return array_map('intval', $REG_IDs);
1946
-    }
1947
-
1948
-
1949
-    /**
1950
-     * @return array
1951
-     */
1952
-    public function existing_reg_payment_REG_IDs()
1953
-    {
1954
-        return $this->_existing_reg_payment_REG_IDs;
1955
-    }
1956
-
1957
-
1958
-    /**
1959
-     * @param array $existing_reg_payment_REG_IDs
1960
-     */
1961
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1962
-    {
1963
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1964
-    }
1965
-
1966
-
1967
-    /**
1968
-     * _get_existing_reg_payment_REG_IDs
1969
-     * returns a list of registration IDs that the payment is currently related to
1970
-     * as recorded in the database
1971
-     *
1972
-     * @param \EE_Payment $payment
1973
-     * @return array
1974
-     * @throws EE_Error
1975
-     */
1976
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1977
-    {
1978
-        if ($this->existing_reg_payment_REG_IDs() === null) {
1979
-            // let's get any existing reg payment records for this payment
1980
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1981
-            // but we only want the REG IDs, so grab the array keys
1982
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1983
-                ? array_keys($existing_reg_payment_REG_IDs)
1984
-                : array();
1985
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1986
-        }
1987
-
1988
-        return $this->existing_reg_payment_REG_IDs();
1989
-    }
1990
-
1991
-
1992
-    /**
1993
-     * _remove_existing_registration_payments
1994
-     * this calculates the difference between existing relations
1995
-     * to the supplied payment and the new list registration IDs,
1996
-     * removes any related registrations that no longer apply,
1997
-     * and then updates the registration paid fields
1998
-     *
1999
-     * @param \EE_Payment $payment
2000
-     * @param int         $PAY_ID
2001
-     * @return bool;
2002
-     * @throws EE_Error
2003
-     * @throws InvalidArgumentException
2004
-     * @throws ReflectionException
2005
-     * @throws InvalidDataTypeException
2006
-     * @throws InvalidInterfaceException
2007
-     */
2008
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2009
-    {
2010
-        // newly created payments will have nothing recorded for $PAY_ID
2011
-        if ($PAY_ID == 0) {
2012
-            return false;
2013
-        }
2014
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2015
-        if (empty($existing_reg_payment_REG_IDs)) {
2016
-            return false;
2017
-        }
2018
-        /** @type EE_Transaction_Payments $transaction_payments */
2019
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2020
-
2021
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
2022
-            $payment,
2023
-            array(
2024
-                array(
2025
-                    'PAY_ID' => $payment->ID(),
2026
-                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2027
-                ),
2028
-            )
2029
-        );
2030
-    }
2031
-
2032
-
2033
-    /**
2034
-     * _update_registration_payments
2035
-     * this applies the payments to the selected registrations
2036
-     * but only if they have not already been paid for
2037
-     *
2038
-     * @param  EE_Transaction $transaction
2039
-     * @param \EE_Payment     $payment
2040
-     * @param array           $REG_IDs
2041
-     * @return void
2042
-     * @throws EE_Error
2043
-     * @throws InvalidArgumentException
2044
-     * @throws ReflectionException
2045
-     * @throws RuntimeException
2046
-     * @throws InvalidDataTypeException
2047
-     * @throws InvalidInterfaceException
2048
-     */
2049
-    protected function _update_registration_payments(
2050
-        EE_Transaction $transaction,
2051
-        EE_Payment $payment,
2052
-        $REG_IDs = array()
2053
-    ) {
2054
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2055
-        // so let's do that using our set of REG_IDs from the form
2056
-        $registration_query_where_params = array(
2057
-            'REG_ID' => array('IN', $REG_IDs),
2058
-        );
2059
-        // but add in some conditions regarding payment,
2060
-        // so that we don't apply payments to registrations that are free or have already been paid for
2061
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2062
-        if (! $payment->is_a_refund()) {
2063
-            $registration_query_where_params['REG_final_price'] = array('!=', 0);
2064
-            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2065
-        }
2066
-        $registrations = $transaction->registrations(array($registration_query_where_params));
2067
-        if (! empty($registrations)) {
2068
-            /** @type EE_Payment_Processor $payment_processor */
2069
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2070
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2071
-        }
2072
-    }
2073
-
2074
-
2075
-    /**
2076
-     * _process_registration_status_change
2077
-     * This processes requested registration status changes for all the registrations
2078
-     * on a given transaction and (optionally) sends out notifications for the changes.
2079
-     *
2080
-     * @param  EE_Transaction $transaction
2081
-     * @param array           $REG_IDs
2082
-     * @return bool
2083
-     * @throws EE_Error
2084
-     * @throws InvalidArgumentException
2085
-     * @throws ReflectionException
2086
-     * @throws InvalidDataTypeException
2087
-     * @throws InvalidInterfaceException
2088
-     */
2089
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2090
-    {
2091
-        // first if there is no change in status then we get out.
2092
-        if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2093
-            || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2094
-        ) {
2095
-            // no error message, no change requested, just nothing to do man.
2096
-            return false;
2097
-        }
2098
-        /** @type EE_Transaction_Processor $transaction_processor */
2099
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2100
-
2101
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2102
-        return $transaction_processor->manually_update_registration_statuses(
2103
-            $transaction,
2104
-            sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2105
-            array(array('REG_ID' => array('IN', $REG_IDs)))
2106
-        );
2107
-    }
2108
-
2109
-
2110
-    /**
2111
-     * _build_payment_json_response
2112
-     *
2113
-     * @access public
2114
-     * @param \EE_Payment $payment
2115
-     * @param array       $REG_IDs
2116
-     * @param bool | null $delete_txn_reg_status_change
2117
-     * @return array
2118
-     * @throws EE_Error
2119
-     * @throws InvalidArgumentException
2120
-     * @throws InvalidDataTypeException
2121
-     * @throws InvalidInterfaceException
2122
-     * @throws ReflectionException
2123
-     */
2124
-    protected function _build_payment_json_response(
2125
-        EE_Payment $payment,
2126
-        $REG_IDs = array(),
2127
-        $delete_txn_reg_status_change = null
2128
-    ) {
2129
-        // was the payment deleted ?
2130
-        if (is_bool($delete_txn_reg_status_change)) {
2131
-            return array(
2132
-                'PAY_ID'                       => $payment->ID(),
2133
-                'amount'                       => $payment->amount(),
2134
-                'total_paid'                   => $payment->transaction()->paid(),
2135
-                'txn_status'                   => $payment->transaction()->status_ID(),
2136
-                'pay_status'                   => $payment->STS_ID(),
2137
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2138
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2139
-            );
2140
-        } else {
2141
-            $this->_get_payment_status_array();
2142
-
2143
-            return array(
2144
-                'amount'           => $payment->amount(),
2145
-                'total_paid'       => $payment->transaction()->paid(),
2146
-                'txn_status'       => $payment->transaction()->status_ID(),
2147
-                'pay_status'       => $payment->STS_ID(),
2148
-                'PAY_ID'           => $payment->ID(),
2149
-                'STS_ID'           => $payment->STS_ID(),
2150
-                'status'           => self::$_pay_status[ $payment->STS_ID() ],
2151
-                'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2152
-                'method'           => strtoupper($payment->source()),
2153
-                'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2154
-                'gateway'          => $payment->payment_method()
2155
-                    ? $payment->payment_method()->admin_name()
2156
-                    : esc_html__("Unknown", 'event_espresso'),
2157
-                'gateway_response' => $payment->gateway_response(),
2158
-                'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2159
-                'po_number'        => $payment->po_number(),
2160
-                'extra_accntng'    => $payment->extra_accntng(),
2161
-                'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2162
-            );
2163
-        }
2164
-    }
2165
-
2166
-
2167
-    /**
2168
-     * delete_payment
2169
-     *    delete a payment or refund made towards a transaction
2170
-     *
2171
-     * @access public
2172
-     * @return void
2173
-     * @throws EE_Error
2174
-     * @throws InvalidArgumentException
2175
-     * @throws ReflectionException
2176
-     * @throws InvalidDataTypeException
2177
-     * @throws InvalidInterfaceException
2178
-     */
2179
-    public function delete_payment()
2180
-    {
2181
-        $json_response_data = array('return_data' => false);
2182
-        $PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2183
-            ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2184
-            : 0;
2185
-        $can_delete = EE_Registry::instance()->CAP->current_user_can(
2186
-            'ee_delete_payments',
2187
-            'delete_payment_from_registration_details'
2188
-        );
2189
-        if ($PAY_ID && $can_delete) {
2190
-            $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2191
-                ? $this->_req_data['delete_txn_reg_status_change']
2192
-                : false;
2193
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2194
-            if ($payment instanceof EE_Payment) {
2195
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2196
-                /** @type EE_Transaction_Payments $transaction_payments */
2197
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2198
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2199
-                    $json_response_data['return_data'] = $this->_build_payment_json_response(
2200
-                        $payment,
2201
-                        $REG_IDs,
2202
-                        $delete_txn_reg_status_change
2203
-                    );
2204
-                    if ($delete_txn_reg_status_change) {
2205
-                        $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2206
-                        // MAKE sure we also add the delete_txn_req_status_change to the
2207
-                        // $_REQUEST global because that's how messages will be looking for it.
2208
-                        $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2209
-                        $this->_maybe_send_notifications();
2210
-                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2211
-                    }
2212
-                }
2213
-            } else {
2214
-                EE_Error::add_error(
2215
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2216
-                    __FILE__,
2217
-                    __FUNCTION__,
2218
-                    __LINE__
2219
-                );
2220
-            }
2221
-        } else {
2222
-            if ($can_delete) {
2223
-                EE_Error::add_error(
2224
-                    esc_html__(
2225
-                        'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2226
-                        'event_espresso'
2227
-                    ),
2228
-                    __FILE__,
2229
-                    __FUNCTION__,
2230
-                    __LINE__
2231
-                );
2232
-            } else {
2233
-                EE_Error::add_error(
2234
-                    esc_html__(
2235
-                        'You do not have access to delete a payment.',
2236
-                        'event_espresso'
2237
-                    ),
2238
-                    __FILE__,
2239
-                    __FUNCTION__,
2240
-                    __LINE__
2241
-                );
2242
-            }
2243
-        }
2244
-        $notices = EE_Error::get_notices(false, false, false);
2245
-        $this->_template_args = array(
2246
-            'data'      => $json_response_data,
2247
-            'success'   => $notices['success'],
2248
-            'error'     => $notices['errors'],
2249
-            'attention' => $notices['attention'],
2250
-        );
2251
-        $this->_return_json();
2252
-    }
2253
-
2254
-
2255
-    /**
2256
-     * _registration_payment_data_array
2257
-     * adds info for 'owing' and 'paid' for each registration to the json response
2258
-     *
2259
-     * @access protected
2260
-     * @param array $REG_IDs
2261
-     * @return array
2262
-     * @throws EE_Error
2263
-     * @throws InvalidArgumentException
2264
-     * @throws InvalidDataTypeException
2265
-     * @throws InvalidInterfaceException
2266
-     * @throws ReflectionException
2267
-     */
2268
-    protected function _registration_payment_data_array($REG_IDs)
2269
-    {
2270
-        $registration_payment_data = array();
2271
-        // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2272
-        if (! empty($REG_IDs)) {
2273
-            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2274
-            foreach ($registrations as $registration) {
2275
-                if ($registration instanceof EE_Registration) {
2276
-                    $registration_payment_data[ $registration->ID() ] = array(
2277
-                        'paid'  => $registration->pretty_paid(),
2278
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2279
-                    );
2280
-                }
2281
-            }
2282
-        }
2283
-
2284
-        return $registration_payment_data;
2285
-    }
2286
-
2287
-
2288
-    /**
2289
-     * _maybe_send_notifications
2290
-     * determines whether or not the admin has indicated that notifications should be sent.
2291
-     * If so, will toggle a filter switch for delivering registration notices.
2292
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2293
-     *
2294
-     * @access protected
2295
-     * @param \EE_Payment | null $payment
2296
-     */
2297
-    protected function _maybe_send_notifications($payment = null)
2298
-    {
2299
-        switch ($payment instanceof EE_Payment) {
2300
-            // payment notifications
2301
-            case true:
2302
-                if (isset(
2303
-                    $this->_req_data['txn_payments'],
2304
-                    $this->_req_data['txn_payments']['send_notifications']
2305
-                )
2306
-                    && filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2307
-                ) {
2308
-                    $this->_process_payment_notification($payment);
2309
-                }
2310
-                break;
2311
-            // registration notifications
2312
-            case false:
2313
-                if (isset(
2314
-                    $this->_req_data['txn_reg_status_change'],
2315
-                    $this->_req_data['txn_reg_status_change']['send_notifications']
2316
-                )
2317
-                    && filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2318
-                ) {
2319
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2320
-                }
2321
-                break;
2322
-        }
2323
-    }
2324
-
2325
-
2326
-    /**
2327
-     * _send_payment_reminder
2328
-     *    generates HTML for the View Transaction Details Admin page
2329
-     *
2330
-     * @access protected
2331
-     * @return void
2332
-     * @throws EE_Error
2333
-     * @throws InvalidArgumentException
2334
-     * @throws InvalidDataTypeException
2335
-     * @throws InvalidInterfaceException
2336
-     */
2337
-    protected function _send_payment_reminder()
2338
-    {
2339
-        $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2340
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2341
-        $query_args = isset($this->_req_data['redirect_to']) ? array(
2342
-            'action' => $this->_req_data['redirect_to'],
2343
-            'TXN_ID' => $this->_req_data['TXN_ID'],
2344
-        ) : array();
2345
-        do_action(
2346
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2347
-            $transaction
2348
-        );
2349
-        $this->_redirect_after_action(
2350
-            false,
2351
-            esc_html__('payment reminder', 'event_espresso'),
2352
-            esc_html__('sent', 'event_espresso'),
2353
-            $query_args,
2354
-            true
2355
-        );
2356
-    }
2357
-
2358
-
2359
-    /**
2360
-     *  get_transactions
2361
-     *    get transactions for given parameters (used by list table)
2362
-     *
2363
-     * @param  int     $perpage how many transactions displayed per page
2364
-     * @param  boolean $count   return the count or objects
2365
-     * @param string   $view
2366
-     * @return mixed int = count || array of transaction objects
2367
-     * @throws EE_Error
2368
-     * @throws InvalidArgumentException
2369
-     * @throws InvalidDataTypeException
2370
-     * @throws InvalidInterfaceException
2371
-     */
2372
-    public function get_transactions($perpage, $count = false, $view = '')
2373
-    {
2374
-
2375
-        $TXN = EEM_Transaction::instance();
2376
-
2377
-        $start_date = isset($this->_req_data['txn-filter-start-date'])
2378
-            ? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2379
-            : date(
2380
-                'm/d/Y',
2381
-                strtotime('-10 year')
2382
-            );
2383
-        $end_date = isset($this->_req_data['txn-filter-end-date'])
2384
-            ? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2385
-            : date('m/d/Y');
2386
-
2387
-        // make sure our timestamps start and end right at the boundaries for each day
2388
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2389
-        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2390
-
2391
-
2392
-        // convert to timestamps
2393
-        $start_date = strtotime($start_date);
2394
-        $end_date = strtotime($end_date);
2395
-
2396
-        // makes sure start date is the lowest value and vice versa
2397
-        $start_date = min($start_date, $end_date);
2398
-        $end_date = max($start_date, $end_date);
2399
-
2400
-        // convert to correct format for query
2401
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2402
-            'TXN_timestamp',
2403
-            date('Y-m-d H:i:s', $start_date),
2404
-            'Y-m-d H:i:s'
2405
-        );
2406
-        $end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2407
-            'TXN_timestamp',
2408
-            date('Y-m-d H:i:s', $end_date),
2409
-            'Y-m-d H:i:s'
2410
-        );
2411
-
2412
-
2413
-        // set orderby
2414
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2415
-
2416
-        switch ($this->_req_data['orderby']) {
2417
-            case 'TXN_ID':
2418
-                $orderby = 'TXN_ID';
2419
-                break;
2420
-            case 'ATT_fname':
2421
-                $orderby = 'Registration.Attendee.ATT_fname';
2422
-                break;
2423
-            case 'event_name':
2424
-                $orderby = 'Registration.Event.EVT_name';
2425
-                break;
2426
-            default: // 'TXN_timestamp'
2427
-                $orderby = 'TXN_timestamp';
2428
-        }
2429
-
2430
-        $sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2431
-        $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2432
-        $per_page = ! empty($perpage) ? $perpage : 10;
2433
-        $per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2434
-
2435
-        $offset = ($current_page - 1) * $per_page;
2436
-        $limit = array($offset, $per_page);
2437
-
2438
-        $_where = array(
2439
-            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2440
-            'Registration.REG_count' => 1,
2441
-        );
2442
-
2443
-        if (isset($this->_req_data['EVT_ID'])) {
2444
-            $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2445
-        }
2446
-
2447
-        if (isset($this->_req_data['s'])) {
2448
-            $search_string = '%' . $this->_req_data['s'] . '%';
2449
-            $_where['OR'] = array(
2450
-                'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2451
-                'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2452
-                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2453
-                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2454
-                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2455
-                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2456
-                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2457
-                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2458
-                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2459
-                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2460
-                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2461
-                'Registration.REG_final_price'        => array('LIKE', $search_string),
2462
-                'Registration.REG_code'               => array('LIKE', $search_string),
2463
-                'Registration.REG_count'              => array('LIKE', $search_string),
2464
-                'Registration.REG_group_size'         => array('LIKE', $search_string),
2465
-                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2466
-                'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2467
-                'Payment.PAY_source'                  => array('LIKE', $search_string),
2468
-                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2469
-                'TXN_session_data'                    => array('LIKE', $search_string),
2470
-                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2471
-            );
2472
-        }
2473
-
2474
-        // failed transactions
2475
-        $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2476
-                  || ($count && $view === 'failed');
2477
-        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2478
-                     || ($count && $view === 'abandoned');
2479
-
2480
-        if ($failed) {
2481
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2482
-        } elseif ($abandoned) {
2483
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2484
-        } else {
2485
-            $_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2486
-            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2487
-        }
2488
-
2489
-        $query_params = array(
2490
-            $_where,
2491
-            'order_by'                 => array($orderby => $sort),
2492
-            'limit'                    => $limit,
2493
-            'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2494
-        );
2495
-
2496
-        $transactions = $count
2497
-            ? $TXN->count(array($_where), 'TXN_ID', true)
2498
-            : $TXN->get_all($query_params);
2499
-
2500
-        return $transactions;
2501
-    }
17
+	/**
18
+	 * @var EE_Transaction
19
+	 */
20
+	private $_transaction;
21
+
22
+	/**
23
+	 * @var EE_Session
24
+	 */
25
+	private $_session;
26
+
27
+	/**
28
+	 * @var array $_txn_status
29
+	 */
30
+	private static $_txn_status;
31
+
32
+	/**
33
+	 * @var array $_pay_status
34
+	 */
35
+	private static $_pay_status;
36
+
37
+	/**
38
+	 * @var array $_existing_reg_payment_REG_IDs
39
+	 */
40
+	protected $_existing_reg_payment_REG_IDs = null;
41
+
42
+
43
+	/**
44
+	 * @Constructor
45
+	 * @access public
46
+	 * @param bool $routing
47
+	 * @throws EE_Error
48
+	 * @throws InvalidArgumentException
49
+	 * @throws ReflectionException
50
+	 * @throws InvalidDataTypeException
51
+	 * @throws InvalidInterfaceException
52
+	 */
53
+	public function __construct($routing = true)
54
+	{
55
+		parent::__construct($routing);
56
+	}
57
+
58
+
59
+	/**
60
+	 *    _init_page_props
61
+	 *
62
+	 * @return void
63
+	 */
64
+	protected function _init_page_props()
65
+	{
66
+		$this->page_slug = TXN_PG_SLUG;
67
+		$this->page_label = esc_html__('Transactions', 'event_espresso');
68
+		$this->_admin_base_url = TXN_ADMIN_URL;
69
+		$this->_admin_base_path = TXN_ADMIN;
70
+	}
71
+
72
+
73
+	/**
74
+	 *    _ajax_hooks
75
+	 *
76
+	 * @return void
77
+	 */
78
+	protected function _ajax_hooks()
79
+	{
80
+		add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
81
+		add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
82
+		add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
83
+	}
84
+
85
+
86
+	/**
87
+	 *    _define_page_props
88
+	 *
89
+	 * @return void
90
+	 */
91
+	protected function _define_page_props()
92
+	{
93
+		$this->_admin_page_title = $this->page_label;
94
+		$this->_labels = array(
95
+			'buttons' => array(
96
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
97
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
98
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
99
+			),
100
+		);
101
+	}
102
+
103
+
104
+	/**
105
+	 *        grab url requests and route them
106
+	 *
107
+	 * @access private
108
+	 * @return void
109
+	 * @throws EE_Error
110
+	 * @throws InvalidArgumentException
111
+	 * @throws InvalidDataTypeException
112
+	 * @throws InvalidInterfaceException
113
+	 */
114
+	public function _set_page_routes()
115
+	{
116
+
117
+		$this->_set_transaction_status_array();
118
+
119
+		$txn_id = ! empty($this->_req_data['TXN_ID'])
120
+				  && ! is_array($this->_req_data['TXN_ID'])
121
+			? $this->_req_data['TXN_ID']
122
+			: 0;
123
+
124
+		$this->_page_routes = array(
125
+
126
+			'default' => array(
127
+				'func'       => '_transactions_overview_list_table',
128
+				'capability' => 'ee_read_transactions',
129
+			),
130
+
131
+			'view_transaction' => array(
132
+				'func'       => '_transaction_details',
133
+				'capability' => 'ee_read_transaction',
134
+				'obj_id'     => $txn_id,
135
+			),
136
+
137
+			'send_payment_reminder' => array(
138
+				'func'       => '_send_payment_reminder',
139
+				'noheader'   => true,
140
+				'capability' => 'ee_send_message',
141
+			),
142
+
143
+			'espresso_apply_payment' => array(
144
+				'func'       => 'apply_payments_or_refunds',
145
+				'noheader'   => true,
146
+				'capability' => 'ee_edit_payments',
147
+			),
148
+
149
+			'espresso_apply_refund' => array(
150
+				'func'       => 'apply_payments_or_refunds',
151
+				'noheader'   => true,
152
+				'capability' => 'ee_edit_payments',
153
+			),
154
+
155
+			'espresso_delete_payment' => array(
156
+				'func'       => 'delete_payment',
157
+				'noheader'   => true,
158
+				'capability' => 'ee_delete_payments',
159
+			),
160
+
161
+		);
162
+	}
163
+
164
+
165
+	protected function _set_page_config()
166
+	{
167
+		$this->_page_config = array(
168
+			'default'          => array(
169
+				'nav'           => array(
170
+					'label' => esc_html__('Overview', 'event_espresso'),
171
+					'order' => 10,
172
+				),
173
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
174
+				'help_tabs'     => array(
175
+					'transactions_overview_help_tab'                       => array(
176
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
177
+						'filename' => 'transactions_overview',
178
+					),
179
+					'transactions_overview_table_column_headings_help_tab' => array(
180
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
181
+						'filename' => 'transactions_overview_table_column_headings',
182
+					),
183
+					'transactions_overview_views_filters_help_tab'         => array(
184
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
185
+						'filename' => 'transactions_overview_views_filters_search',
186
+					),
187
+				),
188
+				'help_tour'     => array('Transactions_Overview_Help_Tour'),
189
+				/**
190
+				 * commented out because currently we are not displaying tips for transaction list table status but this
191
+				 * may change in a later iteration so want to keep the code for then.
192
+				 */
193
+				// 'qtips' => array( 'Transactions_List_Table_Tips' ),
194
+				'require_nonce' => false,
195
+			),
196
+			'view_transaction' => array(
197
+				'nav'       => array(
198
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
199
+					'order'      => 5,
200
+					'url'        => isset($this->_req_data['TXN_ID'])
201
+						? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
202
+						: $this->_admin_base_url,
203
+					'persistent' => false,
204
+				),
205
+				'help_tabs' => array(
206
+					'transactions_view_transaction_help_tab'                                              => array(
207
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
208
+						'filename' => 'transactions_view_transaction',
209
+					),
210
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
+						'filename' => 'transactions_view_transaction_transaction_details_table',
213
+					),
214
+					'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
+						'filename' => 'transactions_view_transaction_attendees_registered',
217
+					),
218
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
221
+					),
222
+				),
223
+				'qtips'     => array('Transaction_Details_Tips'),
224
+				'help_tour' => array('Transaction_Details_Help_Tour'),
225
+				'metaboxes' => array('_transaction_details_metaboxes'),
226
+
227
+				'require_nonce' => false,
228
+			),
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * The below methods aren't used by this class currently
235
+	 */
236
+	protected function _add_screen_options()
237
+	{
238
+		// noop
239
+	}
240
+
241
+	protected function _add_feature_pointers()
242
+	{
243
+		// noop
244
+	}
245
+
246
+	public function admin_init()
247
+	{
248
+		// IF a registration was JUST added via the admin...
249
+		if (isset(
250
+			$this->_req_data['redirect_from'],
251
+			$this->_req_data['EVT_ID'],
252
+			$this->_req_data['event_name']
253
+		)) {
254
+			// then set a cookie so that we can block any attempts to use
255
+			// the back button as a way to enter another registration.
256
+			setcookie(
257
+				'ee_registration_added',
258
+				$this->_req_data['EVT_ID'],
259
+				time() + WEEK_IN_SECONDS,
260
+				'/'
261
+			);
262
+			// and update the global
263
+			$_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
+		}
265
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
+			'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
+			'event_espresso'
268
+		);
269
+		EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
270
+			'An error occurred! Please refresh the page and try again.',
271
+			'event_espresso'
272
+		);
273
+		EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
274
+		EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
275
+		EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
276
+		EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
277
+			'This transaction has been overpaid ! Payments Total',
278
+			'event_espresso'
279
+		);
280
+	}
281
+
282
+	public function admin_notices()
283
+	{
284
+		// noop
285
+	}
286
+
287
+	public function admin_footer_scripts()
288
+	{
289
+		// noop
290
+	}
291
+
292
+
293
+	/**
294
+	 * _set_transaction_status_array
295
+	 * sets list of transaction statuses
296
+	 *
297
+	 * @access private
298
+	 * @return void
299
+	 * @throws EE_Error
300
+	 * @throws InvalidArgumentException
301
+	 * @throws InvalidDataTypeException
302
+	 * @throws InvalidInterfaceException
303
+	 */
304
+	private function _set_transaction_status_array()
305
+	{
306
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
+	}
308
+
309
+
310
+	/**
311
+	 * get_transaction_status_array
312
+	 * return the transaction status array for wp_list_table
313
+	 *
314
+	 * @access public
315
+	 * @return array
316
+	 */
317
+	public function get_transaction_status_array()
318
+	{
319
+		return self::$_txn_status;
320
+	}
321
+
322
+
323
+	/**
324
+	 *    get list of payment statuses
325
+	 *
326
+	 * @access private
327
+	 * @return void
328
+	 * @throws EE_Error
329
+	 * @throws InvalidArgumentException
330
+	 * @throws InvalidDataTypeException
331
+	 * @throws InvalidInterfaceException
332
+	 */
333
+	private function _get_payment_status_array()
334
+	{
335
+		self::$_pay_status = EEM_Payment::instance()->status_array(true);
336
+		$this->_template_args['payment_status'] = self::$_pay_status;
337
+	}
338
+
339
+
340
+	/**
341
+	 *    _add_screen_options_default
342
+	 *
343
+	 * @access protected
344
+	 * @return void
345
+	 * @throws InvalidArgumentException
346
+	 * @throws InvalidDataTypeException
347
+	 * @throws InvalidInterfaceException
348
+	 */
349
+	protected function _add_screen_options_default()
350
+	{
351
+		$this->_per_page_screen_option();
352
+	}
353
+
354
+
355
+	/**
356
+	 * load_scripts_styles
357
+	 *
358
+	 * @access public
359
+	 * @return void
360
+	 */
361
+	public function load_scripts_styles()
362
+	{
363
+		// enqueue style
364
+		wp_register_style(
365
+			'espresso_txn',
366
+			TXN_ASSETS_URL . 'espresso_transactions_admin.css',
367
+			array(),
368
+			EVENT_ESPRESSO_VERSION
369
+		);
370
+		wp_enqueue_style('espresso_txn');
371
+		// scripts
372
+		wp_register_script(
373
+			'espresso_txn',
374
+			TXN_ASSETS_URL . 'espresso_transactions_admin.js',
375
+			array(
376
+				'ee_admin_js',
377
+				'ee-datepicker',
378
+				'jquery-ui-datepicker',
379
+				'jquery-ui-draggable',
380
+				'ee-dialog',
381
+				'ee-accounting',
382
+				'ee-serialize-full-array',
383
+			),
384
+			EVENT_ESPRESSO_VERSION,
385
+			true
386
+		);
387
+		wp_enqueue_script('espresso_txn');
388
+	}
389
+
390
+
391
+	/**
392
+	 *    load_scripts_styles_view_transaction
393
+	 *
394
+	 * @access public
395
+	 * @return void
396
+	 */
397
+	public function load_scripts_styles_view_transaction()
398
+	{
399
+		// styles
400
+		wp_enqueue_style('espresso-ui-theme');
401
+	}
402
+
403
+
404
+	/**
405
+	 *    load_scripts_styles_default
406
+	 *
407
+	 * @access public
408
+	 * @return void
409
+	 */
410
+	public function load_scripts_styles_default()
411
+	{
412
+		// styles
413
+		wp_enqueue_style('espresso-ui-theme');
414
+	}
415
+
416
+
417
+	/**
418
+	 *    _set_list_table_views_default
419
+	 *
420
+	 * @access protected
421
+	 * @return void
422
+	 */
423
+	protected function _set_list_table_views_default()
424
+	{
425
+		$this->_views = array(
426
+			'all'       => array(
427
+				'slug'  => 'all',
428
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
429
+				'count' => 0,
430
+			),
431
+			'abandoned' => array(
432
+				'slug'  => 'abandoned',
433
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
434
+				'count' => 0,
435
+			),
436
+		);
437
+		if (
438
+			/**
439
+			 * Filters whether a link to the "Failed Transactions" list table
440
+			 * appears on the Transactions Admin Page list table.
441
+			 * List display can be turned back on via the following:
442
+			 * add_filter(
443
+			 *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed',
444
+			 *     '__return_true'
445
+			 * );
446
+			 *
447
+			 * @since $VID:$
448
+			 * @param boolean                 $display_failed_txns_list
449
+			 * @param Transactions_Admin_Page $this
450
+			 */
451
+		apply_filters(
452
+			'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
453
+			false,
454
+			$this
455
+		)
456
+		) {
457
+			$this->_views['failed'] = array(
458
+				'slug'  => 'failed',
459
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
460
+				'count' => 0,
461
+			);
462
+		}
463
+	}
464
+
465
+
466
+	/**
467
+	 * _set_transaction_object
468
+	 * This sets the _transaction property for the transaction details screen
469
+	 *
470
+	 * @access private
471
+	 * @return void
472
+	 * @throws EE_Error
473
+	 * @throws InvalidArgumentException
474
+	 * @throws RuntimeException
475
+	 * @throws InvalidDataTypeException
476
+	 * @throws InvalidInterfaceException
477
+	 * @throws ReflectionException
478
+	 */
479
+	private function _set_transaction_object()
480
+	{
481
+		if ($this->_transaction instanceof EE_Transaction) {
482
+			return;
483
+		} //get out we've already set the object
484
+
485
+		$TXN_ID = ! empty($this->_req_data['TXN_ID'])
486
+			? absint($this->_req_data['TXN_ID'])
487
+			: false;
488
+
489
+		// get transaction object
490
+		$this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
491
+		$this->_session = $this->_transaction instanceof EE_Transaction
492
+			? $this->_transaction->get('TXN_session_data')
493
+			: null;
494
+		if ($this->_transaction instanceof EE_Transaction) {
495
+			$this->_transaction->verify_abandoned_transaction_status();
496
+		}
497
+
498
+		if (! $this->_transaction instanceof EE_Transaction) {
499
+			$error_msg = sprintf(
500
+				esc_html__(
501
+					'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
502
+					'event_espresso'
503
+				),
504
+				$TXN_ID
505
+			);
506
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
507
+		}
508
+	}
509
+
510
+
511
+	/**
512
+	 *    _transaction_legend_items
513
+	 *
514
+	 * @access protected
515
+	 * @return array
516
+	 * @throws EE_Error
517
+	 * @throws InvalidArgumentException
518
+	 * @throws ReflectionException
519
+	 * @throws InvalidDataTypeException
520
+	 * @throws InvalidInterfaceException
521
+	 */
522
+	protected function _transaction_legend_items()
523
+	{
524
+		EE_Registry::instance()->load_helper('MSG_Template');
525
+		$items = array();
526
+
527
+		if (EE_Registry::instance()->CAP->current_user_can(
528
+			'ee_read_global_messages',
529
+			'view_filtered_messages'
530
+		)) {
531
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
532
+			if (is_array($related_for_icon)
533
+				&& isset($related_for_icon['css_class'], $related_for_icon['label'])
534
+			) {
535
+				$items['view_related_messages'] = array(
536
+					'class' => $related_for_icon['css_class'],
537
+					'desc'  => $related_for_icon['label'],
538
+				);
539
+			}
540
+		}
541
+
542
+		$items = apply_filters(
543
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
544
+			array_merge(
545
+				$items,
546
+				array(
547
+					'view_details'          => array(
548
+						'class' => 'dashicons dashicons-cart',
549
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
550
+					),
551
+					'view_invoice'          => array(
552
+						'class' => 'dashicons dashicons-media-spreadsheet',
553
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
554
+					),
555
+					'view_receipt'          => array(
556
+						'class' => 'dashicons dashicons-media-default',
557
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
558
+					),
559
+					'view_registration'     => array(
560
+						'class' => 'dashicons dashicons-clipboard',
561
+						'desc'  => esc_html__('View Registration Details', 'event_espresso'),
562
+					),
563
+					'payment_overview_link' => array(
564
+						'class' => 'dashicons dashicons-money',
565
+						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
566
+					),
567
+				)
568
+			)
569
+		);
570
+
571
+		if (EE_Registry::instance()->CAP->current_user_can(
572
+			'ee_send_message',
573
+			'espresso_transactions_send_payment_reminder'
574
+		)) {
575
+			if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
576
+				$items['send_payment_reminder'] = array(
577
+					'class' => 'dashicons dashicons-email-alt',
578
+					'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
579
+				);
580
+			} else {
581
+				$items['blank*'] = array(
582
+					'class' => '',
583
+					'desc'  => '',
584
+				);
585
+			}
586
+		} else {
587
+			$items['blank*'] = array(
588
+				'class' => '',
589
+				'desc'  => '',
590
+			);
591
+		}
592
+		$more_items = apply_filters(
593
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
594
+			array(
595
+				'overpaid'   => array(
596
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
597
+					'desc'  => EEH_Template::pretty_status(
598
+						EEM_Transaction::overpaid_status_code,
599
+						false,
600
+						'sentence'
601
+					),
602
+				),
603
+				'complete'   => array(
604
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
605
+					'desc'  => EEH_Template::pretty_status(
606
+						EEM_Transaction::complete_status_code,
607
+						false,
608
+						'sentence'
609
+					),
610
+				),
611
+				'incomplete' => array(
612
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
613
+					'desc'  => EEH_Template::pretty_status(
614
+						EEM_Transaction::incomplete_status_code,
615
+						false,
616
+						'sentence'
617
+					),
618
+				),
619
+				'abandoned'  => array(
620
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
621
+					'desc'  => EEH_Template::pretty_status(
622
+						EEM_Transaction::abandoned_status_code,
623
+						false,
624
+						'sentence'
625
+					),
626
+				),
627
+				'failed'     => array(
628
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
629
+					'desc'  => EEH_Template::pretty_status(
630
+						EEM_Transaction::failed_status_code,
631
+						false,
632
+						'sentence'
633
+					),
634
+				),
635
+			)
636
+		);
637
+
638
+		return array_merge($items, $more_items);
639
+	}
640
+
641
+
642
+	/**
643
+	 *    _transactions_overview_list_table
644
+	 *
645
+	 * @access protected
646
+	 * @return void
647
+	 * @throws DomainException
648
+	 * @throws EE_Error
649
+	 * @throws InvalidArgumentException
650
+	 * @throws InvalidDataTypeException
651
+	 * @throws InvalidInterfaceException
652
+	 * @throws ReflectionException
653
+	 */
654
+	protected function _transactions_overview_list_table()
655
+	{
656
+		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
657
+		$event = isset($this->_req_data['EVT_ID'])
658
+			? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
659
+			: null;
660
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event
661
+			? sprintf(
662
+				esc_html__(
663
+					'%sViewing Transactions for the Event: %s%s',
664
+					'event_espresso'
665
+				),
666
+				'<h3>',
667
+				'<a href="'
668
+				. EE_Admin_Page::add_query_args_and_nonce(
669
+					array('action' => 'edit', 'post' => $event->ID()),
670
+					EVENTS_ADMIN_URL
671
+				)
672
+				. '" title="'
673
+				. esc_attr__(
674
+					'Click to Edit event',
675
+					'event_espresso'
676
+				)
677
+				. '">' . $event->get('EVT_name') . '</a>',
678
+				'</h3>'
679
+			)
680
+			: '';
681
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
682
+		$this->display_admin_list_table_page_with_no_sidebar();
683
+	}
684
+
685
+
686
+	/**
687
+	 *    _transaction_details
688
+	 * generates HTML for the View Transaction Details Admin page
689
+	 *
690
+	 * @access protected
691
+	 * @return void
692
+	 * @throws DomainException
693
+	 * @throws EE_Error
694
+	 * @throws InvalidArgumentException
695
+	 * @throws InvalidDataTypeException
696
+	 * @throws InvalidInterfaceException
697
+	 * @throws RuntimeException
698
+	 * @throws ReflectionException
699
+	 */
700
+	protected function _transaction_details()
701
+	{
702
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
703
+
704
+		$this->_set_transaction_status_array();
705
+
706
+		$this->_template_args = array();
707
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
708
+
709
+		$this->_set_transaction_object();
710
+
711
+		if (! $this->_transaction instanceof EE_Transaction) {
712
+			return;
713
+		}
714
+		$primary_registration = $this->_transaction->primary_registration();
715
+		$attendee = $primary_registration instanceof EE_Registration
716
+			? $primary_registration->attendee()
717
+			: null;
718
+
719
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
720
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
721
+
722
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
723
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
724
+
725
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
726
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
727
+		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
728
+
729
+		$this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
730
+		$this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
731
+
732
+		$amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
733
+		$this->_template_args['amount_due'] = EEH_Template::format_currency(
734
+			$amount_due,
735
+			true
736
+		);
737
+		if (EE_Registry::instance()->CFG->currency->sign_b4) {
738
+			$this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
739
+												  . $this->_template_args['amount_due'];
740
+		} else {
741
+			$this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
742
+		}
743
+		$this->_template_args['amount_due_class'] = '';
744
+
745
+		if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
746
+			// paid in full
747
+			$this->_template_args['amount_due'] = false;
748
+		} elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
749
+			// overpaid
750
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
751
+		} elseif ($this->_transaction->get('TXN_total') > 0
752
+				  && $this->_transaction->get('TXN_paid') > 0
753
+		) {
754
+			// monies owing
755
+			$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
756
+		} elseif ($this->_transaction->get('TXN_total') > 0
757
+				  && $this->_transaction->get('TXN_paid') == 0
758
+		) {
759
+			// no payments made yet
760
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
761
+		} elseif ($this->_transaction->get('TXN_total') == 0) {
762
+			// free event
763
+			$this->_template_args['amount_due'] = false;
764
+		}
765
+
766
+		$payment_method = $this->_transaction->payment_method();
767
+
768
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
769
+			? $payment_method->admin_name()
770
+			: esc_html__('Unknown', 'event_espresso');
771
+
772
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
773
+		// link back to overview
774
+		$this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
775
+			? $_SERVER['HTTP_REFERER']
776
+			: TXN_ADMIN_URL;
777
+
778
+
779
+		// next link
780
+		$next_txn = $this->_transaction->next(
781
+			null,
782
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
783
+			'TXN_ID'
784
+		);
785
+		$this->_template_args['next_transaction'] = $next_txn
786
+			? $this->_next_link(
787
+				EE_Admin_Page::add_query_args_and_nonce(
788
+					array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
789
+					TXN_ADMIN_URL
790
+				),
791
+				'dashicons dashicons-arrow-right ee-icon-size-22'
792
+			)
793
+			: '';
794
+		// previous link
795
+		$previous_txn = $this->_transaction->previous(
796
+			null,
797
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
798
+			'TXN_ID'
799
+		);
800
+		$this->_template_args['previous_transaction'] = $previous_txn
801
+			? $this->_previous_link(
802
+				EE_Admin_Page::add_query_args_and_nonce(
803
+					array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
804
+					TXN_ADMIN_URL
805
+				),
806
+				'dashicons dashicons-arrow-left ee-icon-size-22'
807
+			)
808
+			: '';
809
+
810
+		// were we just redirected here after adding a new registration ???
811
+		if (isset(
812
+			$this->_req_data['redirect_from'],
813
+			$this->_req_data['EVT_ID'],
814
+			$this->_req_data['event_name']
815
+		)) {
816
+			if (EE_Registry::instance()->CAP->current_user_can(
817
+				'ee_edit_registrations',
818
+				'espresso_registrations_new_registration',
819
+				$this->_req_data['EVT_ID']
820
+			)) {
821
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
822
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
823
+					array(
824
+						'page'     => 'espresso_registrations',
825
+						'action'   => 'new_registration',
826
+						'return'   => 'default',
827
+						'TXN_ID'   => $this->_transaction->ID(),
828
+						'event_id' => $this->_req_data['EVT_ID'],
829
+					),
830
+					REG_ADMIN_URL
831
+				);
832
+				$this->_admin_page_title .= '">';
833
+
834
+				$this->_admin_page_title .= sprintf(
835
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
836
+					htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
837
+				);
838
+				$this->_admin_page_title .= '</a>';
839
+			}
840
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
841
+		}
842
+		// grab messages at the last second
843
+		$this->_template_args['notices'] = EE_Error::get_notices();
844
+		// path to template
845
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
846
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template(
847
+			$template_path,
848
+			$this->_template_args,
849
+			true
850
+		);
851
+
852
+		// the details template wrapper
853
+		$this->display_admin_page_with_sidebar();
854
+	}
855
+
856
+
857
+	/**
858
+	 *        _transaction_details_metaboxes
859
+	 *
860
+	 * @access protected
861
+	 * @return void
862
+	 * @throws EE_Error
863
+	 * @throws InvalidArgumentException
864
+	 * @throws InvalidDataTypeException
865
+	 * @throws InvalidInterfaceException
866
+	 * @throws RuntimeException
867
+	 * @throws ReflectionException
868
+	 */
869
+	protected function _transaction_details_metaboxes()
870
+	{
871
+
872
+		$this->_set_transaction_object();
873
+
874
+		if (! $this->_transaction instanceof EE_Transaction) {
875
+			return;
876
+		}
877
+		add_meta_box(
878
+			'edit-txn-details-mbox',
879
+			esc_html__('Transaction Details', 'event_espresso'),
880
+			array($this, 'txn_details_meta_box'),
881
+			$this->_wp_page_slug,
882
+			'normal',
883
+			'high'
884
+		);
885
+		add_meta_box(
886
+			'edit-txn-attendees-mbox',
887
+			esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
888
+			array($this, 'txn_attendees_meta_box'),
889
+			$this->_wp_page_slug,
890
+			'normal',
891
+			'high',
892
+			array('TXN_ID' => $this->_transaction->ID())
893
+		);
894
+		add_meta_box(
895
+			'edit-txn-registrant-mbox',
896
+			esc_html__('Primary Contact', 'event_espresso'),
897
+			array($this, 'txn_registrant_side_meta_box'),
898
+			$this->_wp_page_slug,
899
+			'side',
900
+			'high'
901
+		);
902
+		add_meta_box(
903
+			'edit-txn-billing-info-mbox',
904
+			esc_html__('Billing Information', 'event_espresso'),
905
+			array($this, 'txn_billing_info_side_meta_box'),
906
+			$this->_wp_page_slug,
907
+			'side',
908
+			'high'
909
+		);
910
+	}
911
+
912
+
913
+	/**
914
+	 * Callback for transaction actions metabox.
915
+	 *
916
+	 * @param EE_Transaction|null $transaction
917
+	 * @throws DomainException
918
+	 * @throws EE_Error
919
+	 * @throws InvalidArgumentException
920
+	 * @throws InvalidDataTypeException
921
+	 * @throws InvalidInterfaceException
922
+	 * @throws ReflectionException
923
+	 * @throws RuntimeException
924
+	 */
925
+	public function getActionButtons(EE_Transaction $transaction = null)
926
+	{
927
+		$content = '';
928
+		$actions = array();
929
+		if (! $transaction instanceof EE_Transaction) {
930
+			return $content;
931
+		}
932
+		/** @var EE_Registration $primary_registration */
933
+		$primary_registration = $transaction->primary_registration();
934
+		$attendee = $primary_registration instanceof EE_Registration
935
+			? $primary_registration->attendee()
936
+			: null;
937
+
938
+		if ($attendee instanceof EE_Attendee
939
+			&& EE_Registry::instance()->CAP->current_user_can(
940
+				'ee_send_message',
941
+				'espresso_transactions_send_payment_reminder'
942
+			)
943
+		) {
944
+			$actions['payment_reminder'] =
945
+				EEH_MSG_Template::is_mt_active('payment_reminder')
946
+				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
947
+				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
948
+					? EEH_Template::get_button_or_link(
949
+						EE_Admin_Page::add_query_args_and_nonce(
950
+							array(
951
+								'action'      => 'send_payment_reminder',
952
+								'TXN_ID'      => $this->_transaction->ID(),
953
+								'redirect_to' => 'view_transaction',
954
+							),
955
+							TXN_ADMIN_URL
956
+						),
957
+						esc_html__(' Send Payment Reminder', 'event_espresso'),
958
+						'button secondary-button',
959
+						'dashicons dashicons-email-alt'
960
+					)
961
+					: '';
962
+		}
963
+
964
+		if ($primary_registration instanceof EE_Registration
965
+			&& EEH_MSG_Template::is_mt_active('receipt')
966
+		) {
967
+			$actions['receipt'] = EEH_Template::get_button_or_link(
968
+				$primary_registration->receipt_url(),
969
+				esc_html__('View Receipt', 'event_espresso'),
970
+				'button secondary-button',
971
+				'dashicons dashicons-media-default'
972
+			);
973
+		}
974
+
975
+		if ($primary_registration instanceof EE_Registration
976
+			&& EEH_MSG_Template::is_mt_active('invoice')
977
+		) {
978
+			$actions['invoice'] = EEH_Template::get_button_or_link(
979
+				$primary_registration->invoice_url(),
980
+				esc_html__('View Invoice', 'event_espresso'),
981
+				'button secondary-button',
982
+				'dashicons dashicons-media-spreadsheet'
983
+			);
984
+		}
985
+		$actions = array_filter(
986
+			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
987
+		);
988
+		if ($actions) {
989
+			$content = '<ul>';
990
+			$content .= '<li>' . implode('</li><li>', $actions) . '</li>';
991
+			$content .= '</uL>';
992
+		}
993
+		return $content;
994
+	}
995
+
996
+
997
+	/**
998
+	 * txn_details_meta_box
999
+	 * generates HTML for the Transaction main meta box
1000
+	 *
1001
+	 * @return void
1002
+	 * @throws DomainException
1003
+	 * @throws EE_Error
1004
+	 * @throws InvalidArgumentException
1005
+	 * @throws InvalidDataTypeException
1006
+	 * @throws InvalidInterfaceException
1007
+	 * @throws RuntimeException
1008
+	 * @throws ReflectionException
1009
+	 */
1010
+	public function txn_details_meta_box()
1011
+	{
1012
+		$this->_set_transaction_object();
1013
+		$this->_template_args['TXN_ID'] = $this->_transaction->ID();
1014
+		$this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1015
+			? $this->_transaction->primary_registration()->attendee()
1016
+			: null;
1017
+		$this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1018
+			'ee_edit_payments',
1019
+			'apply_payment_or_refund_from_registration_details'
1020
+		);
1021
+		$this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1022
+			'ee_delete_payments',
1023
+			'delete_payment_from_registration_details'
1024
+		);
1025
+
1026
+		// get line table
1027
+		EEH_Autoloader::register_line_item_display_autoloaders();
1028
+		$Line_Item_Display = new EE_Line_Item_Display(
1029
+			'admin_table',
1030
+			'EE_Admin_Table_Line_Item_Display_Strategy'
1031
+		);
1032
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1033
+			$this->_transaction->total_line_item()
1034
+		);
1035
+		$this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration')
1036
+															   ->get('REG_code');
1037
+
1038
+		// process taxes
1039
+		$taxes = $this->_transaction->get_many_related(
1040
+			'Line_Item',
1041
+			array(array('LIN_type' => EEM_Line_Item::type_tax))
1042
+		);
1043
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1044
+
1045
+		$this->_template_args['grand_total'] = EEH_Template::format_currency(
1046
+			$this->_transaction->get('TXN_total'),
1047
+			false,
1048
+			false
1049
+		);
1050
+		$this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1051
+		$this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID');
1052
+
1053
+		// process payment details
1054
+		$payments = $this->_transaction->get_many_related('Payment');
1055
+		if (! empty($payments)) {
1056
+			$this->_template_args['payments'] = $payments;
1057
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1058
+		} else {
1059
+			$this->_template_args['payments'] = false;
1060
+			$this->_template_args['existing_reg_payments'] = array();
1061
+		}
1062
+
1063
+		$this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1064
+		$this->_template_args['delete_payment_url'] = add_query_arg(
1065
+			array('action' => 'espresso_delete_payment'),
1066
+			TXN_ADMIN_URL
1067
+		);
1068
+
1069
+		if (isset($txn_details['invoice_number'])) {
1070
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1071
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1072
+				'Invoice Number',
1073
+				'event_espresso'
1074
+			);
1075
+		}
1076
+
1077
+		$this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1078
+			->get_first_related('Registration')
1079
+			->get('REG_session');
1080
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1081
+			'Registration Session',
1082
+			'event_espresso'
1083
+		);
1084
+
1085
+		$this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1086
+			? $this->_session['ip_address']
1087
+			: '';
1088
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1089
+			'Transaction placed from IP',
1090
+			'event_espresso'
1091
+		);
1092
+
1093
+		$this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1094
+			? $this->_session['user_agent']
1095
+			: '';
1096
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1097
+			'Registrant User Agent',
1098
+			'event_espresso'
1099
+		);
1100
+
1101
+		$reg_steps = '<ul>';
1102
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1103
+			if ($reg_step_status === true) {
1104
+				$reg_steps .= '<li style="color:#70cc50">'
1105
+							  . sprintf(
1106
+								  esc_html__('%1$s : Completed', 'event_espresso'),
1107
+								  ucwords(str_replace('_', ' ', $reg_step))
1108
+							  )
1109
+							  . '</li>';
1110
+			} elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1111
+				$reg_steps .= '<li style="color:#2EA2CC">'
1112
+							  . sprintf(
1113
+								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1114
+								  ucwords(str_replace('_', ' ', $reg_step)),
1115
+								  date(
1116
+									  get_option('date_format') . ' ' . get_option('time_format'),
1117
+									  ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1118
+								  )
1119
+							  )
1120
+							  . '</li>';
1121
+			} else {
1122
+				$reg_steps .= '<li style="color:#E76700">'
1123
+							  . sprintf(
1124
+								  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1125
+								  ucwords(str_replace('_', ' ', $reg_step))
1126
+							  )
1127
+							  . '</li>';
1128
+			}
1129
+		}
1130
+		$reg_steps .= '</ul>';
1131
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1132
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1133
+			'Registration Step Progress',
1134
+			'event_espresso'
1135
+		);
1136
+
1137
+
1138
+		$this->_get_registrations_to_apply_payment_to();
1139
+		$this->_get_payment_methods($payments);
1140
+		$this->_get_payment_status_array();
1141
+		$this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1142
+
1143
+		$this->_template_args['transaction_form_url'] = add_query_arg(
1144
+			array(
1145
+				'action'  => 'edit_transaction',
1146
+				'process' => 'transaction',
1147
+			),
1148
+			TXN_ADMIN_URL
1149
+		);
1150
+		$this->_template_args['apply_payment_form_url'] = add_query_arg(
1151
+			array(
1152
+				'page'   => 'espresso_transactions',
1153
+				'action' => 'espresso_apply_payment',
1154
+			),
1155
+			WP_AJAX_URL
1156
+		);
1157
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(
1158
+			array(
1159
+				'page'   => 'espresso_transactions',
1160
+				'action' => 'espresso_delete_payment',
1161
+			),
1162
+			WP_AJAX_URL
1163
+		);
1164
+
1165
+		$this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1166
+
1167
+		// 'espresso_delete_payment_nonce'
1168
+
1169
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1170
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1171
+	}
1172
+
1173
+
1174
+	/**
1175
+	 * _get_registration_payment_IDs
1176
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
1177
+	 *
1178
+	 * @access protected
1179
+	 * @param EE_Payment[] $payments
1180
+	 * @return array
1181
+	 * @throws EE_Error
1182
+	 * @throws InvalidArgumentException
1183
+	 * @throws InvalidDataTypeException
1184
+	 * @throws InvalidInterfaceException
1185
+	 * @throws ReflectionException
1186
+	 */
1187
+	protected function _get_registration_payment_IDs($payments = array())
1188
+	{
1189
+		$existing_reg_payments = array();
1190
+		// get all reg payments for these payments
1191
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(
1192
+			array(
1193
+				array(
1194
+					'PAY_ID' => array(
1195
+						'IN',
1196
+						array_keys($payments),
1197
+					),
1198
+				),
1199
+			)
1200
+		);
1201
+		if (! empty($reg_payments)) {
1202
+			foreach ($payments as $payment) {
1203
+				if (! $payment instanceof EE_Payment) {
1204
+					continue;
1205
+				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1206
+					$existing_reg_payments[ $payment->ID() ] = array();
1207
+				}
1208
+				foreach ($reg_payments as $reg_payment) {
1209
+					if ($reg_payment instanceof EE_Registration_Payment
1210
+						&& $reg_payment->payment_ID() === $payment->ID()
1211
+					) {
1212
+						$existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1213
+					}
1214
+				}
1215
+			}
1216
+		}
1217
+
1218
+		return $existing_reg_payments;
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * _get_registrations_to_apply_payment_to
1224
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1225
+	 * which allows the admin to only apply the payment to the specific registrations
1226
+	 *
1227
+	 * @access protected
1228
+	 * @return void
1229
+	 * @throws \EE_Error
1230
+	 */
1231
+	protected function _get_registrations_to_apply_payment_to()
1232
+	{
1233
+		// we want any registration with an active status (ie: not deleted or cancelled)
1234
+		$query_params = array(
1235
+			array(
1236
+				'STS_ID' => array(
1237
+					'IN',
1238
+					array(
1239
+						EEM_Registration::status_id_approved,
1240
+						EEM_Registration::status_id_pending_payment,
1241
+						EEM_Registration::status_id_not_approved,
1242
+					),
1243
+				),
1244
+			),
1245
+		);
1246
+		$registrations_to_apply_payment_to = EEH_HTML::br()
1247
+											 . EEH_HTML::div(
1248
+												 '',
1249
+												 'txn-admin-apply-payment-to-registrations-dv',
1250
+												 '',
1251
+												 'clear: both; margin: 1.5em 0 0; display: none;'
1252
+											 );
1253
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1254
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1255
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
1256
+			EEH_HTML::tr(
1257
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1258
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1259
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1260
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1261
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1262
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1263
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1264
+			)
1265
+		);
1266
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
1267
+		// get registrations for TXN
1268
+		$registrations = $this->_transaction->registrations($query_params);
1269
+		$existing_reg_payments = $this->_template_args['existing_reg_payments'];
1270
+		foreach ($registrations as $registration) {
1271
+			if ($registration instanceof EE_Registration) {
1272
+				$attendee_name = $registration->attendee() instanceof EE_Attendee
1273
+					? $registration->attendee()->full_name()
1274
+					: esc_html__('Unknown Attendee', 'event_espresso');
1275
+				$owing = $registration->final_price() - $registration->paid();
1276
+				$taxable = $registration->ticket()->taxable()
1277
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1278
+					: '';
1279
+				$checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1280
+					? ' checked="checked"'
1281
+					: '';
1282
+				$disabled = $registration->final_price() > 0 ? '' : ' disabled';
1283
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
1284
+					EEH_HTML::td($registration->ID()) .
1285
+					EEH_HTML::td($attendee_name) .
1286
+					EEH_HTML::td(
1287
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1288
+					) .
1289
+					EEH_HTML::td($registration->event_name()) .
1290
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1291
+					EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1292
+					EEH_HTML::td(
1293
+						'<input type="checkbox" value="' . $registration->ID()
1294
+						. '" name="txn_admin_payment[registrations]"'
1295
+						. $checked . $disabled . '>',
1296
+						'',
1297
+						'jst-cntr'
1298
+					),
1299
+					'apply-payment-registration-row-' . $registration->ID()
1300
+				);
1301
+			}
1302
+		}
1303
+		$registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1304
+		$registrations_to_apply_payment_to .= EEH_HTML::tablex();
1305
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1306
+		$registrations_to_apply_payment_to .= EEH_HTML::p(
1307
+			esc_html__(
1308
+				'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1309
+				'event_espresso'
1310
+			),
1311
+			'',
1312
+			'clear description'
1313
+		);
1314
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1315
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * _get_reg_status_selection
1321
+	 *
1322
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1323
+	 *         instead of events.
1324
+	 * @access protected
1325
+	 * @return void
1326
+	 * @throws EE_Error
1327
+	 */
1328
+	protected function _get_reg_status_selection()
1329
+	{
1330
+		// first get all possible statuses
1331
+		$statuses = EEM_Registration::reg_status_array(array(), true);
1332
+		// let's add a "don't change" option.
1333
+		$status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1334
+		$status_array = array_merge($status_array, $statuses);
1335
+		$this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1336
+			'txn_reg_status_change[reg_status]',
1337
+			$status_array,
1338
+			'NAN',
1339
+			'id="txn-admin-payment-reg-status-inp"',
1340
+			'txn-reg-status-change-reg-status'
1341
+		);
1342
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1343
+			'delete_txn_reg_status_change[reg_status]',
1344
+			$status_array,
1345
+			'NAN',
1346
+			'delete-txn-admin-payment-reg-status-inp',
1347
+			'delete-txn-reg-status-change-reg-status'
1348
+		);
1349
+	}
1350
+
1351
+
1352
+	/**
1353
+	 *    _get_payment_methods
1354
+	 * Gets all the payment methods available generally, or the ones that are already
1355
+	 * selected on these payments (in case their payment methods are no longer active).
1356
+	 * Has the side-effect of updating the template args' payment_methods item
1357
+	 *
1358
+	 * @access private
1359
+	 * @param EE_Payment[] to show on this page
1360
+	 * @return void
1361
+	 * @throws EE_Error
1362
+	 * @throws InvalidArgumentException
1363
+	 * @throws InvalidDataTypeException
1364
+	 * @throws InvalidInterfaceException
1365
+	 * @throws ReflectionException
1366
+	 */
1367
+	private function _get_payment_methods($payments = array())
1368
+	{
1369
+		$payment_methods_of_payments = array();
1370
+		foreach ($payments as $payment) {
1371
+			if ($payment instanceof EE_Payment) {
1372
+				$payment_methods_of_payments[] = $payment->get('PMD_ID');
1373
+			}
1374
+		}
1375
+		if ($payment_methods_of_payments) {
1376
+			$query_args = array(
1377
+				array(
1378
+					'OR*payment_method_for_payment' => array(
1379
+						'PMD_ID'    => array('IN', $payment_methods_of_payments),
1380
+						'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1381
+					),
1382
+				),
1383
+			);
1384
+		} else {
1385
+			$query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1386
+		}
1387
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1388
+	}
1389
+
1390
+
1391
+	/**
1392
+	 * txn_attendees_meta_box
1393
+	 *    generates HTML for the Attendees Transaction main meta box
1394
+	 *
1395
+	 * @access public
1396
+	 * @param WP_Post $post
1397
+	 * @param array   $metabox
1398
+	 * @return void
1399
+	 * @throws DomainException
1400
+	 * @throws EE_Error
1401
+	 */
1402
+	public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1403
+	{
1404
+
1405
+		/** @noinspection NonSecureExtractUsageInspection */
1406
+		extract($metabox['args']);
1407
+		$this->_template_args['post'] = $post;
1408
+		$this->_template_args['event_attendees'] = array();
1409
+		// process items in cart
1410
+		$line_items = $this->_transaction->get_many_related(
1411
+			'Line_Item',
1412
+			array(array('LIN_type' => 'line-item'))
1413
+		);
1414
+		if (! empty($line_items)) {
1415
+			foreach ($line_items as $item) {
1416
+				if ($item instanceof EE_Line_Item) {
1417
+					switch ($item->OBJ_type()) {
1418
+						case 'Event':
1419
+							break;
1420
+						case 'Ticket':
1421
+							$ticket = $item->ticket();
1422
+							// right now we're only handling tickets here.
1423
+							// Cause its expected that only tickets will have attendees right?
1424
+							if (! $ticket instanceof EE_Ticket) {
1425
+								continue;
1426
+							}
1427
+							try {
1428
+								$event_name = $ticket->get_event_name();
1429
+							} catch (Exception $e) {
1430
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1431
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1432
+							}
1433
+							$event_name .= ' - ' . $item->get('LIN_name');
1434
+							$ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1435
+							// now get all of the registrations for this transaction that use this ticket
1436
+							$registrations = $ticket->get_many_related(
1437
+								'Registration',
1438
+								array(array('TXN_ID' => $this->_transaction->ID()))
1439
+							);
1440
+							foreach ($registrations as $registration) {
1441
+								if (! $registration instanceof EE_Registration) {
1442
+									continue;
1443
+								}
1444
+								$this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1445
+									= $registration->status_ID();
1446
+								$this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1447
+									= $registration->count();
1448
+								$this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1449
+									= $event_name;
1450
+								$this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1451
+									= $ticket_price;
1452
+								// attendee info
1453
+								$attendee = $registration->get_first_related('Attendee');
1454
+								if ($attendee instanceof EE_Attendee) {
1455
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1456
+										= $attendee->ID();
1457
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1458
+										= $attendee->full_name();
1459
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']
1460
+										= '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1461
+										  . esc_html__(
1462
+											  ' Event',
1463
+											  'event_espresso'
1464
+										  )
1465
+										  . '">' . $attendee->email() . '</a>';
1466
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']
1467
+										= EEH_Address::format($attendee, 'inline', false, false);
1468
+								} else {
1469
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1470
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1471
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1472
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1473
+								}
1474
+							}
1475
+							break;
1476
+					}
1477
+				}
1478
+			}
1479
+
1480
+			$this->_template_args['transaction_form_url'] = add_query_arg(
1481
+				array(
1482
+					'action'  => 'edit_transaction',
1483
+					'process' => 'attendees',
1484
+				),
1485
+				TXN_ADMIN_URL
1486
+			);
1487
+			echo EEH_Template::display_template(
1488
+				TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1489
+				$this->_template_args,
1490
+				true
1491
+			);
1492
+		} else {
1493
+			echo sprintf(
1494
+				esc_html__(
1495
+					'%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1496
+					'event_espresso'
1497
+				),
1498
+				'<p class="important-notice">',
1499
+				'</p>'
1500
+			);
1501
+		}
1502
+	}
1503
+
1504
+
1505
+	/**
1506
+	 * txn_registrant_side_meta_box
1507
+	 * generates HTML for the Edit Transaction side meta box
1508
+	 *
1509
+	 * @access public
1510
+	 * @return void
1511
+	 * @throws DomainException
1512
+	 * @throws EE_Error
1513
+	 * @throws InvalidArgumentException
1514
+	 * @throws InvalidDataTypeException
1515
+	 * @throws InvalidInterfaceException
1516
+	 * @throws ReflectionException
1517
+	 */
1518
+	public function txn_registrant_side_meta_box()
1519
+	{
1520
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1521
+			? $this->_transaction->primary_registration()->get_first_related('Attendee')
1522
+			: null;
1523
+		if (! $primary_att instanceof EE_Attendee) {
1524
+			$this->_template_args['no_attendee_message'] = esc_html__(
1525
+				'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1526
+				'event_espresso'
1527
+			);
1528
+			$primary_att = EEM_Attendee::instance()->create_default_object();
1529
+		}
1530
+		$this->_template_args['ATT_ID'] = $primary_att->ID();
1531
+		$this->_template_args['prime_reg_fname'] = $primary_att->fname();
1532
+		$this->_template_args['prime_reg_lname'] = $primary_att->lname();
1533
+		$this->_template_args['prime_reg_email'] = $primary_att->email();
1534
+		$this->_template_args['prime_reg_phone'] = $primary_att->phone();
1535
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1536
+			array(
1537
+				'action' => 'edit_attendee',
1538
+				'post'   => $primary_att->ID(),
1539
+			),
1540
+			REG_ADMIN_URL
1541
+		);
1542
+		// get formatted address for registrant
1543
+		$this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1544
+		echo EEH_Template::display_template(
1545
+			TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1546
+			$this->_template_args,
1547
+			true
1548
+		);
1549
+	}
1550
+
1551
+
1552
+	/**
1553
+	 * txn_billing_info_side_meta_box
1554
+	 *    generates HTML for the Edit Transaction side meta box
1555
+	 *
1556
+	 * @access public
1557
+	 * @return void
1558
+	 * @throws DomainException
1559
+	 * @throws EE_Error
1560
+	 */
1561
+	public function txn_billing_info_side_meta_box()
1562
+	{
1563
+
1564
+		$this->_template_args['billing_form'] = $this->_transaction->billing_info();
1565
+		$this->_template_args['billing_form_url'] = add_query_arg(
1566
+			array('action' => 'edit_transaction', 'process' => 'billing'),
1567
+			TXN_ADMIN_URL
1568
+		);
1569
+
1570
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1571
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1572
+	}
1573
+
1574
+
1575
+	/**
1576
+	 * apply_payments_or_refunds
1577
+	 *    registers a payment or refund made towards a transaction
1578
+	 *
1579
+	 * @access public
1580
+	 * @return void
1581
+	 * @throws EE_Error
1582
+	 * @throws InvalidArgumentException
1583
+	 * @throws ReflectionException
1584
+	 * @throws RuntimeException
1585
+	 * @throws InvalidDataTypeException
1586
+	 * @throws InvalidInterfaceException
1587
+	 */
1588
+	public function apply_payments_or_refunds()
1589
+	{
1590
+		$json_response_data = array('return_data' => false);
1591
+		$valid_data = $this->_validate_payment_request_data();
1592
+		$has_access = EE_Registry::instance()->CAP->current_user_can(
1593
+			'ee_edit_payments',
1594
+			'apply_payment_or_refund_from_registration_details'
1595
+		);
1596
+		if (! empty($valid_data) && $has_access) {
1597
+			$PAY_ID = $valid_data['PAY_ID'];
1598
+			// save  the new payment
1599
+			$payment = $this->_create_payment_from_request_data($valid_data);
1600
+			// get the TXN for this payment
1601
+			$transaction = $payment->transaction();
1602
+			// verify transaction
1603
+			if ($transaction instanceof EE_Transaction) {
1604
+				// calculate_total_payments_and_update_status
1605
+				$this->_process_transaction_payments($transaction);
1606
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1607
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1608
+				// apply payment to registrations (if applicable)
1609
+				if (! empty($REG_IDs)) {
1610
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1611
+					$this->_maybe_send_notifications();
1612
+					// now process status changes for the same registrations
1613
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1614
+				}
1615
+				$this->_maybe_send_notifications($payment);
1616
+				// prepare to render page
1617
+				$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1618
+				do_action(
1619
+					'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1620
+					$transaction,
1621
+					$payment
1622
+				);
1623
+			} else {
1624
+				EE_Error::add_error(
1625
+					esc_html__(
1626
+						'A valid Transaction for this payment could not be retrieved.',
1627
+						'event_espresso'
1628
+					),
1629
+					__FILE__,
1630
+					__FUNCTION__,
1631
+					__LINE__
1632
+				);
1633
+			}
1634
+		} else {
1635
+			if ($has_access) {
1636
+				EE_Error::add_error(
1637
+					esc_html__(
1638
+						'The payment form data could not be processed. Please try again.',
1639
+						'event_espresso'
1640
+					),
1641
+					__FILE__,
1642
+					__FUNCTION__,
1643
+					__LINE__
1644
+				);
1645
+			} else {
1646
+				EE_Error::add_error(
1647
+					esc_html__(
1648
+						'You do not have access to apply payments or refunds to a registration.',
1649
+						'event_espresso'
1650
+					),
1651
+					__FILE__,
1652
+					__FUNCTION__,
1653
+					__LINE__
1654
+				);
1655
+			}
1656
+		}
1657
+		$notices = EE_Error::get_notices(
1658
+			false,
1659
+			false,
1660
+			false
1661
+		);
1662
+		$this->_template_args = array(
1663
+			'data'    => $json_response_data,
1664
+			'error'   => $notices['errors'],
1665
+			'success' => $notices['success'],
1666
+		);
1667
+		$this->_return_json();
1668
+	}
1669
+
1670
+
1671
+	/**
1672
+	 * _validate_payment_request_data
1673
+	 *
1674
+	 * @return array
1675
+	 * @throws EE_Error
1676
+	 */
1677
+	protected function _validate_payment_request_data()
1678
+	{
1679
+		if (! isset($this->_req_data['txn_admin_payment'])) {
1680
+			return false;
1681
+		}
1682
+		$payment_form = $this->_generate_payment_form_section();
1683
+		try {
1684
+			if ($payment_form->was_submitted()) {
1685
+				$payment_form->receive_form_submission();
1686
+				if (! $payment_form->is_valid()) {
1687
+					$submission_error_messages = array();
1688
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1689
+						if ($validation_error instanceof EE_Validation_Error) {
1690
+							$submission_error_messages[] = sprintf(
1691
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1692
+								$validation_error->get_form_section()->html_label_text(),
1693
+								$validation_error->getMessage()
1694
+							);
1695
+						}
1696
+					}
1697
+					EE_Error::add_error(
1698
+						implode('<br />', $submission_error_messages),
1699
+						__FILE__,
1700
+						__FUNCTION__,
1701
+						__LINE__
1702
+					);
1703
+
1704
+					return array();
1705
+				}
1706
+			}
1707
+		} catch (EE_Error $e) {
1708
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1709
+
1710
+			return array();
1711
+		}
1712
+
1713
+		return $payment_form->valid_data();
1714
+	}
1715
+
1716
+
1717
+	/**
1718
+	 * _generate_payment_form_section
1719
+	 *
1720
+	 * @return EE_Form_Section_Proper
1721
+	 * @throws EE_Error
1722
+	 */
1723
+	protected function _generate_payment_form_section()
1724
+	{
1725
+		return new EE_Form_Section_Proper(
1726
+			array(
1727
+				'name'        => 'txn_admin_payment',
1728
+				'subsections' => array(
1729
+					'PAY_ID'          => new EE_Text_Input(
1730
+						array(
1731
+							'default'               => 0,
1732
+							'required'              => false,
1733
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1734
+							'validation_strategies' => array(new EE_Int_Normalization()),
1735
+						)
1736
+					),
1737
+					'TXN_ID'          => new EE_Text_Input(
1738
+						array(
1739
+							'default'               => 0,
1740
+							'required'              => true,
1741
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1742
+							'validation_strategies' => array(new EE_Int_Normalization()),
1743
+						)
1744
+					),
1745
+					'type'            => new EE_Text_Input(
1746
+						array(
1747
+							'default'               => 1,
1748
+							'required'              => true,
1749
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1750
+							'validation_strategies' => array(new EE_Int_Normalization()),
1751
+						)
1752
+					),
1753
+					'amount'          => new EE_Text_Input(
1754
+						array(
1755
+							'default'               => 0,
1756
+							'required'              => true,
1757
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1758
+							'validation_strategies' => array(new EE_Float_Normalization()),
1759
+						)
1760
+					),
1761
+					'status'          => new EE_Text_Input(
1762
+						array(
1763
+							'default'         => EEM_Payment::status_id_approved,
1764
+							'required'        => true,
1765
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1766
+						)
1767
+					),
1768
+					'PMD_ID'          => new EE_Text_Input(
1769
+						array(
1770
+							'default'               => 2,
1771
+							'required'              => true,
1772
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1773
+							'validation_strategies' => array(new EE_Int_Normalization()),
1774
+						)
1775
+					),
1776
+					'date'            => new EE_Text_Input(
1777
+						array(
1778
+							'default'         => time(),
1779
+							'required'        => true,
1780
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1781
+						)
1782
+					),
1783
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1784
+						array(
1785
+							'default'               => '',
1786
+							'required'              => false,
1787
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1788
+							'validation_strategies' => array(
1789
+								new EE_Max_Length_Validation_Strategy(
1790
+									esc_html__('Input too long', 'event_espresso'),
1791
+									100
1792
+								),
1793
+							),
1794
+						)
1795
+					),
1796
+					'po_number'       => new EE_Text_Input(
1797
+						array(
1798
+							'default'               => '',
1799
+							'required'              => false,
1800
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1801
+							'validation_strategies' => array(
1802
+								new EE_Max_Length_Validation_Strategy(
1803
+									esc_html__('Input too long', 'event_espresso'),
1804
+									100
1805
+								),
1806
+							),
1807
+						)
1808
+					),
1809
+					'accounting'      => new EE_Text_Input(
1810
+						array(
1811
+							'default'               => '',
1812
+							'required'              => false,
1813
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1814
+							'validation_strategies' => array(
1815
+								new EE_Max_Length_Validation_Strategy(
1816
+									esc_html__('Input too long', 'event_espresso'),
1817
+									100
1818
+								),
1819
+							),
1820
+						)
1821
+					),
1822
+				),
1823
+			)
1824
+		);
1825
+	}
1826
+
1827
+
1828
+	/**
1829
+	 * _create_payment_from_request_data
1830
+	 *
1831
+	 * @param array $valid_data
1832
+	 * @return EE_Payment
1833
+	 * @throws EE_Error
1834
+	 */
1835
+	protected function _create_payment_from_request_data($valid_data)
1836
+	{
1837
+		$PAY_ID = $valid_data['PAY_ID'];
1838
+		// get payment amount
1839
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1840
+		// payments have a type value of 1 and refunds have a type value of -1
1841
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1842
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1843
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1844
+		$date = $valid_data['date']
1845
+			? preg_replace('/\s+/', ' ', $valid_data['date'])
1846
+			: date('Y-m-d g:i a', current_time('timestamp'));
1847
+		$payment = EE_Payment::new_instance(
1848
+			array(
1849
+				'TXN_ID'              => $valid_data['TXN_ID'],
1850
+				'STS_ID'              => $valid_data['status'],
1851
+				'PAY_timestamp'       => $date,
1852
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1853
+				'PMD_ID'              => $valid_data['PMD_ID'],
1854
+				'PAY_amount'          => $amount,
1855
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1856
+				'PAY_po_number'       => $valid_data['po_number'],
1857
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1858
+				'PAY_details'         => $valid_data,
1859
+				'PAY_ID'              => $PAY_ID,
1860
+			),
1861
+			'',
1862
+			array('Y-m-d', 'g:i a')
1863
+		);
1864
+
1865
+		if (! $payment->save()) {
1866
+			EE_Error::add_error(
1867
+				sprintf(
1868
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1869
+					$payment->ID()
1870
+				),
1871
+				__FILE__,
1872
+				__FUNCTION__,
1873
+				__LINE__
1874
+			);
1875
+		}
1876
+
1877
+		return $payment;
1878
+	}
1879
+
1880
+
1881
+	/**
1882
+	 * _process_transaction_payments
1883
+	 *
1884
+	 * @param \EE_Transaction $transaction
1885
+	 * @return void
1886
+	 * @throws EE_Error
1887
+	 * @throws InvalidArgumentException
1888
+	 * @throws ReflectionException
1889
+	 * @throws InvalidDataTypeException
1890
+	 * @throws InvalidInterfaceException
1891
+	 */
1892
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1893
+	{
1894
+		/** @type EE_Transaction_Payments $transaction_payments */
1895
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1896
+		// update the transaction with this payment
1897
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1898
+			EE_Error::add_success(
1899
+				esc_html__(
1900
+					'The payment has been processed successfully.',
1901
+					'event_espresso'
1902
+				),
1903
+				__FILE__,
1904
+				__FUNCTION__,
1905
+				__LINE__
1906
+			);
1907
+		} else {
1908
+			EE_Error::add_error(
1909
+				esc_html__(
1910
+					'The payment was processed successfully but the amount paid for the transaction was not updated.',
1911
+					'event_espresso'
1912
+				),
1913
+				__FILE__,
1914
+				__FUNCTION__,
1915
+				__LINE__
1916
+			);
1917
+		}
1918
+	}
1919
+
1920
+
1921
+	/**
1922
+	 * _get_REG_IDs_to_apply_payment_to
1923
+	 * returns a list of registration IDs that the payment will apply to
1924
+	 *
1925
+	 * @param \EE_Payment $payment
1926
+	 * @return array
1927
+	 * @throws EE_Error
1928
+	 */
1929
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1930
+	{
1931
+		$REG_IDs = array();
1932
+		// grab array of IDs for specific registrations to apply changes to
1933
+		if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1934
+			$REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1935
+		}
1936
+		// nothing specified ? then get all reg IDs
1937
+		if (empty($REG_IDs)) {
1938
+			$registrations = $payment->transaction()->registrations();
1939
+			$REG_IDs = ! empty($registrations)
1940
+				? array_keys($registrations)
1941
+				: $this->_get_existing_reg_payment_REG_IDs($payment);
1942
+		}
1943
+
1944
+		// ensure that REG_IDs are integers and NOT strings
1945
+		return array_map('intval', $REG_IDs);
1946
+	}
1947
+
1948
+
1949
+	/**
1950
+	 * @return array
1951
+	 */
1952
+	public function existing_reg_payment_REG_IDs()
1953
+	{
1954
+		return $this->_existing_reg_payment_REG_IDs;
1955
+	}
1956
+
1957
+
1958
+	/**
1959
+	 * @param array $existing_reg_payment_REG_IDs
1960
+	 */
1961
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1962
+	{
1963
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1964
+	}
1965
+
1966
+
1967
+	/**
1968
+	 * _get_existing_reg_payment_REG_IDs
1969
+	 * returns a list of registration IDs that the payment is currently related to
1970
+	 * as recorded in the database
1971
+	 *
1972
+	 * @param \EE_Payment $payment
1973
+	 * @return array
1974
+	 * @throws EE_Error
1975
+	 */
1976
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1977
+	{
1978
+		if ($this->existing_reg_payment_REG_IDs() === null) {
1979
+			// let's get any existing reg payment records for this payment
1980
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1981
+			// but we only want the REG IDs, so grab the array keys
1982
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1983
+				? array_keys($existing_reg_payment_REG_IDs)
1984
+				: array();
1985
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1986
+		}
1987
+
1988
+		return $this->existing_reg_payment_REG_IDs();
1989
+	}
1990
+
1991
+
1992
+	/**
1993
+	 * _remove_existing_registration_payments
1994
+	 * this calculates the difference between existing relations
1995
+	 * to the supplied payment and the new list registration IDs,
1996
+	 * removes any related registrations that no longer apply,
1997
+	 * and then updates the registration paid fields
1998
+	 *
1999
+	 * @param \EE_Payment $payment
2000
+	 * @param int         $PAY_ID
2001
+	 * @return bool;
2002
+	 * @throws EE_Error
2003
+	 * @throws InvalidArgumentException
2004
+	 * @throws ReflectionException
2005
+	 * @throws InvalidDataTypeException
2006
+	 * @throws InvalidInterfaceException
2007
+	 */
2008
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2009
+	{
2010
+		// newly created payments will have nothing recorded for $PAY_ID
2011
+		if ($PAY_ID == 0) {
2012
+			return false;
2013
+		}
2014
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2015
+		if (empty($existing_reg_payment_REG_IDs)) {
2016
+			return false;
2017
+		}
2018
+		/** @type EE_Transaction_Payments $transaction_payments */
2019
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2020
+
2021
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
2022
+			$payment,
2023
+			array(
2024
+				array(
2025
+					'PAY_ID' => $payment->ID(),
2026
+					'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2027
+				),
2028
+			)
2029
+		);
2030
+	}
2031
+
2032
+
2033
+	/**
2034
+	 * _update_registration_payments
2035
+	 * this applies the payments to the selected registrations
2036
+	 * but only if they have not already been paid for
2037
+	 *
2038
+	 * @param  EE_Transaction $transaction
2039
+	 * @param \EE_Payment     $payment
2040
+	 * @param array           $REG_IDs
2041
+	 * @return void
2042
+	 * @throws EE_Error
2043
+	 * @throws InvalidArgumentException
2044
+	 * @throws ReflectionException
2045
+	 * @throws RuntimeException
2046
+	 * @throws InvalidDataTypeException
2047
+	 * @throws InvalidInterfaceException
2048
+	 */
2049
+	protected function _update_registration_payments(
2050
+		EE_Transaction $transaction,
2051
+		EE_Payment $payment,
2052
+		$REG_IDs = array()
2053
+	) {
2054
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2055
+		// so let's do that using our set of REG_IDs from the form
2056
+		$registration_query_where_params = array(
2057
+			'REG_ID' => array('IN', $REG_IDs),
2058
+		);
2059
+		// but add in some conditions regarding payment,
2060
+		// so that we don't apply payments to registrations that are free or have already been paid for
2061
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2062
+		if (! $payment->is_a_refund()) {
2063
+			$registration_query_where_params['REG_final_price'] = array('!=', 0);
2064
+			$registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2065
+		}
2066
+		$registrations = $transaction->registrations(array($registration_query_where_params));
2067
+		if (! empty($registrations)) {
2068
+			/** @type EE_Payment_Processor $payment_processor */
2069
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2070
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
2071
+		}
2072
+	}
2073
+
2074
+
2075
+	/**
2076
+	 * _process_registration_status_change
2077
+	 * This processes requested registration status changes for all the registrations
2078
+	 * on a given transaction and (optionally) sends out notifications for the changes.
2079
+	 *
2080
+	 * @param  EE_Transaction $transaction
2081
+	 * @param array           $REG_IDs
2082
+	 * @return bool
2083
+	 * @throws EE_Error
2084
+	 * @throws InvalidArgumentException
2085
+	 * @throws ReflectionException
2086
+	 * @throws InvalidDataTypeException
2087
+	 * @throws InvalidInterfaceException
2088
+	 */
2089
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2090
+	{
2091
+		// first if there is no change in status then we get out.
2092
+		if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2093
+			|| $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2094
+		) {
2095
+			// no error message, no change requested, just nothing to do man.
2096
+			return false;
2097
+		}
2098
+		/** @type EE_Transaction_Processor $transaction_processor */
2099
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2100
+
2101
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2102
+		return $transaction_processor->manually_update_registration_statuses(
2103
+			$transaction,
2104
+			sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2105
+			array(array('REG_ID' => array('IN', $REG_IDs)))
2106
+		);
2107
+	}
2108
+
2109
+
2110
+	/**
2111
+	 * _build_payment_json_response
2112
+	 *
2113
+	 * @access public
2114
+	 * @param \EE_Payment $payment
2115
+	 * @param array       $REG_IDs
2116
+	 * @param bool | null $delete_txn_reg_status_change
2117
+	 * @return array
2118
+	 * @throws EE_Error
2119
+	 * @throws InvalidArgumentException
2120
+	 * @throws InvalidDataTypeException
2121
+	 * @throws InvalidInterfaceException
2122
+	 * @throws ReflectionException
2123
+	 */
2124
+	protected function _build_payment_json_response(
2125
+		EE_Payment $payment,
2126
+		$REG_IDs = array(),
2127
+		$delete_txn_reg_status_change = null
2128
+	) {
2129
+		// was the payment deleted ?
2130
+		if (is_bool($delete_txn_reg_status_change)) {
2131
+			return array(
2132
+				'PAY_ID'                       => $payment->ID(),
2133
+				'amount'                       => $payment->amount(),
2134
+				'total_paid'                   => $payment->transaction()->paid(),
2135
+				'txn_status'                   => $payment->transaction()->status_ID(),
2136
+				'pay_status'                   => $payment->STS_ID(),
2137
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2138
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2139
+			);
2140
+		} else {
2141
+			$this->_get_payment_status_array();
2142
+
2143
+			return array(
2144
+				'amount'           => $payment->amount(),
2145
+				'total_paid'       => $payment->transaction()->paid(),
2146
+				'txn_status'       => $payment->transaction()->status_ID(),
2147
+				'pay_status'       => $payment->STS_ID(),
2148
+				'PAY_ID'           => $payment->ID(),
2149
+				'STS_ID'           => $payment->STS_ID(),
2150
+				'status'           => self::$_pay_status[ $payment->STS_ID() ],
2151
+				'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2152
+				'method'           => strtoupper($payment->source()),
2153
+				'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2154
+				'gateway'          => $payment->payment_method()
2155
+					? $payment->payment_method()->admin_name()
2156
+					: esc_html__("Unknown", 'event_espresso'),
2157
+				'gateway_response' => $payment->gateway_response(),
2158
+				'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2159
+				'po_number'        => $payment->po_number(),
2160
+				'extra_accntng'    => $payment->extra_accntng(),
2161
+				'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2162
+			);
2163
+		}
2164
+	}
2165
+
2166
+
2167
+	/**
2168
+	 * delete_payment
2169
+	 *    delete a payment or refund made towards a transaction
2170
+	 *
2171
+	 * @access public
2172
+	 * @return void
2173
+	 * @throws EE_Error
2174
+	 * @throws InvalidArgumentException
2175
+	 * @throws ReflectionException
2176
+	 * @throws InvalidDataTypeException
2177
+	 * @throws InvalidInterfaceException
2178
+	 */
2179
+	public function delete_payment()
2180
+	{
2181
+		$json_response_data = array('return_data' => false);
2182
+		$PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2183
+			? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2184
+			: 0;
2185
+		$can_delete = EE_Registry::instance()->CAP->current_user_can(
2186
+			'ee_delete_payments',
2187
+			'delete_payment_from_registration_details'
2188
+		);
2189
+		if ($PAY_ID && $can_delete) {
2190
+			$delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2191
+				? $this->_req_data['delete_txn_reg_status_change']
2192
+				: false;
2193
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2194
+			if ($payment instanceof EE_Payment) {
2195
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2196
+				/** @type EE_Transaction_Payments $transaction_payments */
2197
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2198
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2199
+					$json_response_data['return_data'] = $this->_build_payment_json_response(
2200
+						$payment,
2201
+						$REG_IDs,
2202
+						$delete_txn_reg_status_change
2203
+					);
2204
+					if ($delete_txn_reg_status_change) {
2205
+						$this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2206
+						// MAKE sure we also add the delete_txn_req_status_change to the
2207
+						// $_REQUEST global because that's how messages will be looking for it.
2208
+						$_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2209
+						$this->_maybe_send_notifications();
2210
+						$this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2211
+					}
2212
+				}
2213
+			} else {
2214
+				EE_Error::add_error(
2215
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2216
+					__FILE__,
2217
+					__FUNCTION__,
2218
+					__LINE__
2219
+				);
2220
+			}
2221
+		} else {
2222
+			if ($can_delete) {
2223
+				EE_Error::add_error(
2224
+					esc_html__(
2225
+						'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2226
+						'event_espresso'
2227
+					),
2228
+					__FILE__,
2229
+					__FUNCTION__,
2230
+					__LINE__
2231
+				);
2232
+			} else {
2233
+				EE_Error::add_error(
2234
+					esc_html__(
2235
+						'You do not have access to delete a payment.',
2236
+						'event_espresso'
2237
+					),
2238
+					__FILE__,
2239
+					__FUNCTION__,
2240
+					__LINE__
2241
+				);
2242
+			}
2243
+		}
2244
+		$notices = EE_Error::get_notices(false, false, false);
2245
+		$this->_template_args = array(
2246
+			'data'      => $json_response_data,
2247
+			'success'   => $notices['success'],
2248
+			'error'     => $notices['errors'],
2249
+			'attention' => $notices['attention'],
2250
+		);
2251
+		$this->_return_json();
2252
+	}
2253
+
2254
+
2255
+	/**
2256
+	 * _registration_payment_data_array
2257
+	 * adds info for 'owing' and 'paid' for each registration to the json response
2258
+	 *
2259
+	 * @access protected
2260
+	 * @param array $REG_IDs
2261
+	 * @return array
2262
+	 * @throws EE_Error
2263
+	 * @throws InvalidArgumentException
2264
+	 * @throws InvalidDataTypeException
2265
+	 * @throws InvalidInterfaceException
2266
+	 * @throws ReflectionException
2267
+	 */
2268
+	protected function _registration_payment_data_array($REG_IDs)
2269
+	{
2270
+		$registration_payment_data = array();
2271
+		// if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2272
+		if (! empty($REG_IDs)) {
2273
+			$registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2274
+			foreach ($registrations as $registration) {
2275
+				if ($registration instanceof EE_Registration) {
2276
+					$registration_payment_data[ $registration->ID() ] = array(
2277
+						'paid'  => $registration->pretty_paid(),
2278
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2279
+					);
2280
+				}
2281
+			}
2282
+		}
2283
+
2284
+		return $registration_payment_data;
2285
+	}
2286
+
2287
+
2288
+	/**
2289
+	 * _maybe_send_notifications
2290
+	 * determines whether or not the admin has indicated that notifications should be sent.
2291
+	 * If so, will toggle a filter switch for delivering registration notices.
2292
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
2293
+	 *
2294
+	 * @access protected
2295
+	 * @param \EE_Payment | null $payment
2296
+	 */
2297
+	protected function _maybe_send_notifications($payment = null)
2298
+	{
2299
+		switch ($payment instanceof EE_Payment) {
2300
+			// payment notifications
2301
+			case true:
2302
+				if (isset(
2303
+					$this->_req_data['txn_payments'],
2304
+					$this->_req_data['txn_payments']['send_notifications']
2305
+				)
2306
+					&& filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2307
+				) {
2308
+					$this->_process_payment_notification($payment);
2309
+				}
2310
+				break;
2311
+			// registration notifications
2312
+			case false:
2313
+				if (isset(
2314
+					$this->_req_data['txn_reg_status_change'],
2315
+					$this->_req_data['txn_reg_status_change']['send_notifications']
2316
+				)
2317
+					&& filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2318
+				) {
2319
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2320
+				}
2321
+				break;
2322
+		}
2323
+	}
2324
+
2325
+
2326
+	/**
2327
+	 * _send_payment_reminder
2328
+	 *    generates HTML for the View Transaction Details Admin page
2329
+	 *
2330
+	 * @access protected
2331
+	 * @return void
2332
+	 * @throws EE_Error
2333
+	 * @throws InvalidArgumentException
2334
+	 * @throws InvalidDataTypeException
2335
+	 * @throws InvalidInterfaceException
2336
+	 */
2337
+	protected function _send_payment_reminder()
2338
+	{
2339
+		$TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2340
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2341
+		$query_args = isset($this->_req_data['redirect_to']) ? array(
2342
+			'action' => $this->_req_data['redirect_to'],
2343
+			'TXN_ID' => $this->_req_data['TXN_ID'],
2344
+		) : array();
2345
+		do_action(
2346
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2347
+			$transaction
2348
+		);
2349
+		$this->_redirect_after_action(
2350
+			false,
2351
+			esc_html__('payment reminder', 'event_espresso'),
2352
+			esc_html__('sent', 'event_espresso'),
2353
+			$query_args,
2354
+			true
2355
+		);
2356
+	}
2357
+
2358
+
2359
+	/**
2360
+	 *  get_transactions
2361
+	 *    get transactions for given parameters (used by list table)
2362
+	 *
2363
+	 * @param  int     $perpage how many transactions displayed per page
2364
+	 * @param  boolean $count   return the count or objects
2365
+	 * @param string   $view
2366
+	 * @return mixed int = count || array of transaction objects
2367
+	 * @throws EE_Error
2368
+	 * @throws InvalidArgumentException
2369
+	 * @throws InvalidDataTypeException
2370
+	 * @throws InvalidInterfaceException
2371
+	 */
2372
+	public function get_transactions($perpage, $count = false, $view = '')
2373
+	{
2374
+
2375
+		$TXN = EEM_Transaction::instance();
2376
+
2377
+		$start_date = isset($this->_req_data['txn-filter-start-date'])
2378
+			? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2379
+			: date(
2380
+				'm/d/Y',
2381
+				strtotime('-10 year')
2382
+			);
2383
+		$end_date = isset($this->_req_data['txn-filter-end-date'])
2384
+			? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2385
+			: date('m/d/Y');
2386
+
2387
+		// make sure our timestamps start and end right at the boundaries for each day
2388
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2389
+		$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2390
+
2391
+
2392
+		// convert to timestamps
2393
+		$start_date = strtotime($start_date);
2394
+		$end_date = strtotime($end_date);
2395
+
2396
+		// makes sure start date is the lowest value and vice versa
2397
+		$start_date = min($start_date, $end_date);
2398
+		$end_date = max($start_date, $end_date);
2399
+
2400
+		// convert to correct format for query
2401
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2402
+			'TXN_timestamp',
2403
+			date('Y-m-d H:i:s', $start_date),
2404
+			'Y-m-d H:i:s'
2405
+		);
2406
+		$end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2407
+			'TXN_timestamp',
2408
+			date('Y-m-d H:i:s', $end_date),
2409
+			'Y-m-d H:i:s'
2410
+		);
2411
+
2412
+
2413
+		// set orderby
2414
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2415
+
2416
+		switch ($this->_req_data['orderby']) {
2417
+			case 'TXN_ID':
2418
+				$orderby = 'TXN_ID';
2419
+				break;
2420
+			case 'ATT_fname':
2421
+				$orderby = 'Registration.Attendee.ATT_fname';
2422
+				break;
2423
+			case 'event_name':
2424
+				$orderby = 'Registration.Event.EVT_name';
2425
+				break;
2426
+			default: // 'TXN_timestamp'
2427
+				$orderby = 'TXN_timestamp';
2428
+		}
2429
+
2430
+		$sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2431
+		$current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2432
+		$per_page = ! empty($perpage) ? $perpage : 10;
2433
+		$per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2434
+
2435
+		$offset = ($current_page - 1) * $per_page;
2436
+		$limit = array($offset, $per_page);
2437
+
2438
+		$_where = array(
2439
+			'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2440
+			'Registration.REG_count' => 1,
2441
+		);
2442
+
2443
+		if (isset($this->_req_data['EVT_ID'])) {
2444
+			$_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2445
+		}
2446
+
2447
+		if (isset($this->_req_data['s'])) {
2448
+			$search_string = '%' . $this->_req_data['s'] . '%';
2449
+			$_where['OR'] = array(
2450
+				'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2451
+				'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2452
+				'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2453
+				'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2454
+				'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2455
+				'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2456
+				'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2457
+				'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2458
+				'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2459
+				'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2460
+				'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2461
+				'Registration.REG_final_price'        => array('LIKE', $search_string),
2462
+				'Registration.REG_code'               => array('LIKE', $search_string),
2463
+				'Registration.REG_count'              => array('LIKE', $search_string),
2464
+				'Registration.REG_group_size'         => array('LIKE', $search_string),
2465
+				'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2466
+				'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2467
+				'Payment.PAY_source'                  => array('LIKE', $search_string),
2468
+				'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2469
+				'TXN_session_data'                    => array('LIKE', $search_string),
2470
+				'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2471
+			);
2472
+		}
2473
+
2474
+		// failed transactions
2475
+		$failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2476
+				  || ($count && $view === 'failed');
2477
+		$abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2478
+					 || ($count && $view === 'abandoned');
2479
+
2480
+		if ($failed) {
2481
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
2482
+		} elseif ($abandoned) {
2483
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2484
+		} else {
2485
+			$_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2486
+			$_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2487
+		}
2488
+
2489
+		$query_params = array(
2490
+			$_where,
2491
+			'order_by'                 => array($orderby => $sort),
2492
+			'limit'                    => $limit,
2493
+			'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2494
+		);
2495
+
2496
+		$transactions = $count
2497
+			? $TXN->count(array($_where), 'TXN_ID', true)
2498
+			: $TXN->get_all($query_params);
2499
+
2500
+		return $transactions;
2501
+	}
2502 2502
 }
Please login to merge, or discard this patch.