<?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' ) );
$per_page  = isset( $_GET['per_page'] ) ? absint( $_GET['per_page'] ) : '';
$status    = isset( $_GET['status'] ) ? sanitize_text_field( $_GET['status'] ) : null;
$statuses  = Helper::get_affiliate_statuses();

$args = [
    'status' => $status,
    'from'   => $from,
    'to'     => $to,
];

$edit_url  = admin_url( 'user-edit.php' );
$admin_url = admin_url( 'admin.php' );
$data      = [];

/**
 * Prepare the data.
 */
global $wpdb;
$meta_table = "{$wpdb->base_prefix}usermeta";

$user_id_query = $wpdb->prepare(
    "SELECT `user_id` FROM `$meta_table` WHERE `meta_key` = '_wc_affiliate_status' %s",
    $status ? $wpdb->prepare( "AND `meta_value` = %s", $status ) : ''
);

$sql = "SELECT * FROM `$meta_table` WHERE `user_id` IN ( $user_id_query )";

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

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

foreach ( $affiliates as $affiliate ) {
    $user         = get_userdata( $affiliate->user_id );
    $format       = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
    $status       = get_user_meta( $affiliate->user_id, '_wc_affiliate_status', true );
    $applied_time = date( $format, $affiliate->meta_value );
    $registered   = date( $format, strtotime( $user->user_registered ) );
    $applied_time = apply_filters( 'wc_affiliate_applied_time_display', $applied_time, $affiliate->meta_value, $format, $affiliate->user_id );
    $registered   = apply_filters( 'wc_affiliate_registered_display', $registered, $user->user_registered, $format, $affiliate->user_id );

    $data[] = [
        'id'           => $affiliate->user_id,
        'affiliate_id' => "#{$affiliate->user_id}",
        'name'         => esc_html( $user->display_name ),
        'registered'   => esc_html( $registered ),
        'applied_time' => esc_html( $applied_time ),
        'status'       => esc_html( $status ),
        'action'       => sprintf(
            '<a href="%s" class="button">%s</a>
             <a href="%s#wf-title" class="button button-primary">%s</a>
             <a href="%s" class="button">%s</a>',
            esc_url( add_query_arg( [ 'page' => 'affiliates', 'affiliate' => $affiliate->user_id ], $admin_url ) ),
            __( 'Review', 'wc-affiliate' ),
            esc_url( add_query_arg( [ 'user_id' => $affiliate->user_id ], $edit_url ) ),
            __( 'Edit', 'wc-affiliate' ),
            esc_url( add_query_arg( [ 'page' => 'wc-affiliate', 'affiliate' => $affiliate->user_id ], $admin_url ) ),
            __( 'Report', 'wc-affiliate' )
        ),
    ];
}

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

/**
 * Config.
 */
$config = [
    'id'           => 'affiliate',
    'per_page'     => $per_page ? $per_page : 10,
    'columns'      => [
        'affiliate_id' => __( 'Affiliate ID', 'wc-affiliate' ),
        'name'         => __( 'Name', 'wc-affiliate' ),
        'registered'   => __( 'Registered', 'wc-affiliate' ),
        'applied_time' => __( 'Applied Time', 'wc-affiliate' ),
        'status'       => __( 'Status', 'wc-affiliate' ),
        'action'       => __( 'Action', 'wc-affiliate' ),
    ],
    'sortable'     => [ 'affiliate_id', 'name', 'registered', 'applied_time', 'status' ],
    'orderby'      => 'affiliate_id',
    'order'        => 'desc',
    'data'         => $data,
    'bulk_actions' => $_actions,
];

$disabled = empty( $data ) ? 'disabled' : '';
$_config  = $config['columns'];
unset( $_config['action'], $_REQUEST['_wp_http_referer'], $_REQUEST['action'], $_REQUEST['per_page'], $_REQUEST['action2'] );
?>

<div class="wrap wca-wrap">
    <?php if ( isset( $_GET['affiliate'] ) && ( $user = get_userdata( absint( sanitize_text_field( $_GET['affiliate'] ) ) ) ) !== false ) : ?>
        <h2>
            <?php
            printf(
                esc_html__( 'Affiliate #%1$d: %2$s', 'wc-affiliate' ),
                esc_html( $user->ID ),
                esc_html( $user->display_name )
            );
            ?>
            <a href="<?php echo esc_url( add_query_arg( 'page', 'affiliates', $admin_url ) ); ?>" class="button wf-al-reports">
                <?php esc_html_e( 'All Affiliates', 'wc-affiliate' ); ?>
            </a>
        </h2>
        <?php do_action( 'wc-affiliate-review-user' ); ?>
    <?php elseif ( isset( $_GET['action'] ) && sanitize_text_field( $_GET['action'] ) === 'add-new-affiliate' ) : ?>
        <h2><?php esc_html_e( 'New Affiliate', 'wc-affiliate' ); ?></h2>
        <?php do_action( 'wc-affiliate-new-affiliate' ); ?>
    <?php else : ?>
        <h2>
            <?php esc_html_e( 'Affiliates', 'wc-affiliate' ); ?>
            <a class="button" href="<?php echo esc_url( add_query_arg( [ 'page' => 'affiliates', 'action' => 'add-new-affiliate' ], $admin_url ) ); ?>">
                <?php esc_html_e( 'Add New', 'wc-affiliate' ); ?>
            </a>
            <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="affiliates" <?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="affiliates">
                <?php
                $table = new Codexpert\Plugin\Table( $config );
                $table->views();
                $table->prepare_items();
                $table->display();
                ?>
            </form>
        </div>
    <?php endif; ?>
</div>