<?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'] : '';
$credit_system = ! empty( $args['credit_system'] ) ? $args['credit_system'] : '';

// 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 ) );

$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_earning_invoice_per_page', 5 );
$date_format   = get_option( 'date_format' );
?>
<div id="gn-earning-invoices" class="gn-dashboard-section gn-section-earning-invoices">
	<div class="gn-head">
		<h3 class="gn-title"><?php echo esc_html__( 'Invoices', 'gigneo' ); ?></h3>
		<div class="gn-actions">
			<form id="gn-earning-invoice-search-form" class="gn-theme-form gn-account-invoice-form">
				<input type="hidden" name="source" value="account">
				<input type="hidden" name="ref" value="earning">
				<input type="hidden" name="step" value="<?php echo esc_attr( $current_page ); ?>">
				<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_class  = 'gn-btn-primary';
							$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-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', 'earning' ) ); ?>" 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
		$invoice_args = array(
			'post_type'      => 'gigneo_invoice',
			'post_status'    => 'completed',
			'posts_per_page' => $show_per_page,
			'orderby'        => 'date',
			'order'          => 'DESC',
			'paged'          => $current_page,
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
			'meta_query'     => array(
				'relation' => 'AND',
				array(
					'key'     => '_gigneo_pm_type',
					'value'   => array( 'service_order', 'job_order' ),
					'compare' => 'IN',
				),
				array(
					'key'     => '_gigneo_pm_profile_id',
					'value'   => $profile_id,
					'compare' => '=',
				),
			),
		);

		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 ( in_array( 'timezone', gigneo_active_modules(), true ) ) {
				$date_range_from_arr = gigneo_prepare_datetime( $date_range_from );
				$date_range_to_arr   = gigneo_prepare_datetime( $date_range_to );

				$date_range_from = ! empty( $date_range_from_arr['gmt'] ) ? $date_range_from_arr['gmt'] : '';
				$date_range_to   = ! empty( $date_range_to_arr['gmt'] ) ? $date_range_to_arr['gmt'] : '';
			}

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

		$invoice_query = new WP_Query( $invoice_args );

		if ( $invoice_query->have_posts() ) {
			?>
		<div class="gn-table-wrapper">
		<table class="gn-table gn-table-borderless">
			<thead>
			<tr>
				<th class="gn-invoice-id">
					<?php echo esc_html__( 'Invoice ID', 'gigneo' ); ?>
				</th>
				<th class="gn-participant">
					<?php echo esc_html__( 'Employer', 'gigneo' ); ?>
				</th>
				<th class="gn-order-id">
					<?php echo esc_html__( 'Order ID', 'gigneo' ); ?>
				</th>
				<th class="gn-amount">
					<?php echo esc_html__( 'Amount', 'gigneo' ); ?>
				</th>
				<th class="gn-date">
					<?php echo esc_html__( 'Date', 'gigneo' ); ?>
				</th>
				<th class="gn-action">
					<?php echo esc_html__( 'Action', 'gigneo' ); ?>
				</th>
			</tr>
			</thead>
			<tbody>
			<?php
			while ( $invoice_query->have_posts() ) {
				$invoice_query->the_post();
				$invoice_id                          = get_the_ID();
				$invoice_status                      = get_post_status( $invoice_id );
				$invoice_type                        = gigneo_post_meta( $invoice_id, '_gigneo_pm_type' );
				$invoice_total                       = gigneo_post_meta( $invoice_id, '_gigneo_pm_total' );
				$invoice_order_id                    = gigneo_post_meta( $invoice_id, '_gigneo_pm_order_id' );
				$invoice_order_employer_id           = gigneo_post_meta( $invoice_order_id, '_gigneo_pm_profile_id' );
				$invoice_order_employer_thumbnail_id = get_post_thumbnail_id( $invoice_order_employer_id );
				$invoice_timestamp_utc               = get_post_time( 'Y-m-d H:i:s', true );
				$invoice_publish_date                = gigneo_datetime( $invoice_timestamp_utc, $date_format );
				$invoice_status_label                = gigneo_status_label( $invoice_status );

				$invoice_label = gigneo_invoice_label( $invoice_type );
				?>
				<tr>
					<td class="gn-invoice-id">
						<?php echo esc_html( gigneo_format_id( $invoice_id, 'invoice', false ) ); ?>
					</td>
					<td class="gn-participant">
						<div class="gn-profile">
							<figure class="gn-avatar">
								<?php gigneo_attachment_image_src( $invoice_order_employer_thumbnail_id ?? 0, 'thumbnail', 'profile' ); ?>
							</figure>
							<span class="gn-name"><?php echo esc_html( gigneo_profile_name( $invoice_order_employer_id ) ); ?></span>
						</div>
					</td>
					<td class="gn-order-id">
						<?php echo esc_html( gigneo_format_id( $invoice_order_id, 'order', false ) ); ?>
					</td>
					<td class="gn-amount">
						<?php echo esc_html( gigneo_price_format( $invoice_total ?? 0, true ) ); ?>
					</td>
					<td class="gn-date">
						<?php echo esc_html( $invoice_publish_date ); ?>
					</td>
					<td class="gn-actions">
						<button type="button" data-gn-invoice-id="<?php echo esc_attr( $invoice_id ); ?>" class="gn-btn gn-invoice-download">
							<i class="hi hi-arrow-down-tray" aria-hidden="true"></i>
						</button>
					</td>
				</tr>
				<?php
			}
			wp_reset_postdata();
			?>
			</tbody>
		</table>
		</div>
			<?php
			gigneo_pagination( $invoice_query, $current_page );
		} else {
			$not_found_args = array(
				'title'       => esc_html__( 'No invoices', 'gigneo' ),
				'description' => esc_html__( 'All your earning invoices will appear here once available.', 'gigneo' ),
			);
			gigneo_not_found( 'account_earning_invoice', $not_found_args );
		}
		?>
	</div>
</div>
