<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Prevent direct access to the script.
}
$profile_id    = ! empty( $args['profile_id'] ) ? $args['profile_id'] : '';
$profile_type  = ! empty( $args['profile_type'] ) ? $args['profile_type'] : '';
$platform_type = ! empty( $args['platform_type'] ) ? $args['platform_type'] : '';

// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only filter parameters; validated below.
$current_page = max( 1, absint( isset( $_GET['step'] ) ? wp_unslash( $_GET['step'] ) : 0 ) );
$p_type       = ! empty( $_GET['type'] ) ? sanitize_text_field( wp_unslash( $_GET['type'] ) ) : '';

$date_range = '';
if ( ! empty( $_GET['date_range'] ) ) {
	$raw_range = sanitize_text_field( wp_unslash( $_GET['date_range'] ) );
	$parts     = explode( ' to ', $raw_range, 2 );

	if ( 2 === count( $parts ) ) {
		$from = trim( $parts[0] );
		$to   = trim( $parts[1] );

		if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $from ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $to ) ) {
			$from_parts = array_map( 'intval', explode( '-', $from ) );
			$to_parts   = array_map( 'intval', explode( '-', $to ) );

			if ( 3 === count( $from_parts ) && 3 === count( $to_parts )
					&& checkdate( $from_parts[1], $from_parts[2], $from_parts[0] )
					&& checkdate( $to_parts[1], $to_parts[2], $to_parts[0] )
					&& $from <= $to
			) {
				$date_range = $from . ' to ' . $to;
			}
		}
	}
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended -- Read-only filter parameters; validated below.

$show_per_page  = apply_filters( 'gigneo_credit_history_per_page', 10 );
$date_format    = get_option( 'date_format' );
$moderator_name = gigneo_moderator_name();
?>
<div id="gn-credit-history" class="gn-dashboard-section gn-section-credit-history">
	<div class="gn-head">
		<h3 class="gn-title"><?php echo esc_html__( 'Credit history', 'gigneo' ); ?></h3>
		<div class="gn-actions">
			<form id="gn-credit-history-search-form" class="gn-theme-form gn-account-history-form">
				<input type="hidden" name="source" value="account">
				<input type="hidden" name="ref" value="credits">
				<input type="hidden" name="step" value="<?php echo esc_attr( $current_page ); ?>">
				<div class="gn-form-field gn-select2">
					<label class="gn-select">
						<select name="type" data-minimum-results-for-search="Infinity">
							<option value="all" <?php selected( 'all' === $p_type || empty( $p_type ) ); ?>><?php echo esc_html__( 'All Type', 'gigneo' ); ?></option>
							<option value="credits_purchased" <?php selected( 'credits_purchased' === $p_type ); ?>> <?php echo esc_html__( 'Purchased', 'gigneo' ); ?></option>
							<option value="credits_used" <?php selected( 'credits_used' === $p_type ); ?>> <?php echo esc_html__( 'Used', 'gigneo' ); ?></option>
						</select>
					</label>
				</div>
				<div class="gn-range-filter">
					<?php
					$button_label = esc_html__( 'Date range', 'gigneo' );
					if ( ! empty( $date_range ) ) {
						$date_range_arr  = explode( ' to ', $date_range );
						$date_range_from = ! empty( $date_range_arr[0] ) ? $date_range_arr[0] : '';
						$date_range_to   = ! empty( $date_range_arr[1] ) ? $date_range_arr[1] : '';

						if ( ! empty( $date_range_from && ! empty( $date_range_to ) ) ) {
							$button_label  = date_i18n( $date_format, strtotime( $date_range_from ), true );
							$button_label .= ' - ';
							$button_label .= date_i18n( $date_format, strtotime( $date_range_to ), true );
						}
					}
					?>
					<button class="gn-range-toggle gn-btn gn-btn-md gn-btn-outline-grey" type="button" class="gn-btn">
						<?php echo esc_html( $button_label ); ?>
						<i class="hi hi-calendar" aria-hidden="true"></i>
					</button>
					<div class="gn-range-dropdown">
						<fieldset class="gn-form-fields">
							<div class="gn-datepicker">
								<input class="gn-date-range-input flatpickr-input" type="hidden" name="date_range" data-default-date="<?php echo esc_attr( $date_range ); ?>" data-date-format="Y-m-d" data-mode="range" data-inline="true" autocomplete="off">
							</div>
							<div class="gn-range-options-wrapper">
								<div class="gn-range-options">
									<button type="button" class=" gn-btn gn-btn-outline-grey gn-btn-sm gn-range-option"
											data-gn-range="last_7_days"><?php echo esc_html__( 'Last 7 Days', 'gigneo' ); ?></button>
									<button type="button" class=" gn-btn gn-btn-outline-grey gn-btn-sm gn-range-option"
											data-gn-range="last_30_days"><?php echo esc_html__( 'Last 30 Days', 'gigneo' ); ?></button>
									<button type="button" class=" gn-btn gn-btn-outline-grey gn-btn-sm gn-range-option"
											data-gn-range="last_6_months"><?php echo esc_html__( 'Last 6 Months', 'gigneo' ); ?></button>
									<button type="button" class=" gn-btn gn-btn-outline-grey gn-btn-sm gn-range-option"
											data-gn-range="last_12_months"><?php echo esc_html__( 'Last 12 Months', 'gigneo' ); ?></button>
								</div>
								<div class="gn-range-actions">
									<button type="submit" class="gn-btn gn-btn-primary gn-btn-sm"><?php echo esc_html__( 'Apply', 'gigneo' ); ?></button>
									<a href="<?php echo esc_url( gigneo_dashboard_url( 'account', 'credits' ) ); ?>" class="gn-btn gn-btn-sm"><?php echo esc_html__( 'Reset', 'gigneo' ); ?></a>
								</div>
							</div>
						</fieldset>
					</div>
				</div>
			</form>
		</div>
	</div>
	<div class="gn-body">
		<?php
		$history_args = array(
			'post_type'      => 'gigneo_invoice',
			'post_status'    => 'any',
			'posts_per_page' => $show_per_page,
			'paged'          => $current_page,
			'orderby'        => 'date',
			'order'          => 'DESC',
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
				'meta_query' => array(
					'relation' => 'AND',
					array(
						'key'     => '_gigneo_pm_profile_id',
						'value'   => $profile_id,
						'compare' => '=',
					),
				),
		);

		if ( is_array( $p_type ) || 'all' === $p_type ) {
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
			$history_args['meta_query'][] = array(
				'key'     => '_gigneo_pm_type',
				'value'   => is_array( $p_type ) ? $p_type : array( 'credit', 'bulk_credit', 'monthly_credit', 'credit_plan', 'job_creation', 'service_creation' ),
				'compare' => 'IN',
			);
		} else {
			$type_filter = sanitize_text_field( $p_type );

			switch ( $type_filter ) {

				case 'credits_purchased':
                    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					$history_args['meta_query'][] = array(
						'key'     => '_gigneo_pm_credit',
						'value'   => 0,
						'compare' => '>',
						'type'    => 'NUMERIC',
					);
					break;

				case 'credits_used':
                    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					$history_args['meta_query'][] = array(
						'key'     => '_gigneo_pm_credit',
						'value'   => 0,
						'compare' => '<',
						'type'    => 'NUMERIC',
					);
					break;

				case 'bulk_credit':
				case 'monthly_credit':
				case 'credit_plan':
                    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					$history_args['meta_query'][] = array(
						'key'     => '_gigneo_pm_type',
						'value'   => $type_filter,
						'compare' => '=',
					);
					break;

				default:
                    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					$history_args['meta_query'][] = array(
						'key'     => '_gigneo_pm_credit',
						'compare' => 'EXISTS',
					);
					break;
			}
		}

		if ( ! empty( $date_range ) ) {

			$date_range_arr  = explode( ' to ', $date_range );
			$date_range_from = ! empty( $date_range_arr[0] ) ? $date_range_arr[0] . ' 00:00:00' : '';
			$date_range_to   = ! empty( $date_range_arr[1] ) ? $date_range_arr[1] . ' 23:59:59' : '';

			if ( ! empty( $date_range_from ) && ! empty( $date_range_to ) ) {
				$history_args['date_query'] = array(
					array(
						'column'    => 'post_date_gmt',
						'after'     => $date_range_from,
						'before'    => $date_range_to,
						'inclusive' => true,
					),
				);
			}
		}

		$history_query = new WP_Query( $history_args );

		if ( $history_query->have_posts() ) {
			?>
			<div class="gn-table-wrapper">
				<table class="gn-table gn-table-borderless">
					<thead>
					<tr>
						<th><?php echo esc_html__( 'Activity', 'gigneo' ); ?></th>
						<th><?php echo esc_html__( 'Type', 'gigneo' ); ?></th>
						<th><?php echo esc_html__( 'Quantity', 'gigneo' ); ?></th>
						<th><?php echo esc_html__( 'Date', 'gigneo' ); ?></th>
					</tr>
					</thead>
					<tbody>
					<?php
					while ( $history_query->have_posts() ) {
						$history_query->the_post();
						$history_id            = get_the_ID();
						$history_timestamp_utc = get_post_time( 'Y-m-d H:i:s', true );
						$history_publish_date  = gigneo_datetime( $history_timestamp_utc, $date_format );
						$total_credits         = gigneo_post_meta( $history_id, '_gigneo_pm_credit' );
						$total_credits         = floatval( $total_credits );
						$total_amount          = gigneo_post_meta( $history_id, '_gigneo_pm_total' );
						$total_amount          = floatval( $total_amount );
						$moderator_note        = gigneo_post_meta( $history_id, '_gigneo_pm_moderator_note' );
						$credits_type          = gigneo_post_meta( $history_id, '_gigneo_pm_type' );
						$p_status              = get_post_status( $history_id );

						switch ( $credits_type ) {
							case 'service_creation':
								$activity_label = esc_html__( 'Service creation', 'gigneo' );
								break;
							case 'job_creation':
								$activity_label = esc_html__( 'Job creation', 'gigneo' );
								break;
							case 'proposal_submission':
								$activity_label = esc_html__( 'Proposal submission', 'gigneo' );
								break;
							case 'bulk_credit':
								$activity_label = sprintf(
									// translators: 2: Type
									esc_html__( 'Credit %1$s', 'gigneo' ),
									0 < $total_credits ? esc_html__( 'rewarded', 'gigneo' ) : esc_html__( 'deducted', 'gigneo' )
								);
								break;
							default:
								$activity_label = $total_credits > 0 ? esc_html__( 'Credit purchased', 'gigneo' ) : esc_html__( 'Credit used', 'gigneo' );
								break;
						}
						?>
						<tr>
							<td class="gn-activity">
								<?php echo esc_html( $activity_label ?? '—' ); ?>
							</td>
							<td class="gn-type">
							<span class="gn-status-tag gn-<?php echo esc_attr( $total_credits > 0 ? 'success' : 'warning' ); ?>">
								<?php
								$status_label = esc_html__( 'Spent', 'gigneo' );
								if ( $total_amount < 0 && $total_credits > 0 ) {
									$status_label = esc_html__( 'Purchased', 'gigneo' );
								} elseif ( empty( $total_amount ) && $total_credits < 0 ) {
									$status_label = esc_html__( 'Deducted', 'gigneo' );
								} elseif ( empty( $total_amount ) && $total_credits > 0 ) {
									$status_label = esc_html__( 'Rewarded', 'gigneo' );
								}
								echo esc_html( $status_label );
								?>
							</span>
							</td>
							<td class="gn-quality">
								<?php echo esc_html( $total_credits ); ?>
							</td>
							<td class="gn-date">
								<?php echo esc_html( $history_publish_date ); ?>
							</td>
						</tr>
						<?php
					}
					wp_reset_postdata();
					?>
					</tbody>
				</table>
			</div>
			<?php
			gigneo_pagination( $history_query, $current_page );
		} else {
			$not_found_args = array(
				'title'       => esc_html__( 'No credit history', 'gigneo' ),
				'description' => esc_html__( 'All your credit transaction history will appear here once available.', 'gigneo' ),
			);
			gigneo_not_found( 'account_credit_history', $not_found_args );
		}
		?>
	</div>
</div>
