<?php
use Codexpert\WC_Affiliate\Helper;

$from = isset( $_GET['from'] ) && '' !== $_GET['from'] 
    ? sanitize_text_field( $_GET['from'] ) 
    : date( 'F d, Y', current_time( 'timestamp' ) - Helper::date_range_diff() );

$to = isset( $_GET['to'] ) && '' !== $_GET['to'] 
    ? sanitize_text_field( $_GET['to'] ) 
    : date( 'F d, Y', current_time( 'timestamp' ) );

$txn_id    = isset( $_GET['txn'] ) ? sanitize_text_field( $_GET['txn'] ) : '';
$affiliate = isset( $_GET['affiliate'] ) ? absint( $_GET['affiliate'] ) : '';
$per_page  = isset( $_GET['per_page'] ) ? absint( $_GET['per_page'] ) : '';
$currency  = get_wc_currency_symbol();

$statuses  = Helper::get_transactions_statuses();
$admin_url = admin_url( 'admin.php' );

/**
 * Prepare the data
 */
global $wpdb;
$data               = array();
$transactions_table = "{$wpdb->prefix}wca_transactions";

if ( is_multisite() ) {
    $blog_id            = get_current_blog_id();
    $transactions_table = "{$wpdb->base_prefix}{$blog_id}_wca_transactions";
}

$sql = "SELECT * FROM $transactions_table WHERE 1 = 1";

if ( isset( $_GET['status'] ) && array_key_exists( sanitize_text_field( $_GET['status'] ), $statuses ) ) {
    $status = sanitize_text_field( $_GET['status'] );
    $sql   .= $wpdb->prepare( ' AND `status` = %s', $status );
}

if ( $from && $to ) {
    $form_date = strtotime( $from );
    $to_date   = strtotime( $to ) + DAY_IN_SECONDS - 1; // Include the entire day
    $sql      .= $wpdb->prepare( ' AND `process_at` BETWEEN %d AND %d', $form_date, $to_date );
}

if ( $txn_id ) {
    $sql .= $wpdb->prepare( ' AND `txn_id` LIKE %s', '%' . $wpdb->esc_like( $txn_id ) . '%' );
}

if ( $affiliate ) {
    $sql .= $wpdb->prepare( ' AND `affiliate` = %d', $affiliate );
}

$sql         .= ' ORDER BY `id` DESC';
$transactions = $wpdb->get_results( $sql );
$format       = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );

foreach ( $transactions as $txn ) {
    $data[] = array(
        'id'             => $txn->id,
        'affiliate'      => get_userdata( $txn->affiliate )->display_name,
        'amount'         => $currency . $txn->amount,
        'payment_method' => $txn->payment_method,
        'txn_id'         => $txn->txn_id,
        'request_at'     => date( $format, $txn->process_at ),
        'process_at'     => date( $format, $txn->process_at ),
        'action'         => '<a href="' . esc_url(
            add_query_arg(
                array(
                    'page'        => 'transactions',
                    'transaction' => $txn->id,
                ),
                $admin_url
            )
        ) . '" class="button wf-edit-transaction">' . esc_html__( 'Edit', 'wc-affiliate' ) . '</a>',
    );
}

/**
 * Config
 */
$config = array(
    'id'           => 'transaction',
    'per_page'     => '' !== $per_page ? $per_page : 10,
    'columns'      => array(
        'affiliate'      => esc_html__( 'Affiliate', 'wc-affiliate' ),
        'amount'         => esc_html__( 'Amount', 'wc-affiliate' ),
        'payment_method' => esc_html__( 'Payment Method', 'wc-affiliate' ),
        'txn_id'         => esc_html__( 'Transaction ID', 'wc-affiliate' ),
        'request_at'     => esc_html__( 'Requested', 'wc-affiliate' ),
        'process_at'     => esc_html__( 'Processed', 'wc-affiliate' ),
        'action'         => esc_html__( 'Action', 'wc-affiliate' ),
    ),
    'orderby'      => 'process_at',
    'order'        => 'desc',
    'data'         => $data,
    'bulk_actions' => array(),
);

$disabled = '';
if ( ! is_array( $data ) || empty( $data ) ) {
    $disabled = 'disabled';
}

$_config = $config['columns'];
unset( $_REQUEST['_wp_http_referer'], $_REQUEST['action'], $_REQUEST['per_page'], $_REQUEST['action2'] );
?>
<div class="wrap wca-wrap">
    <?php if ( isset( $_GET['transaction'] ) && '' !== sanitize_text_field( $_GET['transaction'] ) ) : ?>
        <h2>
            <?php
            if ( 'new' === $_GET['transaction'] ) {
                esc_html_e( 'New transaction', 'wc-affiliate' );
            } else {
                // Translators: %d is the transaction ID number.
                printf( esc_html__( 'Transaction #%d:', 'wc-affiliate' ), absint( $_GET['transaction'] ) );
            }
            ?>
        </h2>
        <?php do_action( 'wc-affiliate-transaction-form' ); ?>
    <?php else : ?>
        <h2>
            <?php esc_html_e( 'Transactions', 'wc-affiliate' ); ?>
            <button 
                class="button button-primary" 
                id="wc-affiliate-export-report-btn" 
                data-params='<?php echo esc_attr( wp_json_encode( $_REQUEST ) ); ?>' 
                data-headings='<?php echo esc_attr( wp_json_encode( $_config ) ); ?>' 
                data-name='transactions' 
                <?php echo esc_attr( $disabled ); ?>>
                <?php esc_html_e( 'Export Report', 'wc-affiliate' ); ?>
            </button>
        </h2>
        <div class="wf-wrap">
            <form method="GET">
                <input type="hidden" name="page" value="transactions">
                <?php
                $table = new Codexpert\Plugin\Table( $config );
                $table->views();
                $table->prepare_items();
                $table->display();
                ?>
            </form>
        </div>
    <?php endif; ?>
</div>
