<?php
/**
 * GGM Commerce Transaction Export Admin Tab
 *
 * @package GGM_Commerce
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Render the Transaction Export admin tab
 */
function ggmc_render_transaction_export_tab() {
    // Ensure export class is loaded.
    if ( ! class_exists( 'GGM_Commerce_Transaction_Export' ) ) {
        require_once plugin_dir_path( __FILE__ ) . 'class-transaction-export.php';
    }

    $export_handler = GGM_Commerce_Transaction_Export::get_instance();
    $batches_data = $export_handler->list_export_batches( 1, 10 );

    // Default date range: last 30 days.
    $default_date_from = gmdate( 'Y-m-d', strtotime( '-30 days' ) );
    $default_date_to = gmdate( 'Y-m-d' );

    $nonce = wp_create_nonce( 'ggmc_transaction_export' );
    ?>
    <div class="wrap ggmc-transaction-export">
        <?php GGM_Commerce_Admin::page_title( __( 'Transaction Export', 'ggm-commerce' ) ); ?>
        <p class="description"><?php esc_html_e( 'Export transaction data for accounting and bookkeeping purposes. Exports include sales, refunds, tax, and shipping totals.', 'ggm-commerce' ); ?></p>

        <!-- Generate Export Section -->
        <div class="ggmc-export-section">
            <h2><?php esc_html_e( 'Generate New Export', 'ggm-commerce' ); ?></h2>

            <form id="ggmc-export-form" class="ggmc-export-form">
                <input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>">

                <div class="ggmc-form-group">
                    <label for="date_from"><?php esc_html_e( 'From Date', 'ggm-commerce' ); ?></label>
                    <input type="date" id="date_from" name="date_from" value="<?php echo esc_attr( $default_date_from ); ?>" required>
                </div>

                <div class="ggmc-form-group">
                    <label for="date_to"><?php esc_html_e( 'To Date', 'ggm-commerce' ); ?></label>
                    <input type="date" id="date_to" name="date_to" value="<?php echo esc_attr( $default_date_to ); ?>" required>
                </div>

                <div class="ggmc-form-group">
                    <label for="format"><?php esc_html_e( 'Format', 'ggm-commerce' ); ?></label>
                    <select id="format" name="format">
                        <option value="csv"><?php esc_html_e( 'CSV (Excel)', 'ggm-commerce' ); ?></option>
                        <option value="json"><?php esc_html_e( 'JSON', 'ggm-commerce' ); ?></option>
                    </select>
                </div>

                <div class="ggmc-form-group">
                    <label>&nbsp;</label>
                    <button type="button" id="ggmc-preview-btn" class="button"><?php esc_html_e( 'Preview', 'ggm-commerce' ); ?></button>
                </div>

                <div class="ggmc-form-group">
                    <label>&nbsp;</label>
                    <button type="submit" id="ggmc-generate-btn" class="button button-primary"><?php esc_html_e( 'Generate Export', 'ggm-commerce' ); ?></button>
                </div>
            </form>

            <!-- Preview Box -->
            <div id="ggmc-preview-box" class="ggmc-preview-box" style="display: none;">
                <h3><?php esc_html_e( 'Export Preview', 'ggm-commerce' ); ?></h3>
                <div class="ggmc-preview-stats">
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value" id="preview-orders">-</div>
                        <div class="ggmc-stat-label"><?php esc_html_e( 'Orders', 'ggm-commerce' ); ?></div>
                    </div>
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value" id="preview-refunds">-</div>
                        <div class="ggmc-stat-label"><?php esc_html_e( 'Refunds', 'ggm-commerce' ); ?></div>
                    </div>
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value ggmc-amount-positive" id="preview-sales">-</div>
                        <div class="ggmc-stat-label"><?php esc_html_e( 'Gross Sales', 'ggm-commerce' ); ?></div>
                    </div>
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value ggmc-amount-negative" id="preview-refund-amount">-</div>
                        <div class="ggmc-stat-label"><?php esc_html_e( 'Refunded', 'ggm-commerce' ); ?></div>
                    </div>
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value" id="preview-tax">-</div>
                        <div class="ggmc-stat-label"><?php esc_html_e( 'Tax', 'ggm-commerce' ); ?></div>
                    </div>
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value" id="preview-shipping">-</div>
                        <div class="ggmc-stat-label"><?php esc_html_e( 'Shipping', 'ggm-commerce' ); ?></div>
                    </div>
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value ggmc-amount-positive" id="preview-net">-</div>
                        <div class="ggmc-stat-label"><?php esc_html_e( 'Net Total', 'ggm-commerce' ); ?></div>
                    </div>
                </div>
            </div>

            <!-- Messages -->
            <div id="ggmc-export-message"></div>

            <!-- Optional Notes -->
            <div class="ggmc-form-group" style="margin-top: 15px; max-width: 500px;">
                <label for="notes"><?php esc_html_e( 'Notes (optional)', 'ggm-commerce' ); ?></label>
                <textarea id="notes" name="notes" rows="2" placeholder="<?php esc_attr_e( 'Add any notes for this export batch...', 'ggm-commerce' ); ?>"></textarea>
            </div>
        </div>

        <!-- Export History Section -->
        <div class="ggmc-export-section">
            <h2><?php esc_html_e( 'Export History', 'ggm-commerce' ); ?></h2>

            <?php if ( empty( $batches_data['batches'] ) ) : ?>
                <div class="ggmc-empty-state">
                    <p><?php esc_html_e( 'No exports have been generated yet.', 'ggm-commerce' ); ?></p>
                </div>
            <?php else : ?>
                <table class="ggmc-batches-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Batch Number', 'ggm-commerce' ); ?></th>
                            <th><?php esc_html_e( 'Date Range', 'ggm-commerce' ); ?></th>
                            <th><?php esc_html_e( 'Orders', 'ggm-commerce' ); ?></th>
                            <th><?php esc_html_e( 'Refunds', 'ggm-commerce' ); ?></th>
                            <th><?php esc_html_e( 'Net Total', 'ggm-commerce' ); ?></th>
                            <th><?php esc_html_e( 'Format', 'ggm-commerce' ); ?></th>
                            <th><?php esc_html_e( 'Created', 'ggm-commerce' ); ?></th>
                            <th><?php esc_html_e( 'Actions', 'ggm-commerce' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $batches_data['batches'] as $batch ) : ?>
                            <tr>
                                <td class="ggmc-batch-number"><?php echo esc_html( $batch->batch_number ); ?></td>
                                <td>
                                    <?php
                                    echo esc_html(
                                        gmdate( 'M j, Y', strtotime( $batch->date_from ) ) . ' - ' .
                                        gmdate( 'M j, Y', strtotime( $batch->date_to ) )
                                    );
                                    ?>
                                </td>
                                <td><?php echo esc_html( $batch->order_count ); ?></td>
                                <td><?php echo esc_html( $batch->refund_count ); ?></td>
                                <td class="<?php echo $batch->net_total >= 0 ? 'ggmc-amount-positive' : 'ggmc-amount-negative'; ?>">
                                    <?php echo esc_html( number_format( $batch->net_total, 2 ) ); ?>
                                </td>
                                <td><?php echo esc_html( strtoupper( $batch->export_format ) ); ?></td>
                                <td>
                                    <?php echo esc_html( gmdate( 'M j, Y g:ia', strtotime( $batch->created_at ) ) ); ?>
                                    <br><small><?php echo esc_html( $batch->created_by_name ); ?></small>
                                </td>
                                <td class="ggmc-action-buttons">
                                    <?php if ( ! empty( $batch->download_url ) ) : ?>
                                        <a href="<?php echo esc_url( $batch->download_url ); ?>" class="button button-small"><?php esc_html_e( 'Download', 'ggm-commerce' ); ?></a>
                                    <?php else : ?>
                                        <span class="description"><?php esc_html_e( 'File not found', 'ggm-commerce' ); ?></span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <?php if ( $batches_data['total_pages'] > 1 ) : ?>
                    <p class="description" style="margin-top: 15px;">
                        <?php
                        printf(
                            /* translators: 1: current items shown, 2: total items */
                            esc_html__( 'Showing %1$d of %2$d export batches', 'ggm-commerce' ),
                            count( $batches_data['batches'] ),
                            intval( $batches_data['total'] )
                        );
                        ?>
                    </p>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <script>
        jQuery(document).ready(function($) {
            var ajaxUrl = '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>';
            var nonce = '<?php echo esc_js( $nonce ); ?>';

            // Preview button
            $('#ggmc-preview-btn').on('click', function() {
                var $btn = $(this);
                var $preview = $('#ggmc-preview-box');

                $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Loading...', 'ggm-commerce' ) ); ?>');

                $.post(ajaxUrl, {
                    action: 'ggmc_get_unexported_orders_count',
                    nonce: nonce,
                    date_from: $('#date_from').val(),
                    date_to: $('#date_to').val()
                }, function(response) {
                    $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Preview', 'ggm-commerce' ) ); ?>');

                    if (response.success) {
                        var data = response.data;
                        var totals = data.totals;

                        $('#preview-orders').text(totals.order_count);
                        $('#preview-refunds').text(totals.refund_count);
                        $('#preview-sales').text(formatCurrency(totals.total_sales));
                        $('#preview-refund-amount').text('-' + formatCurrency(totals.total_refunds));
                        $('#preview-tax').text(formatCurrency(totals.total_tax));
                        $('#preview-shipping').text(formatCurrency(totals.total_shipping));
                        $('#preview-net').text(formatCurrency(totals.net_total));

                        $preview.slideDown();

                        if (data.count === 0) {
                            showMessage('<?php echo esc_js( __( 'No unexported orders found in the selected date range.', 'ggm-commerce' ) ); ?>', 'error');
                        }
                    } else {
                        showMessage(response.data.message, 'error');
                    }
                });
            });

            // Generate export
            $('#ggmc-export-form').on('submit', function(e) {
                e.preventDefault();

                var $btn = $('#ggmc-generate-btn');
                var originalText = $btn.text();

                $btn.prop('disabled', true).html(originalText + '<span class="ggmc-spinner"></span>');

                $.post(ajaxUrl, {
                    action: 'ggmc_generate_transaction_export',
                    nonce: nonce,
                    date_from: $('#date_from').val(),
                    date_to: $('#date_to').val(),
                    format: $('#format').val(),
                    notes: $('#notes').val()
                }, function(response) {
                    $btn.prop('disabled', false).text(originalText);

                    if (response.success) {
                        showMessage(response.data.message + ' <a href="' + response.data.file_url + '" class="button button-small" style="margin-left: 10px;"><?php echo esc_js( __( 'Download Now', 'ggm-commerce' ) ); ?></a>', 'success');

                        // Reload page to show new batch in history
                        setTimeout(function() {
                            location.reload();
                        }, 2000);
                    } else {
                        showMessage(response.data.message, 'error');
                    }
                });
            });

            function formatCurrency(amount) {
                return parseFloat(amount).toFixed(2);
            }

            function showMessage(message, type) {
                var $container = $('#ggmc-export-message');
                $container.html('<div class="ggmc-message ggmc-message-' + type + '">' + message + '</div>');
            }
        });
        </script>
    </div>
    <?php
}
