';
echo self::field_row(array(
'id' => 'aieo-wd-enabled',
'group' => true,
'label' => __('Enable', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::check('enabled', __('Show the withdrawal button and accept declarations.', 'ai-eshop-optimizer'), !empty($s['enabled']), array('id' => 'aieo-wd-enabled')),
));
echo self::field_row(array(
'id' => 'aieo-wd-auto-cancel',
'group' => true,
'label' => __('Let customers cancel instantly', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::check('auto_cancel_enabled', __('Allow a customer to cancel an order themselves while it has not been dispatched.', 'ai-eshop-optimizer'), !empty($s['auto_cancel_enabled']), array('id' => 'aieo-wd-auto-cancel')),
'help' => __('This is a courtesy, not a legal requirement — the law is satisfied by accepting the withdrawal declaration. Switch it off and every withdrawal, however new the order, arrives in your queue for you to handle. Nothing about the statutory 14 days changes either way.', 'ai-eshop-optimizer'),
));
$secs = AIEO_Withdrawal::window_seconds();
if (empty($s['auto_cancel_enabled'])) {
$aieo_wd_total = __('Switched off above — this window is not in use.', 'ai-eshop-optimizer');
} elseif ($secs > 0) {
$aieo_wd_total = sprintf(
__('Customers can cancel themselves for %s after ordering.', 'ai-eshop-optimizer'),
human_time_diff(0, $secs)
);
} else {
$aieo_wd_total = __('Zero: nobody cancels instantly, even though the option above is ticked. Untick it instead, so the next person to read this screen can tell it was decided.', 'ai-eshop-optimizer');
}
echo self::field_row(array(
'id' => 'aieo-wd-window',
'label' => __('Instant-cancel window', 'ai-eshop-optimizer'),
'parts' => array(
array('label' => '', 'id' => 'aieo-wd-window-hours', 'control' => AIEO_Kit::input('window_hours', (string) $s['window_hours'], array('type' => 'number', 'id' => 'aieo-wd-window-hours', 'min' => 0, 'max' => 720, 'step' => 1, 'xs' => true, 'unit' => __('hours', 'ai-eshop-optimizer'), 'aria-label' => __('Instant-cancel window', 'ai-eshop-optimizer') . ', ' . __('hours', 'ai-eshop-optimizer')))),
array('label' => '', 'id' => 'aieo-wd-window-minutes', 'control' => AIEO_Kit::input('window_minutes', (string) $s['window_minutes'], array('type' => 'number', 'id' => 'aieo-wd-window-minutes', 'min' => 0, 'max' => 59, 'step' => 1, 'xs' => true, 'unit' => __('minutes', 'ai-eshop-optimizer'), 'aria-label' => __('Instant-cancel window', 'ai-eshop-optimizer') . ', ' . __('minutes', 'ai-eshop-optimizer')))),
),
'help_html' => esc_html__('While an order is this new AND still has one of the statuses below, the customer cancels it themselves in one click. This is a courtesy you control — it does NOT shorten the statutory 14 days, which apply regardless.', 'ai-eshop-optimizer')
. ' ' . esc_html($aieo_wd_total) . '',
));
$all = function_exists('wc_get_order_statuses') ? wc_get_order_statuses() : array();
$statuses = array();
foreach ($all as $key => $label) {
$slug = preg_replace('/^wc-/', '', $key);
if (in_array($slug, array('cancelled', 'refunded', 'failed'), true)) { continue; }
$statuses[$slug] = (string) $label;
}
echo self::field_row(array(
'id' => 'aieo-wd-statuses',
'group' => true,
'label' => __('Statuses that can still be cancelled', 'ai-eshop-optimizer'),
'control' => ''
. AIEO_Kit::checks('cancel_statuses', $statuses, array_map('strval', (array) $s['cancel_statuses']), array('grid' => true)),
'help' => __('Tick only statuses that mean "has not been dispatched". Anything else falls through to a withdrawal declaration for you to process.', 'ai-eshop-optimizer'),
));
if (class_exists('AIEO_Withdrawal_Rejection_Reasons')) {
$aieo_wd_grounds = '';
foreach (AIEO_Withdrawal_Rejection_Reasons::all() as $rid => $reason) {
$aieo_wd_grounds .= '
'
. ''
. ''
. ''
. '
';
}
$aieo_wd_grounds .= '
'
. ''
. ''
. ''
. '
';
echo self::field_row(array(
'id' => 'aieo-wd-grounds',
'group' => true,
'label' => __('Grounds for refusing a request', 'ai-eshop-optimizer'),
'control' => $aieo_wd_grounds,
'help' => __('Written as the reason itself, with no leading "because" — the notice supplies that once and then lists them, so each line continues the sentence. Untick a ground to retire it without losing refusals already recorded against it: rewording or retiring changes what future notices say, never what past refusals were.', 'ai-eshop-optimizer'),
));
}
$page_id = (int) $s['guest_form_page_id'];
$aieo_wd_pages = (string) wp_dropdown_pages(array(
'name' => 'guest_form_page_id',
'id' => 'aieo-wd-guest-page',
'class' => 'rooster-admin-select',
'selected' => $page_id,
'show_option_none' => __('— not set —', 'ai-eshop-optimizer'),
'option_none_value' => 0,
'echo' => 0,
));
$aieo_wd_pages = '' !== $aieo_wd_pages
? preg_replace('/^
';
echo AIEO_DMM_UI::card_form('aieo_dmm_withdrawal_save', $aieo_wd_group, $aieo_wd_form, (string) ob_get_clean());
echo $aieo_wd_close;
$this->render_notification_settings($s, $aieo_wd_group);
$this->render_return_settings($s, $aieo_wd_group);
if (function_exists('rooster_admin_band_close')) {
rooster_admin_band_close();
}
$this->print_settings_js($nonce);
}
private function render_notification_settings(array $s, $group = 'withdrawal_settings') {
$form_id = 'aieo-card-withdrawal-when-a-declaration-arrives-form';
list($aieo_wd_open, $aieo_wd_close) = AIEO_DMM_UI::card(array(
'anchor' => 'withdrawal-when-a-declaration-arrives',
'icon' => 'mail',
'title' => __('When a declaration arrives', 'ai-eshop-optimizer'),
'description' => __('Auto-cancelled orders announce themselves — they turn to "Cancelled" and WooCommerce emails you. A declaration that needs processing used to leave only a private order note; these two make it land where your staff actually look.', 'ai-eshop-optimizer'),
'footer' => \Rooster\Admin\States::save_button($form_id),
));
echo $aieo_wd_open;
ob_start();
echo '
';
echo self::field_row(array(
'id' => 'aieo-wd-request-status',
'group' => true,
'label' => __('Flag the order', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::check('request_status_enabled', __('Set the order status to "Withdrawal requested" while the declaration is processed.', 'ai-eshop-optimizer'), !empty($s['request_status_enabled']), array('id' => 'aieo-wd-request-status')),
'help' => __('A dedicated status (wc-withdrawal-req), deliberately not "Cancelled" — cancellation is a courtesy you may refuse, withdrawal is a right you may not, and the orders list must keep them apart. Off by default because anything that reads order statuses (an ERP, a feed, custom reports) will meet a status it has never seen. If you switch it off later, move any orders still in the status first — without the registration they display as a bare slug.', 'ai-eshop-optimizer'),
));
$email_obj = null;
if (function_exists('WC') && WC()->mailer()) {
$roster = WC()->mailer()->get_emails();
$email_obj = isset($roster['AIEO_Email_Withdrawal_Request']) ? $roster['AIEO_Email_Withdrawal_Request'] : null;
}
$mail_url = admin_url('admin.php?page=wc-settings&tab=email§ion=aieo_withdrawal_request');
if ($email_obj) {
echo self::field_row(array(
'id' => 'aieo-wd-store-email',
'group' => true,
'label' => __('Email the shop', 'ai-eshop-optimizer'),
'control' => ''
. AIEO_Kit::check('store_email_enabled', __('Send the shop manager an email when a new withdrawal declaration arrives.', 'ai-eshop-optimizer'), 'yes' === $email_obj->get_option('enabled', 'yes'), array('id' => 'aieo-wd-store-email')),
'help_html' => esc_html(sprintf(
__('Goes to %s — the WooCommerce "new order" recipient by default.', 'ai-eshop-optimizer'),
(string) $email_obj->get_recipient()
)) . ' ' . sprintf(
esc_html__('Recipients, subject and template live with every other store email, on %s.', 'ai-eshop-optimizer'),
'' . esc_html__('WooCommerce → Settings → Emails', 'ai-eshop-optimizer') . ''
),
));
} else {
echo self::field_row(array(
'label' => __('Email the shop', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::note(__('WooCommerce\'s mailer is not available, so the store email cannot be configured right now.', 'ai-eshop-optimizer')),
));
}
$survey_url = isset($s['survey_url']) ? (string) $s['survey_url'] : '';
$survey_days = isset($s['survey_delay_days']) ? (int) $s['survey_delay_days'] : 3;
echo self::field_row(array(
'id' => 'aieo-wd-survey',
'group' => true,
'label' => __('Ask why, afterwards', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::check('survey_enabled', __('Email the customer a short survey once their withdrawal is finished.', 'ai-eshop-optimizer'), !empty($s['survey_enabled']), array('id' => 'aieo-wd-survey')),
'help' => __('Sent when the money has gone back, or straight away when nothing was owed, such as an unpaid order cancelled before dispatch. Never after a refusal. The email says answering is optional and changes nothing, because the law does not require a reason and neither do we.', 'ai-eshop-optimizer'),
));
echo self::field_row(array(
'id' => 'aieo-wd-survey-url',
'label' => __('Survey page', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::input('survey_url', $survey_url, array('type' => 'url', 'id' => 'aieo-wd-survey-url', 'placeholder' => 'https://')),
'help' => __('A page on your site holding the survey form. Rooster One adds a signed link for the order, so the answer is tied to the right customer and lands with your other survey results. Leave it empty and nothing is sent, whatever the tick box says.', 'ai-eshop-optimizer'),
));
echo self::field_row(array(
'id' => 'aieo-wd-survey-days',
'label' => __('Send it this many days after the withdrawal finishes', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::input('survey_delay_days', (string) $survey_days, array('type' => 'number', 'id' => 'aieo-wd-survey-days', 'min' => 0, 'max' => 60, 'step' => 1, 'xs' => true)),
'help' => __('Three days is a good default: far enough from the refund that it does not read as a condition of it, near enough that they still remember why.', 'ai-eshop-optimizer'),
));
echo '
';
echo AIEO_DMM_UI::card_form('aieo_dmm_withdrawal_save', (string) $group, $form_id, (string) ob_get_clean());
echo $aieo_wd_close;
}
private function render_return_settings(array $s, $group = 'withdrawal_settings') {
$party = isset($s['return_charge_party']) ? (string) $s['return_charge_party'] : '';
$form_id = 'aieo-card-withdrawal-returns-for-withdrawals-form';
list($aieo_wd_open, $aieo_wd_close) = AIEO_DMM_UI::card(array(
'anchor' => 'withdrawal-returns-for-withdrawals',
'icon' => 'package',
'title' => __('Returns for withdrawals', 'ai-eshop-optimizer'),
'description' => __('When a customer withdraws after dispatch, the goods have to come back. These two answers decide what a return voucher says. Nothing here changes whether a withdrawal is accepted — that is a right, and it works with or without a voucher.', 'ai-eshop-optimizer'),
'footer' => \Rooster\Admin\States::save_button($form_id),
));
echo $aieo_wd_open;
ob_start();
echo '
';
$options = array(
'' => __('— not decided yet —', 'ai-eshop-optimizer'),
'recipient' => __('We do — the shop covers return shipping', 'ai-eshop-optimizer'),
'sender' => __('The customer does', 'ai-eshop-optimizer'),
);
echo self::field_row(array(
'id' => 'aieo-wd-return-party',
'label' => __('Who pays for the return', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::select('return_charge_party', $options, $party, array('id' => 'aieo-wd-return-party')),
'help' => __('The withdrawal law governs the declaration, not the cost of sending goods back — that sits in the older distance-selling rules and turns partly on what your terms of service say. Check yours before answering. Until you do, return vouchers are not issued and the queue tells you to arrange collections yourself.', 'ai-eshop-optimizer'),
));
$current = isset($s['return_carrier']) ? (string) $s['return_carrier'] : '';
$choices = class_exists('AIEO_Withdrawal_Returns') ? AIEO_Withdrawal_Returns::return_courier_options() : array();
$any_returns = false;
$carriers = array('' => __('— same courier that delivered it —', 'ai-eshop-optimizer'));
foreach ($choices as $code => $o) {
if (!empty($o['api_returns'])) { $any_returns = true; }
$carriers[(string) $code] = (string) $o['label'] . (!empty($o['api_returns']) ? '' : ' — ' . __('book it at their portal', 'ai-eshop-optimizer'));
}
if ($any_returns) {
$aieo_wd_carrier_help = esc_html__('Do not assume a parcel comes back the way it went out: you may hold a different contract for collections, and a locker courier cannot collect from a doorstep at all.', 'ai-eshop-optimizer');
} else {
$aieo_couriers_url = add_query_arg(
array('page' => AIEO_DMM::MENU_SLUG, 'dmm_tab' => 'fulfillment', 'ff_section' => 'couriers'),
admin_url('admin.php')
);
$aieo_wd_carrier_help = '' . esc_html__('No courier here can issue a return voucher automatically yet.', 'ai-eshop-optimizer') . ' '
. sprintf(
esc_html__('Set "Collects returns for us" on the couriers that collect for you, on %s. Where we hold no API for them, arrange the collection at their portal and, in the declarations queue, record the number and upload the label they gave you — the customer receives it exactly as if we had issued it.', 'ai-eshop-optimizer'),
'' . esc_html__('Operations → Couriers', 'ai-eshop-optimizer') . ''
);
}
echo self::field_row(array(
'id' => 'aieo-wd-return-carrier',
'label' => __('Preferred return courier', 'ai-eshop-optimizer'),
'control' => AIEO_Kit::select('return_carrier', $carriers, $current, array('id' => 'aieo-wd-return-carrier')),
'help_html' => $aieo_wd_carrier_help,
));
echo '
';
echo '' . esc_html__('Collect from', 'ai-eshop-optimizer') . '';
echo '';
foreach (AIEO_Withdrawal_Returns::pickup_fields() as $f) {
echo '';
}
echo '';
echo ''
. esc_html($has_vno
? __('Printed on the voucher already — change the courier to edit it.', 'ai-eshop-optimizer')
: __('Defaults to the delivery address. Delivery back to you always uses your courier account address.', 'ai-eshop-optimizer'))
. '';
echo '
';
echo '
';
}
echo '
';
echo '
';
echo '';
echo '
';
$manual = AIEO_Withdrawal_Returns::manual_return_couriers();
if (empty($manual)) {
echo ''
. esc_html__('No courier is set to take returns by direct booking yet, so the label is stored without one. Set it on the courier\'s card in Courier Settings.', 'ai-eshop-optimizer')
. '';
}
if (!empty($manual)) {
echo '';
}
echo \Rooster\Admin\Ui::file( '', array( 'id' => 'aieo-wd-file-' . $id, 'class' => 'aieo-wd-label-file', 'accept' => '.pdf,.png,.jpg,.jpeg' ) );
echo AIEO_Kit::button(__('Upload', 'ai-eshop-optimizer'), array(
'size' => 'sm',
'class' => 'aieo-wd-ret',
'attrs' => array('data-mode' => 'upload', 'data-aieo-action' => 'withdrawal.return', 'data-aieo-action-variant' => 'upload', 'data-id' => (string) $id, 'data-nonce' => $nonce),
));
echo '
';
echo ''
. esc_html__('PDF, PNG or JPEG from the courier\'s portal. An uploaded file is what the customer gets, in place of anything we could fetch.', 'ai-eshop-optimizer')
. '';
echo '
';
echo AIEO_Kit::note(__('The right of withdrawal itself cannot be refused. Refuse only a request that falls outside it, and say which of your published grounds applies. The customer is told exactly what you tick here.', 'ai-eshop-optimizer'));
foreach (AIEO_Withdrawal_Rejection_Reasons::enabled() as $gid => $ground) {
echo '';
}
echo '';
echo AIEO_Kit::button(__('Refuse and tell the customer', 'ai-eshop-optimizer'), array(
'size' => 'sm',
'variant' => 'destructive',
'class' => 'aieo-wd-rej-go',
'attrs' => array(
'data-aieo-action' => 'withdrawal.reject',
'data-aieo-action-destructive' => '1',
'data-id' => (string) $rid,
'data-nonce' => $nonce,
'data-nomail' => __('Refused, and saved — but the email to the customer did not go out. Tell them another way.', 'ai-eshop-optimizer'),
'data-confirm' => __('Refuse this request and email the customer?', 'ai-eshop-optimizer'),
),
));
echo '
';
echo AIEO_Kit::fold(__('Refuse this request', 'ai-eshop-optimizer'), (string) ob_get_clean(), array('class' => 'aieo-wd-reject'));
}
return array(
'html' => (string) ob_get_clean(),
'class' => 'aieo-wd-panel-row' . $alt,
'id' => 'aieo-wd-panel-' . $id,
'hidden' => true,
);
}
private function admin_label_url($declaration_id) {
return wp_nonce_url(
add_query_arg(
array('action' => 'aieo_dmm_withdrawal_label', 'id' => (int) $declaration_id),
admin_url('admin-post.php')
),
'aieo_wd_admin_label_' . (int) $declaration_id
);
}
public function admin_label() {
if (!current_user_can('manage_woocommerce')) {
wp_die(esc_html__('You cannot do that.', 'ai-eshop-optimizer'), '', array('response' => 403));
}
$id = isset($_GET['id']) ? absint($_GET['id']) : 0;
check_admin_referer('aieo_wd_admin_label_' . $id);
if (!class_exists('AIEO_Withdrawal_Returns')) {
wp_die(esc_html__('Returns support is unavailable.', 'ai-eshop-optimizer'));
}
$row = AIEO_Withdrawal_Returns::declaration($id);
if (!$row) { wp_die(esc_html__('Declaration not found.', 'ai-eshop-optimizer'), '', array('response' => 404)); }
$label = AIEO_Withdrawal_Returns::label_pdf($row);
if (empty($label['ok'])) {
wp_die(esc_html((string) $label['error']), '', array('response' => 409));
}
nocache_headers();
header('Content-Type: ' . (!empty($label['mime']) ? $label['mime'] : 'application/pdf'));
header('Content-Disposition: inline; filename="' . $label['filename'] . '"');
header('Content-Length: ' . strlen($label['pdf']));
echo $label['pdf'];
exit;
}
public function ajax_reject() {
AIEO_DMM::verify_ajax_request();
global $wpdb;
$table = $wpdb->prefix . 'aieo_dmm_withdrawal_declarations';
$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
if ($id <= 0) { wp_send_json_error(array('message' => __('Missing declaration.', 'ai-eshop-optimizer'))); }
$reasons = isset($_POST['reasons']) && is_array($_POST['reasons'])
? array_values(array_unique(array_filter(array_map('sanitize_key', wp_unslash($_POST['reasons'])))))
: array();
if (!$reasons) {
wp_send_json_error(array('message' => __('Tick at least one ground before refusing.', 'ai-eshop-optimizer')));
}
$note = isset($_POST['note']) ? trim(wp_strip_all_tags((string) wp_unslash($_POST['note']))) : '';
$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $id));
if (!$row) { wp_send_json_error(array('message' => __('Declaration not found.', 'ai-eshop-optimizer'))); }
if (AIEO_Withdrawal::STATUS_AWAITING_APPROVAL !== (string) $row->status) {
wp_send_json_error(array('message' => __('This request has already moved on and can no longer be refused.', 'ai-eshop-optimizer')));
}
$has_label = class_exists('AIEO_Withdrawal_Returns') && AIEO_Withdrawal_Returns::has_label($row);
if (!empty($row->return_voucher_no) || $has_label) {
wp_send_json_error(array('message' => __('A return voucher or label has already been issued for this request. Cancel it with the courier first, then refuse.', 'ai-eshop-optimizer')));
}
$ok = $wpdb->update(
$table,
array(
'status' => AIEO_Withdrawal::STATUS_REJECTED,
'rejected_at_gmt' => current_time('mysql', true),
'rejected_by_user_id' => get_current_user_id(),
'rejection_reasons' => wp_json_encode($reasons),
'rejection_note' => ('' === $note) ? null : mb_substr($note, 0, 500),
),
array('id' => $id),
array('%s', '%s', '%d', '%s', '%s'),
array('%d')
);
if (false === $ok) { wp_send_json_error(array('message' => __('Could not save the refusal.', 'ai-eshop-optimizer'))); }
$sent = false;
if (class_exists('AIEO_Withdrawal_Emails') && method_exists('AIEO_Withdrawal_Emails', 'send_rejection')) {
$order = function_exists('wc_get_order') ? wc_get_order((int) $row->order_id) : null;
$row->status = AIEO_Withdrawal::STATUS_REJECTED;
$row->rejection_reasons = wp_json_encode($reasons);
$row->rejection_note = $note;
$sent = (bool) AIEO_Withdrawal_Emails::send_rejection($row, $order);
}
wp_send_json_success(array('sent' => $sent));
}
public function ajax_save() {
AIEO_DMM::verify_ajax_request();
$statuses = array();
if (!empty($_POST['cancel_statuses_present'])) {
$in = isset($_POST['cancel_statuses']) && is_array($_POST['cancel_statuses'])
? wp_unslash($_POST['cancel_statuses'])
: array();
$statuses = array_values(array_unique(array_filter(array_map('sanitize_key', (array) $in))));
} else {
$current = AIEO_Withdrawal::settings();
$statuses = (array) $current['cancel_statuses'];
}
if (!empty($_POST['rejection_reasons_present']) && class_exists('AIEO_Withdrawal_Rejection_Reasons')) {
$r_ids = isset($_POST['rejection_reason_ids']) && is_array($_POST['rejection_reason_ids'])
? wp_unslash($_POST['rejection_reason_ids'])
: array();
$r_lbl = isset($_POST['rejection_reason_labels']) && is_array($_POST['rejection_reason_labels'])
? wp_unslash($_POST['rejection_reason_labels'])
: array();
$r_on = isset($_POST['rejection_reason_on']) && is_array($_POST['rejection_reason_on'])
? array_flip(array_map('sanitize_key', wp_unslash($_POST['rejection_reason_on'])))
: array();
$rows = array();
foreach ($r_ids as $i => $rid) {
$rid = sanitize_key($rid);
$label = isset($r_lbl[$i]) ? trim(wp_strip_all_tags((string) $r_lbl[$i])) : '';
$is_new = ('' === $rid);
if ('' === $rid) {
if ('' === $label) { continue; }
$rid = substr(sanitize_title($label), 0, 32);
if ('' === $rid) { $rid = 'reason_' . ($i + 1); }
}
$rows[] = array(
'id' => $rid,
'label' => $label,
'enabled' => $is_new ? isset($r_on['']) : isset($r_on[$rid]),
);
}
AIEO_Withdrawal_Rejection_Reasons::save($rows);
}
$patch = array(
'withdrawal' => array(
'enabled' => !empty($_POST['enabled']),
'auto_cancel_enabled' => !empty($_POST['auto_cancel_enabled']),
'request_status_enabled' => !empty($_POST['request_status_enabled']),
'window_hours' => isset($_POST['window_hours']) ? max(0, min(720, (int) $_POST['window_hours'])) : 2,
'window_minutes' => isset($_POST['window_minutes']) ? max(0, min(59, (int) $_POST['window_minutes'])) : 0,
'cancel_statuses' => $statuses,
'guest_form_page_id' => isset($_POST['guest_form_page_id']) ? absint($_POST['guest_form_page_id']) : 0,
'email_intro' => isset($_POST['email_intro']) ? sanitize_textarea_field(wp_unslash($_POST['email_intro'])) : '',
'return_charge_party' => $this->clean_charge_party(
isset($_POST['return_charge_party']) ? sanitize_key(wp_unslash($_POST['return_charge_party'])) : ''
),
'return_carrier' => isset($_POST['return_carrier']) ? sanitize_key(wp_unslash($_POST['return_carrier'])) : '',
'survey_enabled' => !empty($_POST['survey_enabled']),
'survey_url' => isset($_POST['survey_url']) ? esc_url_raw(trim((string) wp_unslash($_POST['survey_url']))) : '',
'survey_delay_days' => isset($_POST['survey_delay_days']) ? max(0, min(60, (int) $_POST['survey_delay_days'])) : 3,
),
);
if (method_exists('AIEO_DMM_Settings', 'replace')) {
$all = AIEO_DMM_Settings::get_all();
$all['withdrawal'] = $patch['withdrawal'];
AIEO_DMM_Settings::replace($all);
} else {
AIEO_DMM_Settings::update($patch);
}
if (!empty($_POST['store_email_present']) && function_exists('WC') && WC()->mailer()) {
$roster = WC()->mailer()->get_emails();
if (isset($roster['AIEO_Email_Withdrawal_Request'])) {
$roster['AIEO_Email_Withdrawal_Request']->update_option(
'enabled',
!empty($_POST['store_email_enabled']) ? 'yes' : 'no'
);
}
}
wp_send_json_success(array('message' => __('Withdrawal settings saved.', 'ai-eshop-optimizer')));
}
private function clean_charge_party($value) {
return in_array($value, array('sender', 'recipient'), true) ? $value : '';
}
public function ajax_return_voucher() {
AIEO_DMM::verify_ajax_request();
if (!class_exists('AIEO_Withdrawal_Returns')) {
wp_send_json_error(array('message' => __('Returns support is unavailable.', 'ai-eshop-optimizer')), 500);
}
$id = isset($_POST['id']) ? absint($_POST['id']) : 0;
$mode = isset($_POST['mode']) ? sanitize_key(wp_unslash($_POST['mode'])) : 'issue';
if (!$id) { wp_send_json_error(array('message' => 'missing id'), 400); }
if (in_array($mode, array('issue', 'record'), true)
&& isset($_POST['pickup']) && is_array($_POST['pickup'])) {
AIEO_Withdrawal_Returns::set_pickup(
$id,
wp_unslash($_POST['pickup'])
);
}
$carrier = isset($_POST['carrier']) ? sanitize_key(wp_unslash($_POST['carrier'])) : '';
if ('record' === $mode) {
$result = AIEO_Withdrawal_Returns::record_manual(
$id,
$carrier,
isset($_POST['voucher_no']) ? sanitize_text_field(wp_unslash($_POST['voucher_no'])) : ''
);
} elseif ('approve' === $mode) {
$result = AIEO_Withdrawal_Returns::approve($id, get_current_user_id());
} elseif ('clear' === $mode) {
$result = AIEO_Withdrawal_Returns::clear_voucher($id);
} elseif ('upload' === $mode) {
$result = isset($_FILES['label_file']) && is_array($_FILES['label_file'])
? AIEO_Withdrawal_Returns::store_uploaded_label($id, $_FILES['label_file'], $carrier)
: new WP_Error('aieo_wdr_no_file', __('Choose a file first.', 'ai-eshop-optimizer'));
} else {
$result = AIEO_Withdrawal_Returns::issue($id, $carrier);
}
if (is_wp_error($result)) {
wp_send_json_error(array('message' => $result->get_error_message()), 409);
}
wp_send_json_success($result);
}
public function ajax_process() {
AIEO_DMM::verify_ajax_request();
global $wpdb;
$id = isset($_POST['id']) ? absint($_POST['id']) : 0;
$to = isset($_POST['to']) ? sanitize_key(wp_unslash($_POST['to'])) : 'received';
if (!$id) { wp_send_json_error(array('message' => 'missing id'), 400); }
if (!in_array($to, array('received', 'refunded'), true)) {
wp_send_json_error(array('message' => 'bad target status'), 400);
}
$table = $wpdb->prefix . 'aieo_dmm_withdrawal_declarations';
$now = current_time('mysql', true);
$current = $wpdb->get_var($wpdb->prepare("SELECT status FROM {$table} WHERE id = %d", $id));
if (null === $current) { wp_send_json_error(array('message' => 'not found'), 404); }
if ('refunded' === $to && 'received' !== $current) {
wp_send_json_error(array(
'message' => __('The goods have not been marked as received yet. Refunds can only be issued after the return is back.', 'ai-eshop-optimizer'),
), 409);
}
if ('received' === $to && !in_array($current, array('pending', 'received'), true)) {
wp_send_json_error(array('message' => AIEO_Withdrawal::STATUS_AWAITING_APPROVAL === $current
? __('Approve the return first — that is what confirms it to the customer.', 'ai-eshop-optimizer')
: __('That declaration is no longer awaiting a return.', 'ai-eshop-optimizer')
), 409);
}
$data = array('status' => $to, 'processed_by_user_id' => get_current_user_id());
$format = array('%s', '%d');
if ('received' === $to) {
$data['received_at_gmt'] = $now;
$format[] = '%s';
} else {
$amount = isset($_POST['amount']) ? (float) wp_unslash($_POST['amount']) : 0.0;
$data['refund_amount'] = max(0, $amount);
$data['refunded_at_gmt'] = $now;
$data['processed_at_gmt'] = $now;
$format[] = '%f';
$format[] = '%s';
$format[] = '%s';
$how = isset($_POST['refund_method']) ? sanitize_key(wp_unslash($_POST['refund_method'])) : '';
if (array_key_exists($how, AIEO_Withdrawal::refund_methods())) {
$data['refund_method'] = $how;
$format[] = '%s';
}
}
$wpdb->update($table, $data, array('id' => $id), $format, array('%d'));
if (class_exists('AIEO_Withdrawal') && method_exists('AIEO_Withdrawal', 'maybe_complete')) {
AIEO_Withdrawal::maybe_complete($id);
}
wp_send_json_success();
}
private function status_counts() {
global $wpdb;
$t = $wpdb->prefix . 'aieo_dmm_withdrawal_declarations';
if ($wpdb->get_var("SHOW TABLES LIKE '{$t}'") !== $t) { return array(); }
$out = array();
foreach ((array) $wpdb->get_results("SELECT status, COUNT(*) c FROM {$t} GROUP BY status") as $r) {
$out[$r->status] = (int) $r->c;
}
return $out;
}
private function amount_owed() {
global $wpdb;
$t = $wpdb->prefix . 'aieo_dmm_withdrawal_declarations';
if ($wpdb->get_var("SHOW TABLES LIKE '{$t}'") !== $t) { return 0.0; }
return (float) $wpdb->get_var("SELECT COALESCE(SUM(declared_total),0) FROM {$t} WHERE status = 'received'");
}
public function ajax_create_page() {
AIEO_DMM::verify_ajax_request();
$page_id = wp_insert_post(array(
'post_title' => __('Withdrawal from an order', 'ai-eshop-optimizer'),
'post_name' => 'ypanaxorisi',
'post_content' => '[' . AIEO_Withdrawal_Guest::SHORTCODE . ']',
'post_status' => 'publish',
'post_type' => 'page',
));
if (is_wp_error($page_id) || !$page_id) {
wp_send_json_error(array('message' => __('Could not create the page.', 'ai-eshop-optimizer')), 500);
}
$all = AIEO_DMM_Settings::get_all();
if (!isset($all['withdrawal']) || !is_array($all['withdrawal'])) { $all['withdrawal'] = array(); }
$all['withdrawal']['guest_form_page_id'] = (int) $page_id;
if (method_exists('AIEO_DMM_Settings', 'replace')) {
AIEO_DMM_Settings::replace($all);
} else {
AIEO_DMM_Settings::update(array('withdrawal' => $all['withdrawal']));
}
wp_send_json_success(array('page_id' => (int) $page_id));
}
}