<?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' ) );
$affiliate = isset( $_GET['affiliate'] ) ? absint( $_GET['affiliate'] ) : '';
$per_page  = isset( $_GET['per_page'] ) ? absint( $_GET['per_page'] ) : '';
$product   = isset( $_GET['product'] ) ? sanitize_text_field( $_GET['product'] ) : '';
$visit     = isset( $_GET['visit'] ) ? sanitize_text_field( $_GET['visit'] ) : '';
$currency  = get_wc_currency_symbol();

$statuses  = Helper::get_referral_statuses();
$admin_url = wp_nonce_url( add_query_arg( 'page', 'referrals', admin_url( 'admin.php' ) ) );
$visits_url = wp_nonce_url( add_query_arg( 'page', 'visits', admin_url( 'admin.php' ) ) );

$data = array();

/**
 * Prepare the data
 */
global $wpdb;
$referrals_table = "{$wpdb->prefix}wca_referrals";

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

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

if ( isset( $_GET['referral'] ) && '' !== $_GET['referral'] ) {
    $sql .= $wpdb->prepare( ' AND `id` = %d', absint( $_GET['referral'] ) );
}

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

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

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

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

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

$sql .= ' ORDER BY `time` DESC';

$referrals = $wpdb->get_results( $sql );

$format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );

$_actions = array();
foreach ( $statuses as $key => $status ) {
    $_actions[ $key ] = sprintf( __( 'Mark %s', 'wc-affiliate' ), $status );
}
$_actions['delete'] = __( 'Delete', 'wc-affiliate' );

foreach ( $referrals as $referral ) {
    $products  = '';
    $_products = maybe_unserialize( $referral->products );

    if ( is_array( $_products ) ) {
        $products = implode( ', ', array_map( 'esc_html', $_products ) );
    }

    $actions    = $_actions;
    unset( $actions[ $referral->payment_status ] );
    $action_url = add_query_arg( 'item_id', $referral->id, $admin_url );
    $action_btns = array();

    foreach ( $actions as $key => $action ) {
        $action_url    = add_query_arg( 'action', $key, $action_url );
        $action_btns[] = "<a href='" . esc_url( $action_url ) . "' class='wf-referral-action-button {$key} wl-action-{$key}'>" . esc_html( $action ) . '</a>';
    }

    $affiliate_user = get_userdata( $referral->affiliate );
    $affiliate_display_name = $affiliate_user ? esc_html( $affiliate_user->display_name ) : __( 'User not found', 'wc-affiliate' );

    $visit = add_query_arg( array( 'referral' => $referral->visit ), $visits_url );

    $data[] = array(
        'id'             => $referral->id,
        'affiliate'      => $affiliate_display_name,
        'commission'     => esc_html( $currency . $referral->commission ),
        'type'           => esc_html( $referral->type ),
        'visit'          => '<a href="' . esc_url( $visit ) . '">' . esc_html( $referral->visit ) . '</a>',
        'order_id'       => '<a href="' . esc_url( get_edit_post_link( $referral->order_id ) ) . '">' . esc_html( $referral->order_id ) . '</a>',
        'products'       => esc_html( $products ),
        'order_total'    => esc_html( $currency . $referral->order_total ),
        'payment_status' => esc_html( $referral->payment_status ),
        'actions'        => implode( ' | ', $action_btns ),
        'time'           => esc_html( date( $format, $referral->time ) ),
    );
}

$config = array(
    'id'           => 'referral',
    'per_page'     => '' !== $per_page ? $per_page : 10,
    'columns'      => array(
        'affiliate'      => __( 'Affiliate', 'wc-affiliate' ),
        'commission'     => __( 'Commission', 'wc-affiliate' ),
        'type'           => __( 'Type', 'wc-affiliate' ),
        'visit'          => __( 'Visit #', 'wc-affiliate' ),
        'order_id'       => __( 'Order #', 'wc-affiliate' ),
        'products'       => __( 'Products', 'wc-affiliate' ),
        'order_total'    => __( 'Order Total', 'wc-affiliate' ),
        'payment_status' => __( 'Status', 'wc-affiliate' ),
        'time'           => __( 'Time', 'wc-affiliate' ),
        'actions'        => __( 'Actions', 'wc-affiliate' ),
    ),
    'sortable'     => array( 'affiliate', 'visit', 'order_id', 'products', 'commission', 'payment_status', 'actions', 'time' ),
    'orderby'      => 'time',
    'order'        => 'desc',
    'data'         => $data,
    'bulk_actions' => $_actions,
);

$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">
    <h2>
        <?php esc_html_e( 'Referrals', '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='referrals' <?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="referrals">
            <?php
            $table = new Codexpert\Plugin\Table( $config );
            $table->views();
            $table->prepare_items();
            $table->display();
            ?>
        </form>
    </div>
</div>
