<?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'] : '';

$profile_timezone = gigneo_timezone( $profile_id );
$primary_color    = gigneo_option( '_gigneo_ts_primary_color', apply_filters( 'gigneo_primary_color', '#7E4CFF' ) );
$secondary_color  = 'both' === $platform_type ? '#EBEBEB' : $primary_color;
?>
<div id="gn-earning-overview" class="gn-dashboard-section gn-section-earning-overview gn-h-100">
	<div class="gn-head">
		<h3 class="gn-title"><?php echo esc_html__( 'Overview', 'gigneo' ); ?></h3>
		<div class="gn-select2">
			<label class="gn-select">
				<select id="gn-earning-duration" class="gn-select" data-minimum-results-for-search="Infinity">
					<option value="last_7_days"><?php esc_html_e( 'Last 7 Days', 'gigneo' ); ?></option>
					<option value="last_30_days"><?php esc_html_e( 'Last 30 Days', 'gigneo' ); ?></option>
					<option value="last_6_months"><?php esc_html_e( 'Last 6 Months', 'gigneo' ); ?></option>
					<option value="last_12_months" selected><?php esc_html_e( 'Last 12 Months', 'gigneo' ); ?></option>
				</select>
			</label>
		</div>
	</div>
	<div class="gn-body">
		<div class="gn-account-chart gn-account-bar-chart">
			<?php
			global $wpdb;

			// Fetch all relevant invoices
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$invoices = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT p.ID,
                p.post_date_gmt,
                pm_type.meta_value AS type,
                pm_total.meta_value AS total
         FROM {$wpdb->posts} p
         INNER JOIN {$wpdb->postmeta} pm_profile 
            ON (p.ID = pm_profile.post_id AND pm_profile.meta_key = '_gigneo_pm_profile_id')
         INNER JOIN {$wpdb->postmeta} pm_type 
            ON (p.ID = pm_type.post_id AND pm_type.meta_key = '_gigneo_pm_type')
         INNER JOIN {$wpdb->postmeta} pm_total 
            ON (p.ID = pm_total.post_id AND pm_total.meta_key = '_gigneo_pm_total')
         WHERE p.post_type = 'gigneo_invoice'
           AND p.post_status = 'completed'
           AND pm_profile.meta_value = %d
           AND (pm_type.meta_value = 'service_order' OR pm_type.meta_value = 'job_order')",
					$profile_id
				)
			);
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

			$service_7  = array();
			$service_30 = array();
			$service_6  = array();
			$service_12 = array();

			$job_7  = array();
			$job_30 = array();
			$job_6  = array();
			$job_12 = array();

			// Add local datetime info for each invoice
			foreach ( $invoices as $invoice ) {
				// Formatted local date (for display if needed)
				$invoice->local_date = gigneo_datetime( $invoice->post_date_gmt, 'Y-m-d H:i:s', $profile_id );

				// Create DateTime object in user's timezone
				$dt = new DateTime( $invoice->post_date_gmt, new DateTimeZone( 'UTC' ) );
				$dt->setTimezone( new DateTimeZone( $profile_timezone ) );

				$invoice->local_timestamp = $dt->getTimestamp();
				$invoice->local_day       = $dt->format( 'D' );   // Mon, Tue, etc.
				$invoice->local_month     = $dt->format( 'M' );   // Apr, May, etc.
			}

			// LAST 7 DAYS
			for ( $i = 6; $i >= 0; $i-- ) {
				$day_label = ( new DateTime( 'now', new DateTimeZone( $profile_timezone ) ) )
						->modify( "-$i days" )
						->format( 'D' );

				$service_7[ $day_label ] = 0;
				$job_7[ $day_label ]     = 0;
			}

			foreach ( $invoices as $invoice ) {
				$local_dt = new DateTime( "@{$invoice->local_timestamp}" );
				$local_dt->setTimezone( new DateTimeZone( $profile_timezone ) );

				$seven_days_ago = ( new DateTime( 'now', new DateTimeZone( $profile_timezone ) ) )
						->modify( '-7 days' )
						->setTime( 0, 0 );

				if ( $local_dt >= $seven_days_ago ) {
					$day   = $local_dt->format( 'D' );
					$total = floatval( $invoice->total );

					if ( 'service_order' === $invoice->type ) {
						$service_7[ $day ] += $total;
					} else {
						$job_7[ $day ] += $total;
					}
				}
			}

			// LAST 30 DAYS (Weekly)
			for ( $i = 3; $i >= 0; $i-- ) {
				$week                = 'Week ' . ( 4 - $i );
				$service_30[ $week ] = 0;
				$job_30[ $week ]     = 0;
			}

			foreach ( $invoices as $invoice ) {
				$local_dt = new DateTime( "@{$invoice->local_timestamp}" );
				$local_dt->setTimezone( new DateTimeZone( $profile_timezone ) );

				$thirty_days_ago = ( new DateTime( 'now', new DateTimeZone( $profile_timezone ) ) )
						->modify( '-30 days' )
						->setTime( 0, 0 );

				if ( $local_dt >= $thirty_days_ago ) {
					$diff_days  = floor( ( $local_dt->getTimestamp() - $thirty_days_ago->getTimestamp() ) / 86400 );
					$week_index = min( 3, floor( $diff_days / 7 ) );
					$week_key   = 'Week ' . ( 4 - $week_index );
					$total      = floatval( $invoice->total );

					if ( 'service_order' === $invoice->type ) {
						$service_30[ $week_key ] += $total;
					} else {
						$job_30[ $week_key ] += $total;
					}
				}
			}

			// LAST 6 MONTHS
			for ( $i = 5; $i >= 0; $i-- ) {
				$month               = ( new DateTime( 'now', new DateTimeZone( $profile_timezone ) ) )
						->modify( "-$i months" )
						->format( 'M' );
				$service_6[ $month ] = 0;
				$job_6[ $month ]     = 0;
			}

			foreach ( $invoices as $invoice ) {
				$local_dt = new DateTime( "@{$invoice->local_timestamp}" );
				$local_dt->setTimezone( new DateTimeZone( $profile_timezone ) );

				$six_months_ago = ( new DateTime( 'now', new DateTimeZone( $profile_timezone ) ) )
						->modify( '-6 months' )
						->setTime( 0, 0 );

				if ( $local_dt >= $six_months_ago ) {
					$month = $local_dt->format( 'M' );
					$total = floatval( $invoice->total );

					if ( 'service_order' === $invoice->type ) {
						$service_6[ $month ] += $total;
					} else {
						$job_6[ $month ] += $total;
					}
				}
			}

			// LAST 12 MONTHS
			for ( $i = 11; $i >= 0; $i-- ) {
				$month               = ( new DateTime( 'now', new DateTimeZone( $profile_timezone ) ) )
						->modify( "-$i months" )
						->format( 'M' );
				$service_y[ $month ] = 0;
				$job_y[ $month ]     = 0;
			}

			foreach ( $invoices as $invoice ) {
				$local_dt = new DateTime( "@{$invoice->local_timestamp}" );
				$local_dt->setTimezone( new DateTimeZone( $profile_timezone ) );

				$one_year_ago = ( new DateTime( 'now', new DateTimeZone( $profile_timezone ) ) )
						->modify( '-12 months' )
						->setTime( 0, 0 );

				if ( $local_dt >= $one_year_ago ) {
					$month = $local_dt->format( 'M' );
					$total = floatval( $invoice->total );

					if ( 'service_order' === $invoice->type ) {
						$service_y[ $month ] += $total;
					} else {
						$job_y[ $month ] += $total;
					}
				}
			}

			// CHART DATA
			$chart_data = array(
				'last_7_days'    => array(
					'labels'   => array_keys( $service_7 ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Services', 'gigneo' ),
							'data'            => array_values( $service_7 ),
							'backgroundColor' => gigneo_hex_to_rgb( $primary_color ),
							'borderRadius'    => 4,
						),
						array(
							'label'           => esc_html__( 'Jobs', 'gigneo' ),
							'data'            => array_values( $job_7 ),
							'backgroundColor' => gigneo_hex_to_rgb( $secondary_color ),
							'borderRadius'    => 4,
						),
					),
				),
				'last_30_days'   => array(
					'labels'   => array_keys( $service_30 ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Services', 'gigneo' ),
							'data'            => array_values( $service_30 ),
							'backgroundColor' => gigneo_hex_to_rgb( $primary_color ),
							'borderRadius'    => 4,
						),
						array(
							'label'           => esc_html__( 'Jobs', 'gigneo' ),
							'data'            => array_values( $job_30 ),
							'backgroundColor' => gigneo_hex_to_rgb( $secondary_color ),
							'borderRadius'    => 4,
						),
					),
				),
				'last_6_months'  => array(
					'labels'   => array_keys( $service_6 ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Services', 'gigneo' ),
							'data'            => array_values( $service_6 ),
							'backgroundColor' => gigneo_hex_to_rgb( $primary_color ),
							'borderRadius'    => 4,
						),
						array(
							'label'           => esc_html__( 'Jobs', 'gigneo' ),
							'data'            => array_values( $job_6 ),
							'backgroundColor' => gigneo_hex_to_rgb( $secondary_color ),
							'borderRadius'    => 4,
						),
					),
				),
				'last_12_months' => array(
					'labels'   => array_keys( $service_y ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Services', 'gigneo' ),
							'data'            => array_values( $service_y ),
							'backgroundColor' => gigneo_hex_to_rgb( $primary_color ),
							'borderRadius'    => 4,
						),
						array(
							'label'           => esc_html__( 'Jobs', 'gigneo' ),
							'data'            => array_values( $job_y ),
							'backgroundColor' => gigneo_hex_to_rgb( $secondary_color ),
							'borderRadius'    => 4,
						),
					),
				),
			);

			// Platform Type Filter
			if ( 'both' !== $platform_type ) {
				foreach ( $chart_data as $key => &$data ) {
					if ( 'services' === $platform_type ) {
						unset( $data['datasets'][1] ); // Remove Jobs
					} elseif ( 'jobs' === $platform_type ) {
						unset( $data['datasets'][0] ); // Remove Services
					}
					$data['datasets'] = array_values( $data['datasets'] );
				}
				unset( $data ); // break reference
			}
			?>
			<canvas id="gn-earning-bar-chart-canvas" data-gn-chart="<?php echo esc_attr( wp_json_encode( $chart_data ) ); ?>"></canvas>
		</div>
	</div>
</div>
