<?php
/**
 * Admin: payment history for reconciliation and control.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Payment history admin screen.
 */
class Maca_MenuList_Admin_Payment_History {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'register_menu'), 99);
        add_action('admin_init', array($this, 'maybe_export_csv'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    /**
     * Register submenu under maca Restu.
     */
    public function register_menu() {
        if (!maca_menulist_is_dishes_mode() || !maca_menulist_table_order_enabled()) {
            return;
        }

        add_submenu_page(
            'maca-restu',
            __('Betalningshistorik', 'maca-restu-pro'),
            __('Betalningshistorik', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-payment-history',
            array($this, 'render_page')
        );
    }

    /**
     * @param string $hook Hook suffix.
     */
    public function enqueue_scripts($hook) {
        if ($hook !== 'maca-restu_page_maca-restu-payment-history') {
            return;
        }

        wp_enqueue_style(
            'maca-menulist-admin-payments',
            MACA_MENULIST_PLUGIN_URL . 'assets/css/admin-payments.css',
            array(),
            MACA_MENULIST_VERSION
        );
    }

    /**
     * Parse filter args from request.
     *
     * @return array<string, mixed>
     */
    private function get_filter_args_from_request() {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Filter UI only.
        $last_days = isset($_GET['last_days']) ? max(0, absint(wp_unslash($_GET['last_days']))) : 30;
        if ($last_days === 0 && !isset($_GET['last_days'])) {
            $last_days = 30;
        }

        $payment_status = isset($_GET['payment_status']) ? sanitize_key(wp_unslash($_GET['payment_status'])) : 'all';
        $payment_method = isset($_GET['payment_method']) ? sanitize_key(wp_unslash($_GET['payment_method'])) : 'all';
        $table_number = isset($_GET['table_number']) ? sanitize_text_field(wp_unslash($_GET['table_number'])) : '';
        $date_from = isset($_GET['date_from']) ? sanitize_text_field(wp_unslash($_GET['date_from'])) : '';
        $date_to = isset($_GET['date_to']) ? sanitize_text_field(wp_unslash($_GET['date_to'])) : '';
        $paged = isset($_GET['paged']) ? max(1, absint(wp_unslash($_GET['paged']))) : 1;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        $allowed_status = array_merge(array('all', 'unpaid'), maca_menulist_payment_statuses());
        if (!in_array($payment_status, $allowed_status, true)) {
            $payment_status = 'all';
        }

        $allowed_methods = array_merge(array('all', 'unset'), maca_menulist_payment_methods());
        if (!in_array($payment_method, $allowed_methods, true)) {
            $payment_method = 'all';
        }

        $args = array(
            'status_filter'         => 'all',
            'payment_status_filter' => $payment_status,
            'payment_method_filter' => $payment_method,
            'table_number'          => $table_number,
            'date_from'             => $date_from,
            'date_to'               => $date_to,
            'orderby'               => 'paid_at',
            'paged'                 => $paged,
            'per_page'              => 30,
        );

        if ($date_from === '' && $date_to === '' && $last_days > 0) {
            $args['last_days'] = $last_days;
        }

        return $args;
    }

    /**
     * Build URL with current filters.
     *
     * @param array<string, mixed> $extra Extra query args.
     * @return string
     */
    private function history_url($extra = array()) {
        $base = admin_url('admin.php?page=maca-restu-payment-history');
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $filters = array(
            'last_days'       => isset($_GET['last_days']) ? absint(wp_unslash($_GET['last_days'])) : 30,
            'payment_status'  => isset($_GET['payment_status']) ? sanitize_key(wp_unslash($_GET['payment_status'])) : 'all',
            'payment_method'  => isset($_GET['payment_method']) ? sanitize_key(wp_unslash($_GET['payment_method'])) : 'all',
            'table_number'    => isset($_GET['table_number']) ? sanitize_text_field(wp_unslash($_GET['table_number'])) : '',
            'date_from'       => isset($_GET['date_from']) ? sanitize_text_field(wp_unslash($_GET['date_from'])) : '',
            'date_to'         => isset($_GET['date_to']) ? sanitize_text_field(wp_unslash($_GET['date_to'])) : '',
        );

        return add_query_arg(array_merge($filters, $extra), $base);
    }

    /**
     * Export CSV when requested.
     */
    public function maybe_export_csv() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!isset($_GET['page']) || sanitize_key(wp_unslash($_GET['page'])) !== 'maca-restu-payment-history') {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!isset($_GET['maca_export']) || sanitize_key(wp_unslash($_GET['maca_export'])) !== 'csv') {
            return;
        }

        if (!maca_menulist_user_can_manage_import_export()) {
            return;
        }

        check_admin_referer('maca_payment_history_export');

        $args = $this->get_filter_args_from_request();
        $args['paged'] = 1;
        $args['per_page'] = 5000;

        $orders = maca_menulist_db_list_table_orders($args);
        $filename = 'maca-payment-history-' . wp_date('Y-m-d') . '.csv';

        nocache_headers();
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=' . $filename);

        $out = fopen('php://output', 'w');
        if ($out === false) {
            return;
        }

        fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF));

        fputcsv(
            $out,
            array(
                __('Order ID', 'maca-restu-pro'),
                __('Table', 'maca-restu-pro'),
                __('Order status', 'maca-restu-pro'),
                __('Payment status', 'maca-restu-pro'),
                __('How paid', 'maca-restu-pro'),
                __('Provider', 'maca-restu-pro'),
                __('Amount paid', 'maca-restu-pro'),
                __('Order total', 'maca-restu-pro'),
                __('Tip', 'maca-restu-pro'),
                __('Currency', 'maca-restu-pro'),
                __('Paid at', 'maca-restu-pro'),
                __('Order created', 'maca-restu-pro'),
                __('External payment ID', 'maca-restu-pro'),
                __('Payment transactions', 'maca-restu-pro'),
            )
        );

        foreach ($orders as $order) {
            $balance = maca_menulist_get_order_payment_balance($order);
            $amount_display = maca_menulist_format_order_payment_amount_display($order);

            fputcsv(
                $out,
                array(
                    (int) $order->id,
                    (string) $order->table_number,
                    maca_menulist_get_table_order_status_label((string) $order->status),
                    maca_menulist_get_order_payment_status_label($order),
                    maca_menulist_get_payment_method_label(isset($order->payment_method) ? (string) $order->payment_method : ''),
                    maca_menulist_get_payment_provider_label(isset($order->payment_provider) ? (string) $order->payment_provider : ''),
                    $balance['paid'] > 0 ? number_format($balance['paid'], 2, '.', '') : '',
                    $balance['total'] > 0 ? number_format($balance['total'], 2, '.', '') : '',
                    function_exists('maca_menulist_get_order_tip_amount')
                        ? number_format(maca_menulist_get_order_tip_amount($order), 2, '.', '')
                        : '',
                    isset($order->payment_currency) ? (string) $order->payment_currency : '',
                    !empty($order->paid_at) ? (string) $order->paid_at : '',
                    (string) $order->created_at,
                    isset($order->payment_external_id) ? (string) $order->payment_external_id : '',
                    function_exists('maca_menulist_format_order_payment_transactions_short')
                        ? maca_menulist_format_order_payment_transactions_short($order)
                        : '',
                )
            );
        }

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- CSV stream to php://output.
        fclose($out);
        exit;
    }

    /**
     * Render payment history page.
     */
    public function render_page() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        if (!maca_menulist_pro_has_feature('table_orders')) {
            echo maca_menulist_pro_locked_notice('table_orders'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            return;
        }

        $args = $this->get_filter_args_from_request();
        $total = maca_menulist_db_count_table_orders($args);
        $orders = maca_menulist_db_list_table_orders($args);
        $summary = maca_menulist_get_payment_history_summary($args);
        $per_page = (int) $args['per_page'];
        $paged = (int) $args['paged'];
        $total_pages = max(1, (int) ceil($total / $per_page));
        $currency = maca_menulist_get_price_currency();
        $list_url = admin_url('admin.php?page=maca-restu-payment-history');
        $export_url = wp_nonce_url(
            $this->history_url(array('maca_export' => 'csv')),
            'maca_payment_history_export'
        );

        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $filter_last_days = isset($_GET['last_days']) ? absint(wp_unslash($_GET['last_days'])) : 30;
        $filter_payment_status = isset($_GET['payment_status']) ? sanitize_key(wp_unslash($_GET['payment_status'])) : 'all';
        $filter_payment_method = isset($_GET['payment_method']) ? sanitize_key(wp_unslash($_GET['payment_method'])) : 'all';
        $filter_table = isset($_GET['table_number']) ? sanitize_text_field(wp_unslash($_GET['table_number'])) : '';
        $filter_date_from = isset($_GET['date_from']) ? sanitize_text_field(wp_unslash($_GET['date_from'])) : '';
        $filter_date_to = isset($_GET['date_to']) ? sanitize_text_field(wp_unslash($_GET['date_to'])) : '';
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        ?>
        <div class="wrap maca-payments-wrap maca-payment-history-wrap<?php echo esc_attr(maca_menulist_admin_demo_readonly_wrap_class()); ?>">
            <h1><?php esc_html_e('Payment history', 'maca-restu-pro'); ?></h1>

            <?php maca_menulist_render_admin_demo_readonly_notice(); ?>

            <p class="description">
                <?php esc_html_e('Review how guest orders were paid — for daily reconciliation, accounting, and Stripe verification. Use filters and export to CSV.', 'maca-restu-pro'); ?>
            </p>
            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-payments')); ?>">
                    <?php esc_html_e('Payment settings', 'maca-restu-pro'); ?>
                </a>
                &nbsp;|&nbsp;
                <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-orders')); ?>">
                    <?php esc_html_e('All table orders', 'maca-restu-pro'); ?>
                </a>
            </p>

            <div class="maca-payment-history-summary">
                <div class="maca-payment-history-stat">
                    <span class="maca-payment-history-stat-value"><?php echo esc_html((string) $summary['paid']); ?></span>
                    <span class="maca-payment-history-stat-label"><?php esc_html_e('Paid', 'maca-restu-pro'); ?></span>
                </div>
                <div class="maca-payment-history-stat">
                    <span class="maca-payment-history-stat-value"><?php echo esc_html((string) $summary['paid_online']); ?></span>
                    <span class="maca-payment-history-stat-label"><?php esc_html_e('Paid online', 'maca-restu-pro'); ?></span>
                </div>
                <div class="maca-payment-history-stat">
                    <span class="maca-payment-history-stat-value"><?php echo esc_html((string) $summary['paid_manual']); ?></span>
                    <span class="maca-payment-history-stat-label"><?php esc_html_e('Paid with server', 'maca-restu-pro'); ?></span>
                </div>
                <div class="maca-payment-history-stat">
                    <span class="maca-payment-history-stat-value"><?php echo esc_html((string) $summary['partial']); ?></span>
                    <span class="maca-payment-history-stat-label"><?php esc_html_e('Partially paid', 'maca-restu-pro'); ?></span>
                </div>
                <div class="maca-payment-history-stat">
                    <span class="maca-payment-history-stat-value"><?php echo esc_html((string) $summary['pending']); ?></span>
                    <span class="maca-payment-history-stat-label"><?php esc_html_e('Payment pending', 'maca-restu-pro'); ?></span>
                </div>
                <div class="maca-payment-history-stat">
                    <span class="maca-payment-history-stat-value"><?php echo esc_html((string) $summary['unpaid']); ?></span>
                    <span class="maca-payment-history-stat-label"><?php esc_html_e('Not paid', 'maca-restu-pro'); ?></span>
                </div>
                <div class="maca-payment-history-stat">
                    <span class="maca-payment-history-stat-value"><?php echo esc_html((string) $summary['total']); ?></span>
                    <span class="maca-payment-history-stat-label"><?php esc_html_e('Orders in period', 'maca-restu-pro'); ?></span>
                </div>
            </div>

            <form method="get" action="" class="maca-payment-history-filters">
                <input type="hidden" name="page" value="maca-restu-payment-history" />

                <label for="maca_ph_last_days"><?php esc_html_e('Last (days)', 'maca-restu-pro'); ?></label>
                <input type="number" min="0" step="1" name="last_days" id="maca_ph_last_days" value="<?php echo esc_attr((string) $filter_last_days); ?>" class="small-text" />
                <span class="description"><?php esc_html_e('0 = use date range below', 'maca-restu-pro'); ?></span>

                <label for="maca_ph_date_from"><?php esc_html_e('From', 'maca-restu-pro'); ?></label>
                <input type="date" name="date_from" id="maca_ph_date_from" value="<?php echo esc_attr($filter_date_from); ?>" />

                <label for="maca_ph_date_to"><?php esc_html_e('To', 'maca-restu-pro'); ?></label>
                <input type="date" name="date_to" id="maca_ph_date_to" value="<?php echo esc_attr($filter_date_to); ?>" />

                <label for="maca_ph_payment_status"><?php esc_html_e('Payment', 'maca-restu-pro'); ?></label>
                <select name="payment_status" id="maca_ph_payment_status">
                    <option value="all" <?php selected($filter_payment_status, 'all'); ?>><?php esc_html_e('All', 'maca-restu-pro'); ?></option>
                    <option value="paid" <?php selected($filter_payment_status, 'paid'); ?>><?php esc_html_e('Paid', 'maca-restu-pro'); ?></option>
                    <option value="partial" <?php selected($filter_payment_status, 'partial'); ?>><?php esc_html_e('Partially paid', 'maca-restu-pro'); ?></option>
                    <option value="pending" <?php selected($filter_payment_status, 'pending'); ?>><?php esc_html_e('Payment pending', 'maca-restu-pro'); ?></option>
                    <option value="unpaid" <?php selected($filter_payment_status, 'unpaid'); ?>><?php esc_html_e('Not paid / failed', 'maca-restu-pro'); ?></option>
                    <option value="none" <?php selected($filter_payment_status, 'none'); ?>><?php esc_html_e('Not paid', 'maca-restu-pro'); ?></option>
                    <option value="failed" <?php selected($filter_payment_status, 'failed'); ?>><?php esc_html_e('Payment failed', 'maca-restu-pro'); ?></option>
                </select>

                <label for="maca_ph_payment_method"><?php esc_html_e('How paid', 'maca-restu-pro'); ?></label>
                <select name="payment_method" id="maca_ph_payment_method">
                    <option value="all" <?php selected($filter_payment_method, 'all'); ?>><?php esc_html_e('All', 'maca-restu-pro'); ?></option>
                    <option value="online" <?php selected($filter_payment_method, 'online'); ?>><?php esc_html_e('Online (Stripe)', 'maca-restu-pro'); ?></option>
                    <option value="manual" <?php selected($filter_payment_method, 'manual'); ?>><?php esc_html_e('With server', 'maca-restu-pro'); ?></option>
                    <option value="unset" <?php selected($filter_payment_method, 'unset'); ?>><?php esc_html_e('Not chosen', 'maca-restu-pro'); ?></option>
                </select>

                <label for="maca_ph_table"><?php esc_html_e('Table', 'maca-restu-pro'); ?></label>
                <input type="text" name="table_number" id="maca_ph_table" value="<?php echo esc_attr($filter_table); ?>" class="small-text" placeholder="<?php esc_attr_e('e.g. 12', 'maca-restu-pro'); ?>" />

                <?php submit_button(__('Filter', 'maca-restu-pro'), 'secondary', '', false); ?>
                <a class="button" href="<?php echo esc_url($export_url); ?>"><?php esc_html_e('Export CSV', 'maca-restu-pro'); ?></a>
            </form>

            <table class="wp-list-table widefat fixed striped maca-payment-history-table">
                <thead>
                    <tr>
                        <th scope="col"><?php esc_html_e('ID', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Table', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Payment', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('How paid', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Provider', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Amount', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Tip', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Paid at', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Order created', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('External ID', 'maca-restu-pro'); ?></th>
                        <th scope="col"><?php esc_html_e('Actions', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($orders)) : ?>
                        <tr>
                            <td colspan="11"><?php esc_html_e('No orders match your filters.', 'maca-restu-pro'); ?></td>
                        </tr>
                    <?php else : ?>
                        <?php foreach ($orders as $order) : ?>
                            <?php
                            $effective_status = maca_menulist_order_effective_payment_status($order);
                            $row_class = '';
                            if ($effective_status === 'paid') {
                                $row_class = 'maca-payment-history-row--paid';
                            } elseif ($effective_status === 'partial') {
                                $row_class = 'maca-payment-history-row--partial';
                            } elseif ($effective_status === 'pending') {
                                $row_class = 'maca-payment-history-row--pending';
                            }
                            ?>
                            <tr class="<?php echo esc_attr($row_class); ?>">
                                <td><?php echo esc_html((string) $order->id); ?></td>
                                <td><?php echo esc_html($order->table_number !== '' ? (string) $order->table_number : '—'); ?></td>
                                <td><?php echo esc_html(maca_menulist_get_order_payment_status_label($order)); ?></td>
                                <td><?php echo esc_html(maca_menulist_get_payment_method_label(isset($order->payment_method) ? (string) $order->payment_method : '')); ?></td>
                                <td><?php echo esc_html(maca_menulist_get_payment_provider_label(isset($order->payment_provider) ? (string) $order->payment_provider : '')); ?></td>
                                <td><?php echo esc_html(maca_menulist_format_order_payment_amount_display($order, $currency)); ?></td>
                                <td>
                                    <?php
                                    $tip = function_exists('maca_menulist_get_order_tip_amount')
                                        ? maca_menulist_get_order_tip_amount($order)
                                        : 0;
                                    echo esc_html($tip > 0 ? maca_menulist_format_price($tip) : '—');
                                    ?>
                                </td>
                                <td><?php echo esc_html(!empty($order->paid_at) ? maca_menulist_format_order_datetime((string) $order->paid_at) : '—'); ?></td>
                                <td><?php echo esc_html(maca_menulist_format_order_datetime((string) $order->created_at)); ?></td>
                                <td>
                                    <?php
                                    $tx_state = function_exists('maca_menulist_build_order_payment_transactions_state')
                                        ? maca_menulist_build_order_payment_transactions_state($order)
                                        : array('count' => 0);
                                    if ($tx_state['count'] > 1) :
                                        ?>
                                        <span class="maca-payment-history-tx-summary" title="<?php echo esc_attr($tx_state['summary_label']); ?>">
                                            <?php
                                            printf(
                                                /* translators: %d: number of payment transactions */
                                                esc_html(_n('%d payments', '%d payments', $tx_state['count'], 'maca-restu-pro')),
                                                (int) $tx_state['count']
                                            );
                                            ?>
                                        </span>
                                    <?php elseif ($tx_state['count'] === 1 && !empty($tx_state['items'][0]['external_id'])) : ?>
                                        <?php $external_id = (string) $tx_state['items'][0]['external_id']; ?>
                                        <a
                                            href="#"
                                            class="maca-payment-history-external-id-link"
                                            data-external-id="<?php echo esc_attr($external_id); ?>"
                                        >
                                            <?php esc_html_e('Visa', 'maca-restu-pro'); ?>
                                        </a>
                                    <?php elseif (!empty($order->payment_external_id)) : ?>
                                        <?php $external_id = (string) $order->payment_external_id; ?>
                                        <a
                                            href="#"
                                            class="maca-payment-history-external-id-link"
                                            data-external-id="<?php echo esc_attr($external_id); ?>"
                                        >
                                            <?php esc_html_e('Visa', 'maca-restu-pro'); ?>
                                        </a>
                                    <?php else : ?>
                                        —
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-orders&action=view&order_id=' . (int) $order->id)); ?>">
                                        <?php esc_html_e('View', 'maca-restu-pro'); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>

            <?php if ($total_pages > 1) : ?>
                <div class="tablenav bottom">
                    <div class="tablenav-pages">
                        <?php
                        echo wp_kses_post(
                            paginate_links(
                                array(
                                    'base'     => add_query_arg('paged', '%#%', $list_url),
                                    'format'   => '',
                                    'current'  => $paged,
                                    'total'    => $total_pages,
                                    'add_args' => array(
                                        'last_days'       => $filter_last_days,
                                        'payment_status'  => $filter_payment_status,
                                        'payment_method'  => $filter_payment_method,
                                        'table_number'    => $filter_table,
                                        'date_from'       => $filter_date_from,
                                        'date_to'         => $filter_date_to,
                                    ),
                                )
                            )
                        );
                        ?>
                    </div>
                </div>
            <?php endif; ?>

            <div id="maca-payment-external-id-modal" class="maca-payment-external-id-modal" hidden>
                <div class="maca-payment-external-id-modal__backdrop" data-modal-close="1"></div>
                <div class="maca-payment-external-id-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="maca-payment-external-id-title">
                    <h2 id="maca-payment-external-id-title"><?php esc_html_e('Externt ID', 'maca-restu-pro'); ?></h2>
                    <code id="maca-payment-external-id-value" class="maca-payment-history-external-id">—</code>
                    <p class="maca-payment-external-id-modal__actions">
                        <button type="button" class="button button-secondary" data-modal-close="1">
                            <?php esc_html_e('Stäng', 'maca-restu-pro'); ?>
                        </button>
                    </p>
                </div>
            </div>
            <script>
            (function () {
                var modal = document.getElementById('maca-payment-external-id-modal');
                var valueEl = document.getElementById('maca-payment-external-id-value');
                if (!modal || !valueEl) {
                    return;
                }

                function closeModal() {
                    modal.setAttribute('hidden', 'hidden');
                    valueEl.textContent = '—';
                }

                document.addEventListener('click', function (event) {
                    var link = event.target.closest('.maca-payment-history-external-id-link');
                    if (link) {
                        event.preventDefault();
                        valueEl.textContent = link.getAttribute('data-external-id') || '—';
                        modal.removeAttribute('hidden');
                        return;
                    }

                    if (event.target.closest('[data-modal-close="1"]')) {
                        closeModal();
                    }
                });

                document.addEventListener('keydown', function (event) {
                    if (event.key === 'Escape' && !modal.hasAttribute('hidden')) {
                        closeModal();
                    }
                });
            })();
            </script>
        </div>
        <?php
    }
}
