<?php
/**
 * Guest order confirmation email after online payment (not stored in site database).
 *
 * @package Maca_Menu_List
 */

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

/**
 * Parse optional confirmation email from checkout AJAX (not persisted locally).
 *
 * @return array{send: bool, email: string}|WP_Error
 */
function maca_menulist_parse_confirmation_email_from_request() {
    $send = !empty($_POST['send_confirmation']);

    if (!$send) {
        return array(
            'send' => false,
            'email' => '',
        );
    }

    $email = isset($_POST['confirmation_email'])
        ? sanitize_email(wp_unslash($_POST['confirmation_email']))
        : '';

    if (!is_email($email)) {
        return new WP_Error(
            'confirmation_email',
            __('Please enter a valid email address for the order confirmation.', 'maca-restu-pro')
        );
    }

    return array(
        'send' => true,
        'email' => $email,
    );
}

/**
 * Header lines shared by order confirmation emails.
 *
 * @return array<int, string>
 */
function maca_menulist_confirmation_email_header_lines() {
    $restaurant = maca_menulist_get_restaurant_name_from_settings();
    $settings = function_exists('maca_menulist_get_menu_footer_settings')
        ? maca_menulist_get_menu_footer_settings()
        : array(
            'address' => '',
            'vat_number' => '',
        );

    $lines = array($restaurant);

    if (!empty($settings['address'])) {
        $lines[] = str_replace(array("\r\n", "\r", "\n"), ', ', trim((string) $settings['address']));
    }

    if (!empty($settings['vat_number'])) {
        /* translators: %s: VAT registration number */
        $lines[] = sprintf(__('VAT no. %s', 'maca-restu-pro'), (string) $settings['vat_number']);
    }

    return $lines;
}

/**
 * VAT breakdown merged across multiple paid orders (combined checkout).
 *
 * @param array<int, object> $orders Orders with lines attached.
 * @return array<string, mixed>
 */
function maca_menulist_build_combined_orders_vat_breakdown($orders) {
    $lines_out = array();
    $by_rate = array();
    $total_gross = 0.0;

    foreach ($orders as $order_index => $order) {
        $breakdown = maca_menulist_build_order_vat_breakdown($order);

        foreach ($breakdown['lines'] as $item) {
            $line = $item;

            if ($order_index > 0 && empty($line['is_tip'])) {
                $line['title'] = sprintf(
                    /* translators: 1: add-on order number, 2: dish title */
                    __('Add-on order #%1$d: %2$s', 'maca-restu-pro'),
                    $order_index + 1,
                    $line['title']
                );
            }

            $lines_out[] = $line;

            if (!empty($line['is_tip'])) {
                continue;
            }

            $rate_key = $line['rate'] !== '' ? $line['rate'] : 'unknown';

            if (!isset($by_rate[ $rate_key ])) {
                $by_rate[ $rate_key ] = array(
                    'rate' => $line['rate'],
                    'rate_label' => $line['rate_label'],
                    'gross' => 0.0,
                    'net' => 0.0,
                    'vat' => 0.0,
                );
            }

            $by_rate[ $rate_key ]['gross'] += (float) $line['gross'];
            $by_rate[ $rate_key ]['net'] += (float) $line['net'];
            $by_rate[ $rate_key ]['vat'] += (float) $line['vat'];
        }

        $total_gross += (float) $breakdown['total_gross'];
    }

    $total_vat = 0.0;
    $total_net = 0.0;

    foreach ($by_rate as $bucket) {
        $total_vat += $bucket['vat'];
        $total_net += $bucket['net'];
    }

    foreach ($lines_out as $line) {
        if (!empty($line['is_tip'])) {
            $total_net += (float) $line['gross'];
        }
    }

    ksort($by_rate, SORT_NATURAL);

    return array(
        'lines' => $lines_out,
        'by_rate' => array_values($by_rate),
        'total_gross' => round($total_gross, 2),
        'total_gross_label' => maca_menulist_format_price($total_gross),
        'total_net' => round($total_net, 2),
        'total_vat' => round($total_vat, 2),
    );
}

/**
 * Send combined order confirmation email after successful online payment.
 *
 * @param array<int, object>   $orders  Orders with lines attached (sorted).
 * @param string               $email   Recipient (not stored).
 * @param array<string, mixed> $session Stripe session payload.
 * @return bool
 */
function maca_menulist_send_combined_order_confirmation_email($orders, $email, $session = array()) {
    $email = sanitize_email($email);
    if (!is_email($email) || count($orders) < 2) {
        return false;
    }

    $restaurant = maca_menulist_get_restaurant_name_from_settings();

    /* translators: %s: restaurant name */
    $subject = sprintf(__('Order confirmation – %s', 'maca-restu-pro'), $restaurant);

    $body = maca_menulist_build_combined_orders_confirmation_email_body($orders, $session);

    /**
     * Filter combined order confirmation email before sending.
     *
     * @param string               $body    Email body.
     * @param array<int, object>   $orders  Order rows with lines.
     * @param string               $email   Recipient address.
     * @param array<string, mixed> $session Stripe session data.
     */
    $body = apply_filters('maca_menulist_combined_order_confirmation_email_body', $body, $orders, $email, $session);

    return maca_menulist_wp_mail_as_restaurant($email, $subject, $body);
}

/**
 * Plain-text body for a combined order confirmation email.
 *
 * @param array<int, object>   $orders  Orders with lines.
 * @param array<string, mixed> $session Stripe session.
 * @return string
 */
function maca_menulist_build_combined_orders_confirmation_email_body($orders, $session = array()) {
    $restaurant = maca_menulist_get_restaurant_name_from_settings();
    $primary = $orders[0];
    $breakdown = maca_menulist_build_combined_orders_vat_breakdown($orders);
    $lines = maca_menulist_confirmation_email_header_lines();

    $lines[] = '';
    $lines[] = __('ORDER CONFIRMATION', 'maca-restu-pro');
    $lines[] = str_repeat('-', 40);
    $lines[] = '';

    $lines[] = __('IMPORTANT: This is an order and payment confirmation only — not an official tax receipt. Ask the restaurant for an official receipt if you need one.', 'maca-restu-pro');
    $lines[] = '';

    if (!empty($primary->table_number)) {
        /* translators: %s: table number */
        $lines[] = sprintf(__('Table: %s', 'maca-restu-pro'), (string) $primary->table_number);
    }

    if (count($orders) > 1) {
        /* translators: %d: number of orders */
        $lines[] = sprintf(__('Orders combined: %d', 'maca-restu-pro'), count($orders));
    }

    if (!empty($primary->paid_at)) {
        $lines[] = sprintf(
            /* translators: %s: formatted date/time */
            __('Paid at: %s', 'maca-restu-pro'),
            maca_menulist_format_payment_datetime((string) $primary->paid_at)
        );
    }

    if (!empty($session['id'])) {
        /* translators: %s: payment reference */
        $lines[] = sprintf(__('Payment reference: %s', 'maca-restu-pro'), (string) $session['id']);
    }

    $lines[] = '';
    $lines[] = __('Order details', 'maca-restu-pro');
    $lines[] = str_repeat('-', 40);

    foreach ($breakdown['lines'] as $item) {
        $lines[] = sprintf(
            '%d × %s — %s',
            (int) $item['qty'],
            $item['title'],
            $item['gross_label']
        );
    }

    $lines[] = str_repeat('-', 40);
    /* translators: %s: formatted total amount */
    $lines[] = sprintf(__('Total paid: %s', 'maca-restu-pro'), $breakdown['total_gross_label']);
    $lines[] = '';

    if (!empty($breakdown['by_rate'])) {
        $lines[] = __('VAT breakdown (prices include VAT)', 'maca-restu-pro');
        $lines[] = str_repeat('-', 40);

        foreach ($breakdown['by_rate'] as $bucket) {
            if ($bucket['rate'] === '') {
                continue;
            }

            $label = $bucket['rate_label'] !== ''
                ? $bucket['rate_label']
                : maca_menulist_format_vat_rate_label($bucket['rate']);

            $lines[] = sprintf(
                '%s — %s %s, %s %s',
                $label,
                __('net', 'maca-restu-pro'),
                maca_menulist_format_price($bucket['net']),
                __('VAT', 'maca-restu-pro'),
                maca_menulist_format_price($bucket['vat'])
            );
        }

        if ($breakdown['total_vat'] > 0) {
            $lines[] = sprintf(
                '%s: %s',
                __('Total VAT', 'maca-restu-pro'),
                maca_menulist_format_price($breakdown['total_vat'])
            );
        }

        $lines[] = '';
    }

    $notes = array();
    foreach ($orders as $order_index => $order) {
        if (empty($order->order_note)) {
            continue;
        }

        if ($order_index === 0) {
            $notes[] = __('Order note', 'maca-restu-pro') . ': ' . (string) $order->order_note;
        } else {
            $notes[] = sprintf(
                /* translators: 1: add-on order number, 2: order note */
                __('Add-on order #%1$d note: %2$s', 'maca-restu-pro'),
                $order_index + 1,
                (string) $order->order_note
            );
        }
    }

    if (!empty($notes)) {
        $lines = array_merge($lines, $notes, array(''));
    }

    $lines[] = __('Thank you for your visit!', 'maca-restu-pro');
    $lines[] = $restaurant;

    return implode("\n", $lines);
}

/**
 * Send confirmation email for combined checkout when requested by the guest.
 *
 * @param array<string, mixed> $session   Stripe session object.
 * @param array<int, int>      $order_ids Order IDs in the combined payment.
 * @return void
 */
function maca_menulist_maybe_send_combined_confirmation_email($session, $order_ids) {
    $confirmation = maca_menulist_confirmation_email_from_stripe_session($session);
    if (!$confirmation['send'] || $confirmation['email'] === '') {
        return;
    }

    $orders = array();
    foreach ($order_ids as $order_id) {
        $order_id = absint($order_id);
        if ($order_id <= 0) {
            continue;
        }

        $order = maca_menulist_db_get_table_order($order_id);
        if (!$order) {
            continue;
        }

        $orders[] = maca_menulist_db_attach_table_order_lines(array($order))[0];
    }

    if (count($orders) < 2) {
        if (!empty($orders[0])) {
            maca_menulist_send_order_confirmation_email($orders[0], $confirmation['email'], $session);
        }

        return;
    }

    usort(
        $orders,
        static function ($a, $b) {
            return (int) $a->id <=> (int) $b->id;
        }
    );

    maca_menulist_send_combined_order_confirmation_email($orders, $confirmation['email'], $session);
}

/**
 * Extract guest email + send flag from a Stripe Checkout session object.
 *
 * @param array<string, mixed> $session Stripe session.
 * @return array{send: bool, email: string}
 */
function maca_menulist_confirmation_email_from_stripe_session($session) {
    $send = !empty($session['metadata']['send_confirmation'])
        && (string) $session['metadata']['send_confirmation'] === '1';

    $email = '';
    if (!empty($session['customer_details']['email'])) {
        $email = sanitize_email((string) $session['customer_details']['email']);
    } elseif (!empty($session['customer_email'])) {
        $email = sanitize_email((string) $session['customer_email']);
    }

    if (!is_email($email)) {
        $send = false;
        $email = '';
    }

    return array(
        'send' => $send,
        'email' => $email,
    );
}

/**
 * Send order confirmation email after successful online payment.
 *
 * @param object               $order   Order with lines attached.
 * @param string               $email   Recipient (not stored).
 * @param array<string, mixed> $session Stripe session payload.
 * @return bool
 */
function maca_menulist_send_order_confirmation_email($order, $email, $session = array()) {
    $email = sanitize_email($email);
    if (!is_email($email) || !$order) {
        return false;
    }

    $restaurant = maca_menulist_get_restaurant_name_from_settings();

    /* translators: %s: restaurant name */
    $subject = sprintf(__('Order confirmation – %s', 'maca-restu-pro'), $restaurant);

    $body = maca_menulist_build_order_confirmation_email_body($order, $session);

    /**
     * Filter order confirmation email before sending.
     *
     * @param string               $body    Email body.
     * @param object               $order   Order row with lines.
     * @param string               $email   Recipient address.
     * @param array<string, mixed> $session Stripe session data.
     */
    $body = apply_filters('maca_menulist_order_confirmation_email_body', $body, $order, $email, $session);

    return maca_menulist_wp_mail_as_restaurant($email, $subject, $body);
}

/**
 * Plain-text email body with line spec, VAT split, and disclaimer.
 *
 * @param object               $order   Order with lines.
 * @param array<string, mixed> $session Stripe session.
 * @return string
 */
function maca_menulist_build_order_confirmation_email_body($order, $session = array()) {
    $restaurant = maca_menulist_get_restaurant_name_from_settings();

    $breakdown = maca_menulist_build_order_vat_breakdown($order);
    $lines = maca_menulist_confirmation_email_header_lines();

    $lines[] = '';
    $lines[] = __('ORDER CONFIRMATION', 'maca-restu-pro');
    $lines[] = str_repeat('-', 40);
    $lines[] = '';

    $lines[] = __('IMPORTANT: This is an order and payment confirmation only — not an official tax receipt. Ask the restaurant for an official receipt if you need one.', 'maca-restu-pro');
    $lines[] = '';

    if (!empty($order->table_number)) {
        /* translators: %s: table number */
        $lines[] = sprintf(__('Table: %s', 'maca-restu-pro'), (string) $order->table_number);
    }

    if (!empty($order->paid_at)) {
        $lines[] = sprintf(
            /* translators: %s: formatted date/time */
            __('Paid at: %s', 'maca-restu-pro'),
            maca_menulist_format_payment_datetime((string) $order->paid_at)
        );
    }

    if (!empty($session['id'])) {
        /* translators: %s: payment reference */
        $lines[] = sprintf(__('Payment reference: %s', 'maca-restu-pro'), (string) $session['id']);
    }

    $lines[] = '';
    $lines[] = __('Order details', 'maca-restu-pro');
    $lines[] = str_repeat('-', 40);

    foreach ($breakdown['lines'] as $item) {
        $lines[] = sprintf(
            '%d × %s — %s',
            (int) $item['qty'],
            $item['title'],
            $item['gross_label']
        );
    }

    $lines[] = str_repeat('-', 40);
    /* translators: %s: formatted total amount */
    $lines[] = sprintf(__('Total paid: %s', 'maca-restu-pro'), $breakdown['total_gross_label']);
    $lines[] = '';

    if (!empty($breakdown['by_rate'])) {
        $lines[] = __('VAT breakdown (prices include VAT)', 'maca-restu-pro');
        $lines[] = str_repeat('-', 40);

        foreach ($breakdown['by_rate'] as $bucket) {
            if ($bucket['rate'] === '') {
                continue;
            }

            $label = $bucket['rate_label'] !== ''
                ? $bucket['rate_label']
                : maca_menulist_format_vat_rate_label($bucket['rate']);

            $lines[] = sprintf(
                '%s — %s %s, %s %s',
                $label,
                __('net', 'maca-restu-pro'),
                maca_menulist_format_price($bucket['net']),
                __('VAT', 'maca-restu-pro'),
                maca_menulist_format_price($bucket['vat'])
            );
        }

        if ($breakdown['total_vat'] > 0) {
            $lines[] = sprintf(
                '%s: %s',
                __('Total VAT', 'maca-restu-pro'),
                maca_menulist_format_price($breakdown['total_vat'])
            );
        }

        $lines[] = '';
    }

    if (!empty($order->order_note)) {
        $lines[] = __('Order note', 'maca-restu-pro') . ': ' . (string) $order->order_note;
        $lines[] = '';
    }

    $lines[] = __('Thank you for your visit!', 'maca-restu-pro');
    $lines[] = $restaurant;

    return implode("\n", $lines);
}
