<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Prevent direct access
}

$profile_id    = ! empty( $args['profile_id'] ) ? $args['profile_id'] : '';
$profile_type  = ! empty( $args['profile_type'] ) ? $args['profile_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' ) );
?>
<div id="gn-wallet-overview" class="gn-dashboard-section gn-section-wallet-overview gn-h-100">
	<div class="gn-head">
		<h3 class="gn-title"><?php echo esc_html__( 'Cash flow', 'gigneo' ); ?></h3>
		<div class="gn-select2">
			<label class="gn-select">
				<select id="gn-wallet-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-line-chart">
			<?php
			global $wpdb;

			// Fetch all transactions
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$transactions = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT p.ID,
                p.post_date_gmt,
                CAST(pm_total.meta_value AS DECIMAL(10,2)) AS total,
                COALESCE(pm_type.meta_value, '') AS txn_type
                 FROM {$wpdb->posts} p
                 INNER JOIN {$wpdb->postmeta} pm_total 
                    ON (p.ID = pm_total.post_id AND pm_total.meta_key = '_gigneo_pm_total')
                 INNER JOIN {$wpdb->postmeta} pm_profile 
                    ON (p.ID = pm_profile.post_id AND pm_profile.meta_key = '_gigneo_pm_profile_id')
                 LEFT JOIN {$wpdb->postmeta} pm_type 
                    ON (p.ID = pm_type.post_id AND pm_type.meta_key = '_gigneo_pm_type')
                 WHERE p.post_type = 'gigneo_invoice'
                   AND p.post_status NOT IN ('draft', 'pending', 'processing')
                   AND pm_profile.meta_value = %d
                 ORDER BY p.post_date_gmt DESC",
					$profile_id
				)
			);
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

			$earning_7  = array();
			$deposit_7  = array();
			$spending_7 = array();
			$withdraw_7 = array();

			$earning_30  = array();
			$deposit_30  = array();
			$spending_30 = array();
			$withdraw_30 = array();

			$earning_6  = array();
			$deposit_6  = array();
			$spending_6 = array();
			$withdraw_6 = array();

			$earning_12  = array();
			$deposit_12  = array();
			$spending_12 = array();
			$withdraw_12 = array();

			// Add local timezone data
			foreach ( $transactions as $txn ) {
				$txn->local_date = gigneo_datetime( $txn->post_date_gmt, 'Y-m-d H:i:s', $profile_id );

				$dt = new DateTime( $txn->post_date_gmt, new DateTimeZone( 'UTC' ) );
				$dt->setTimezone( new DateTimeZone( $profile_timezone ) );

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

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

				$earning_7[ $day ]  = 0;
				$deposit_7[ $day ]  = 0;
				$spending_7[ $day ] = 0;
				$withdraw_7[ $day ] = 0;
			}

			foreach ( $transactions as $txn ) {
				$local_dt = new DateTime( "@{$txn->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' );
					$amount = floatval( $txn->total );
					$t_type = strtolower( $txn->txn_type );

					if ( $amount > 0 ) {
						if ( 'wallet' === $t_type ) {
							$deposit_7[ $day ] += $amount;
						} else {
							$earning_7[ $day ] += $amount;
						}
					} elseif ( 'withdraw' === $t_type ) {
						$withdraw_7[ $day ] += abs( $amount );
					} else {
						$spending_7[ $day ] += abs( $amount );
					}
				}
			}

			// LAST 30 DAYS
			for ( $i = 3; $i >= 0; $i-- ) {
				$week = 'Week ' . ( 4 - $i );

				$earning_30[ $week ]  = 0;
				$deposit_30[ $week ]  = 0;
				$spending_30[ $week ] = 0;
				$withdraw_30[ $week ] = 0;
			}

			foreach ( $transactions as $txn ) {
				$local_dt = new DateTime( "@{$txn->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 );

					$amount = floatval( $txn->total );
					$t_type = strtolower( $txn->txn_type );

					if ( $amount > 0 ) {
						if ( 'wallet' === $t_type ) {
							$deposit_30[ $week_key ] += $amount;
						} else {
							$earning_30[ $week_key ] += $amount;
						}
					} elseif ( 'withdraw' === $t_type ) {
						$withdraw_30[ $week_key ] += abs( $amount );
					} else {
						$spending_30[ $week_key ] += abs( $amount );
					}
				}
			}

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

				$earning_6[ $month ]  = 0;
				$deposit_6[ $month ]  = 0;
				$spending_6[ $month ] = 0;
				$withdraw_6[ $month ] = 0;

			}

			foreach ( $transactions as $txn ) {
				$local_dt = new DateTime( "@{$txn->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' );
					$amount = floatval( $txn->total );
					$t_type = strtolower( $txn->txn_type );

					if ( $amount > 0 ) {
						if ( 'wallet' === $t_type ) {
							$deposit_6[ $month ] += $amount;
						} else {
							$earning_6[ $month ] += $amount;
						}
					} elseif ( 'withdraw' === $t_type ) {
						$withdraw_6[ $month ] += abs( $amount );
					} else {
						$spending_6[ $month ] += abs( $amount );
					}
				}
			}

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

				$earning_12[ $month ]  = 0;
				$deposit_12[ $month ]  = 0;
				$spending_12[ $month ] = 0;
				$withdraw_12[ $month ] = 0;
			}

			foreach ( $transactions as $txn ) {
				$local_dt = new DateTime( "@{$txn->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' );
					$amount = floatval( $txn->total );
					$t_type = strtolower( $txn->txn_type );

					if ( $amount > 0 ) {
						if ( 'wallet' === $t_type ) {
							$deposit_12[ $month ] += $amount;
						} else {
							$earning_12[ $month ] += $amount;
						}
					} elseif ( 'withdraw' === $t_type ) {
						$withdraw_12[ $month ] += abs( $amount );
					} else {
						$spending_12[ $month ] += abs( $amount );
					}
				}
			}

			// ====================== CHART DATA ======================
			$chart_data = array(
				'last_7_days'    => array(
					'labels'   => array_keys( $earning_7 ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Deposits', 'gigneo' ),
							'data'            => array_values( $deposit_7 ),
							'backgroundColor' => 'rgb(46, 144, 250)',
							'borderColor'     => 'rgb(46, 144, 250)',
						),
						array(
							'label'           => esc_html__( 'Earnings', 'gigneo' ),
							'data'            => array_values( $earning_7 ),
							'backgroundColor' => 'rgb(23, 178, 106)',
							'borderColor'     => 'rgb(23, 178, 106)',
						),
						array(
							'label'           => esc_html__( 'Spending', 'gigneo' ),
							'data'            => array_values( $spending_7 ),
							'backgroundColor' => 'rgb(247, 144, 9)',
							'borderColor'     => 'rgb(247, 144, 9)',
						),
						array(
							'label'           => esc_html__( 'Withdrawals', 'gigneo' ),
							'data'            => array_values( $withdraw_7 ),
							'backgroundColor' => $primary_color,
							'borderColor'     => $primary_color,
						),
					),
				),
				'last_30_days'   => array( /* Same structure as above */ ),
				'last_6_months'  => array( /* Same structure as above */ ),
				'last_12_months' => array( /* Same structure as above */ ),
			);

			// Fill the remaining periods (to avoid repetition)
			$periods = array( 'last_30_days', 'last_6_months', 'last_12_months' );
			$sources = array(
				'30' => array( 'earning_30', 'deposit_30', 'spending_30', 'withdraw_30' ),
				'6'  => array( 'earning_6', 'deposit_6', 'spending_6', 'withdraw_6' ),
				'12' => array( 'earning_12', 'deposit_12', 'spending_12', 'withdraw_12' ),
			);

			foreach ( $periods as $period ) {
				$key                   = str_replace( array( 'last_', '_days', '_months' ), '', $period );
				$chart_data[ $period ] = array(
					'labels'   => array_keys( ${'earning_' . $key} ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Deposits', 'gigneo' ),
							'data'            => array_values( ${'deposit_' . $key} ),
							'backgroundColor' => 'rgb(46, 144, 250)',
							'borderColor'     => 'rgb(46, 144, 250)',
						),
						array(
							'label'           => esc_html__( 'Earnings', 'gigneo' ),
							'data'            => array_values( ${'earning_' . $key} ),
							'backgroundColor' => 'rgb(23, 178, 106)',
							'borderColor'     => 'rgb(23, 178, 106)',
						),
						array(
							'label'           => esc_html__( 'Spending', 'gigneo' ),
							'data'            => array_values( ${'spending_' . $key} ),
							'backgroundColor' => 'rgb(247, 144, 9)',
							'borderColor'     => 'rgb(247, 144, 9)',
						),
						array(
							'label'           => esc_html__( 'Withdrawals', 'gigneo' ),
							'data'            => array_values( ${'withdraw_' . $key} ),
							'backgroundColor' => $primary_color,
							'borderColor'     => $primary_color,
						),
					),
				);
			}

			// Employer Profile: Remove Earnings
			if ( 'employer' === $profile_type ) {
				foreach ( $chart_data as $key => &$data ) {
					unset( $data['datasets'][1] ); // Remove Earnings (index 1)
					$data['datasets'] = array_values( $data['datasets'] );
				}
				unset( $data );
			}
			?>
			<canvas id="gn-wallet-overview-line-chart-canvas" data-gn-chart="<?php echo esc_attr( wp_json_encode( $chart_data ) ); ?>"></canvas>
		</div>
	</div>
</div>
