<?php
/**
 * AJAX handlers for guest payment flow.
 *
 * @package Maca_Menu_List
 */

if (!defined('ABSPATH')) {
    exit;
}

add_action('wp_ajax_maca_set_table_order_payment_method', 'maca_menulist_ajax_set_table_order_payment_method');
add_action('wp_ajax_nopriv_maca_set_table_order_payment_method', 'maca_menulist_ajax_set_table_order_payment_method');
add_action('wp_ajax_maca_create_table_order_checkout', 'maca_menulist_ajax_create_table_order_checkout');
add_action('wp_ajax_nopriv_maca_create_table_order_checkout', 'maca_menulist_ajax_create_table_order_checkout');
add_action('wp_ajax_maca_create_combined_table_order_checkout', 'maca_menulist_ajax_create_combined_table_order_checkout');
add_action('wp_ajax_nopriv_maca_create_combined_table_order_checkout', 'maca_menulist_ajax_create_combined_table_order_checkout');
add_action('wp_ajax_maca_set_combined_table_order_payment_method', 'maca_menulist_ajax_set_combined_table_order_payment_method');
add_action('wp_ajax_nopriv_maca_set_combined_table_order_payment_method', 'maca_menulist_ajax_set_combined_table_order_payment_method');
add_action('wp_ajax_maca_set_combined_order_bill_split', 'maca_menulist_ajax_set_combined_order_bill_split');
add_action('wp_ajax_nopriv_maca_set_combined_order_bill_split', 'maca_menulist_ajax_set_combined_order_bill_split');
add_action('wp_ajax_maca_set_table_order_tip', 'maca_menulist_ajax_set_table_order_tip');
add_action('wp_ajax_nopriv_maca_set_table_order_tip', 'maca_menulist_ajax_set_table_order_tip');
add_action('wp_ajax_maca_set_order_bill_split', 'maca_menulist_ajax_set_order_bill_split');
add_action('wp_ajax_nopriv_maca_set_order_bill_split', 'maca_menulist_ajax_set_order_bill_split');

/**
 * Verify table order AJAX nonce.
 *
 * @return bool
 */
function maca_menulist_verify_table_order_ajax() {
    $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';

    return wp_verify_nonce($nonce, 'maca_table_order_nonce');
}

/**
 * Save guest tip before payment.
 */
function maca_menulist_ajax_set_table_order_tip() {
    if (!maca_menulist_verify_table_order_ajax()) {
        wp_send_json_error(array('message' => __('Invalid request.', 'maca-restu-pro')));
    }

    if (!maca_menulist_tips_enabled()) {
        wp_send_json_error(array('message' => __('Tips are not enabled.', 'maca-restu-pro')));
    }

    $guest_token = isset($_POST['guest_token']) ? sanitize_text_field(wp_unslash($_POST['guest_token'])) : '';
    $order = maca_menulist_get_guest_order_for_token($guest_token);

    if (!$order) {
        wp_send_json_error(array('message' => __('Order not found.', 'maca-restu-pro')));
    }

    if (!maca_menulist_order_payment_timing_allows_action($order)) {
        wp_send_json_error(array('message' => __('Payment is not available for this order yet.', 'maca-restu-pro')));
    }

    $tip = maca_menulist_resolve_tip_from_request($order);
    if (is_wp_error($tip)) {
        wp_send_json_error(array('message' => $tip->get_error_message()));
    }

    $saved = maca_menulist_db_set_order_tip_amount((int) $order->id, $tip);
    if (is_wp_error($saved)) {
        wp_send_json_error(array('message' => $saved->get_error_message()));
    }

    $order = maca_menulist_get_guest_order_for_token($guest_token);
    wp_send_json_success(maca_menulist_format_guest_order_status_for_json($order));
}

/**
 * Apply tip from request when tips are enabled.
 *
 * @param object $order Order with lines.
 * @return true|WP_Error
 */
function maca_menulist_maybe_apply_tip_from_request($order) {
    if (!maca_menulist_tips_enabled()) {
        return true;
    }

    if (!isset($_POST['tip_amount']) && !isset($_POST['tip_choice']) && !isset($_POST['tip_custom_amount'])) {
        return true;
    }

    $tip = maca_menulist_resolve_tip_from_request($order);
    if (is_wp_error($tip)) {
        return $tip;
    }

    return maca_menulist_db_set_order_tip_amount((int) $order->id, $tip);
}

/**
 * Guest configures bill split (equal shares or fixed amount per person).
 */
function maca_menulist_ajax_set_order_bill_split() {
    if (!maca_menulist_verify_table_order_ajax()) {
        wp_send_json_error(array('message' => __('Invalid request.', 'maca-restu-pro')));
    }

    if (!maca_menulist_payments_allow_bill_split()) {
        wp_send_json_error(array('message' => __('Bill splitting is not enabled.', 'maca-restu-pro')));
    }

    $guest_token = isset($_POST['guest_token']) ? sanitize_text_field(wp_unslash($_POST['guest_token'])) : '';
    $mode = isset($_POST['mode']) ? sanitize_key(wp_unslash($_POST['mode'])) : '';
    $people = isset($_POST['people']) ? absint($_POST['people']) : 0;
    $fixed_amount = isset($_POST['fixed_amount']) ? round((float) wp_unslash($_POST['fixed_amount']), 2) : 0.0;

    if ($mode === '' && $people === 0 && $fixed_amount <= 0) {
        $mode = '';
    } elseif ($mode === '' && $people > 0) {
        $mode = 'equal';
    }

    $order = maca_menulist_get_guest_order_for_token($guest_token);
    if (!$order) {
        wp_send_json_error(array('message' => __('Order not found.', 'maca-restu-pro')));
    }

    if (!maca_menulist_order_payment_timing_allows_action($order)) {
        wp_send_json_error(array('message' => __('Payment is not available for this order yet.', 'maca-restu-pro')));
    }

    $result = maca_menulist_db_set_order_bill_split(
        (int) $order->id,
        array(
            'mode' => $mode,
            'people' => $people,
            'fixed_amount' => $fixed_amount,
        )
    );
    if (is_wp_error($result)) {
        wp_send_json_error(array('message' => $result->get_error_message()));
    }

    $order = maca_menulist_get_guest_order_for_token($guest_token);
    wp_send_json_success(maca_menulist_format_guest_order_status_for_json($order));
}

/**
 * Guest chooses manual or online payment.
 */
function maca_menulist_ajax_set_table_order_payment_method() {
    if (!maca_menulist_verify_table_order_ajax()) {
        wp_send_json_error(array('message' => __('Invalid request.', 'maca-restu-pro')));
    }

    if (!maca_menulist_payments_guest_flow_enabled()) {
        wp_send_json_error(array('message' => __('Payments are not enabled.', 'maca-restu-pro')));
    }

    $guest_token = isset($_POST['guest_token']) ? sanitize_text_field(wp_unslash($_POST['guest_token'])) : '';
    $method = isset($_POST['method']) ? sanitize_key(wp_unslash($_POST['method'])) : '';

    $order = maca_menulist_get_guest_order_for_token($guest_token);
    if (!$order) {
        wp_send_json_error(array('message' => __('Order not found.', 'maca-restu-pro')));
    }

    if ($method === 'online' && (!maca_menulist_payments_allow_online() || !maca_menulist_payments_online_ready())) {
        wp_send_json_error(array('message' => __('Online payment is not available.', 'maca-restu-pro')));
    }

    if ($method === 'manual' && !maca_menulist_payments_allow_manual()) {
        wp_send_json_error(array('message' => __('Pay at table is not available.', 'maca-restu-pro')));
    }

    $tip_result = maca_menulist_maybe_apply_tip_from_request($order);
    if (is_wp_error($tip_result)) {
        wp_send_json_error(array('message' => $tip_result->get_error_message()));
    }

    $result = maca_menulist_db_set_order_payment_method((int) $order->id, $method);
    if (is_wp_error($result)) {
        wp_send_json_error(array('message' => $result->get_error_message()));
    }

    $order = maca_menulist_get_guest_order_for_token($guest_token);
    $payload = maca_menulist_format_guest_order_status_for_json($order);

    if ($method === 'manual') {
        $payload['message'] = __('You will pay your server. They will confirm when payment is received.', 'maca-restu-pro');
    }

    wp_send_json_success($payload);
}

/**
 * Start Stripe Checkout for a table order.
 */
function maca_menulist_ajax_create_table_order_checkout() {
    if (!maca_menulist_verify_table_order_ajax()) {
        wp_send_json_error(array('message' => __('Invalid request.', 'maca-restu-pro')));
    }

    if (!maca_menulist_stripe_guest_checkout_active()) {
        wp_send_json_error(array('message' => __('Online payment is not available.', 'maca-restu-pro')));
    }

    $guest_token = isset($_POST['guest_token']) ? sanitize_text_field(wp_unslash($_POST['guest_token'])) : '';
    $return_url = isset($_POST['return_url']) ? esc_url_raw(wp_unslash($_POST['return_url'])) : '';

    $order = maca_menulist_get_guest_order_for_token($guest_token);
    if (!$order) {
        wp_send_json_error(array('message' => __('Order not found.', 'maca-restu-pro')));
    }

    $tip_result = maca_menulist_maybe_apply_tip_from_request($order);
    if (is_wp_error($tip_result)) {
        wp_send_json_error(array('message' => $tip_result->get_error_message()));
    }

    if ((string) $order->payment_method === '') {
        maca_menulist_db_set_order_payment_method((int) $order->id, 'online');
    }

    $order = maca_menulist_get_guest_order_for_token($guest_token);

    $confirmation = maca_menulist_parse_confirmation_email_from_request();
    if (is_wp_error($confirmation)) {
        wp_send_json_error(array('message' => $confirmation->get_error_message()));
    }

    $checkout_opts = array();
    if (!empty($confirmation['send'])) {
        $checkout_opts['send_confirmation'] = true;
        $checkout_opts['confirmation_email'] = $confirmation['email'];
    }

    $checkout = maca_menulist_stripe_create_table_order_checkout($order, $return_url, $checkout_opts);
    if (is_wp_error($checkout)) {
        wp_send_json_error(array('message' => $checkout->get_error_message()));
    }

    wp_send_json_success($checkout);
}

/**
 * Start Stripe Checkout for multiple table orders.
 */
function maca_menulist_ajax_create_combined_table_order_checkout() {
    if (!maca_menulist_verify_table_order_ajax()) {
        wp_send_json_error(array('message' => __('Invalid request.', 'maca-restu-pro')));
    }

    if (!maca_menulist_stripe_guest_checkout_active()) {
        wp_send_json_error(array('message' => __('Online payment is not available.', 'maca-restu-pro')));
    }

    $tokens = maca_menulist_parse_guest_tokens_from_request();
    $orders = maca_menulist_get_guest_orders_for_tokens($tokens);
    $orders = maca_menulist_validate_combined_payment_orders($orders);
    if (is_wp_error($orders)) {
        wp_send_json_error(array('message' => $orders->get_error_message()));
    }

    $tip_result = maca_menulist_apply_combined_tip_from_request($orders);
    if (is_wp_error($tip_result)) {
        wp_send_json_error(array('message' => $tip_result->get_error_message()));
    }

    $orders = maca_menulist_reload_combined_payment_orders($orders);
    if (is_wp_error($orders)) {
        wp_send_json_error(array('message' => $orders->get_error_message()));
    }

    foreach ($orders as $order) {
        if ((string) $order->payment_method === '') {
            maca_menulist_db_set_order_payment_method((int) $order->id, 'online');
        }
    }

    $orders = maca_menulist_reload_combined_payment_orders($orders);
    if (is_wp_error($orders)) {
        wp_send_json_error(array('message' => $orders->get_error_message()));
    }

    $return_url = isset($_POST['return_url']) ? esc_url_raw(wp_unslash($_POST['return_url'])) : '';
    $confirmation = maca_menulist_parse_confirmation_email_from_request();
    if (is_wp_error($confirmation)) {
        wp_send_json_error(array('message' => $confirmation->get_error_message()));
    }

    $checkout_opts = array();
    if (!empty($confirmation['send'])) {
        $checkout_opts['send_confirmation'] = true;
        $checkout_opts['confirmation_email'] = $confirmation['email'];
    }

    $checkout = maca_menulist_stripe_create_combined_table_order_checkout($orders, $return_url, $checkout_opts);
    if (is_wp_error($checkout)) {
        wp_send_json_error(array('message' => $checkout->get_error_message()));
    }

    wp_send_json_success($checkout);
}

/**
 * Guest chooses manual or online payment for multiple orders.
 */
function maca_menulist_ajax_set_combined_table_order_payment_method() {
    if (!maca_menulist_verify_table_order_ajax()) {
        wp_send_json_error(array('message' => __('Invalid request.', 'maca-restu-pro')));
    }

    if (!maca_menulist_payments_guest_flow_enabled()) {
        wp_send_json_error(array('message' => __('Payments are not enabled.', 'maca-restu-pro')));
    }

    $method = isset($_POST['method']) ? sanitize_key(wp_unslash($_POST['method'])) : '';
    $tokens = maca_menulist_parse_guest_tokens_from_request();
    $orders = maca_menulist_get_guest_orders_for_tokens($tokens);
    $orders = maca_menulist_validate_combined_payment_orders($orders);
    if (is_wp_error($orders)) {
        wp_send_json_error(array('message' => $orders->get_error_message()));
    }

    if ($method === 'online' && (!maca_menulist_payments_allow_online() || !maca_menulist_payments_online_ready())) {
        wp_send_json_error(array('message' => __('Online payment is not available.', 'maca-restu-pro')));
    }

    if ($method === 'manual' && !maca_menulist_payments_allow_manual()) {
        wp_send_json_error(array('message' => __('Pay at table is not available.', 'maca-restu-pro')));
    }

    $tip_result = maca_menulist_apply_combined_tip_from_request($orders);
    if (is_wp_error($tip_result)) {
        wp_send_json_error(array('message' => $tip_result->get_error_message()));
    }

    foreach ($orders as $order) {
        $result = maca_menulist_db_set_order_payment_method((int) $order->id, $method);
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }
    }

    $payload = array(
        'orders' => array(),
        'message' => '',
    );

    foreach ($orders as $order) {
        $guest_token = isset($order->guest_token) ? (string) $order->guest_token : '';
        if ($guest_token === '') {
            continue;
        }

        $fresh = maca_menulist_get_guest_order_for_token($guest_token);
        if ($fresh) {
            $payload['orders'][] = maca_menulist_format_guest_order_status_for_json($fresh);
        }
    }

    if ($method === 'manual') {
        $payload['message'] = __('You will pay your server. They will confirm when payment is received.', 'maca-restu-pro');
    }

    wp_send_json_success($payload);
}

/**
 * Guest configures bill split for multiple orders (combined total).
 */
function maca_menulist_ajax_set_combined_order_bill_split() {
    if (!maca_menulist_verify_table_order_ajax()) {
        wp_send_json_error(array('message' => __('Invalid request.', 'maca-restu-pro')));
    }

    if (!maca_menulist_payments_allow_bill_split()) {
        wp_send_json_error(array('message' => __('Bill splitting is not enabled.', 'maca-restu-pro')));
    }

    $mode = isset($_POST['mode']) ? sanitize_key(wp_unslash($_POST['mode'])) : '';
    $people = isset($_POST['people']) ? absint($_POST['people']) : 0;
    $fixed_amount = isset($_POST['fixed_amount']) ? round((float) wp_unslash($_POST['fixed_amount']), 2) : 0.0;

    if ($mode === '' && $people === 0 && $fixed_amount <= 0) {
        $mode = '';
    } elseif ($mode === '' && $people > 0) {
        $mode = 'equal';
    }

    $tokens = maca_menulist_parse_guest_tokens_from_request();
    $orders = maca_menulist_get_guest_orders_for_tokens($tokens);
    $orders = maca_menulist_validate_combined_payment_orders($orders);
    if (is_wp_error($orders)) {
        wp_send_json_error(array('message' => $orders->get_error_message()));
    }

    foreach ($orders as $order) {
        if (!maca_menulist_order_payment_timing_allows_action($order)) {
            wp_send_json_error(array('message' => __('Payment is not available for this order yet.', 'maca-restu-pro')));
        }
    }

    $result = maca_menulist_db_set_combined_order_bill_split(
        $orders,
        array(
            'mode' => $mode,
            'people' => $people,
            'fixed_amount' => $fixed_amount,
        )
    );
    if (is_wp_error($result)) {
        wp_send_json_error(array('message' => $result->get_error_message()));
    }

    $payload = array(
        'orders' => array(),
    );

    foreach ($orders as $order) {
        $guest_token = isset($order->guest_token) ? (string) $order->guest_token : '';
        if ($guest_token === '') {
            continue;
        }

        $fresh = maca_menulist_get_guest_order_for_token($guest_token);
        if ($fresh) {
            $payload['orders'][] = maca_menulist_format_guest_order_status_for_json($fresh);
        }
    }

    wp_send_json_success($payload);
}
