<?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  = '#EBEBEB';
?>
<div id="gn-credit-overview" class="gn-dashboard-section gn-section-credits-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-credit-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 credit-related transactions (Removed type filter)
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$credits = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT 
            p.ID,
            p.post_date_gmt,
            CAST(pm_credit.meta_value AS DECIMAL(12,2)) AS credit_amount,
            COALESCE(pm_type.meta_value, '') AS txn_type
         FROM {$wpdb->posts} p
         INNER JOIN {$wpdb->postmeta} pm_credit ON (p.ID = pm_credit.post_id AND pm_credit.meta_key = '_gigneo_pm_credit')
         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 IN ('paid')
         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

			$purchased_7  = array();
			$purchased_30 = array();
			$purchased_6  = array();
			$purchased_12 = array();

			$used_7  = array();
			$used_30 = array();
			$used_6  = array();
			$used_12 = array();

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

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

				$credit->local_timestamp = $dt->getTimestamp();
				$credit->local_day       = $dt->format( 'D' );
				$credit->local_month     = $dt->format( 'M' );
			}

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

				$purchased_7[ $day ] = 0;
				$used_7[ $day ]      = 0;
			}

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

					if ( $amount > 0 ) {
						$purchased_7[ $day ] += $amount;      // Purchased Credits
					} else {
						$used_7[ $day ] += abs( $amount );      // Used Credits
					}
				}
			}

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

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

					if ( $amount > 0 ) {
						$purchased_30[ $week_key ] += $amount;
					} else {
						$used_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' );
				$purchased_6[ $month ] = 0;
				$used_6[ $month ]      = 0;
			}

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

					if ( $amount > 0 ) {
						$purchased_6[ $month ] += $amount;
					} else {
						$used_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' );
				$purchased_12[ $month ] = 0;
				$used_12[ $month ]      = 0;
			}

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

					if ( $amount > 0 ) {
						$purchased_12[ $month ] += $amount;
					} else {
						$used_12[ $month ] += abs( $amount );
					}
				}
			}

			// CREDIT CHART DATA
			$chart_data = array(
				'last_7_days'    => array(
					'labels'   => array_keys( $purchased_7 ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Purchased', 'gigneo' ),
							'data'            => array_values( $purchased_7 ),
							'backgroundColor' => $primary_color,
							'borderRadius'    => 4,
						),
						array(
							'label'           => esc_html__( 'Spent', 'gigneo' ),
							'data'            => array_values( $used_7 ),
							'backgroundColor' => $secondary_color,
							'borderRadius'    => 4,
						),
					),
				),
				'last_30_days'   => array(
					'labels'   => array_keys( $purchased_30 ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Purchased', 'gigneo' ),
							'data'            => array_values( $purchased_30 ),
							'backgroundColor' => $primary_color,
							'borderRadius'    => 4,
						),
						array(
							'label'           => esc_html__( 'Spent', 'gigneo' ),
							'data'            => array_values( $used_30 ),
							'backgroundColor' => $secondary_color,
							'borderRadius'    => 4,
						),
					),
				),
				'last_6_months'  => array(
					'labels'   => array_keys( $purchased_6 ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Purchased', 'gigneo' ),
							'data'            => array_values( $purchased_6 ),
							'backgroundColor' => $primary_color,
                            'borderRadius'    => 4,
						),
						array(
							'label'           => esc_html__( 'Spent', 'gigneo' ),
							'data'            => array_values( $used_6 ),
							'backgroundColor' => $secondary_color,
							'borderRadius'    => 4,
						),
					),
				),
				'last_12_months' => array(
					'labels'   => array_keys( $purchased_12 ),
					'datasets' => array(
						array(
							'label'           => esc_html__( 'Purchased', 'gigneo' ),
							'data'            => array_values( $purchased_12 ),
							'backgroundColor' => $primary_color,
                            'borderRadius'    => 4,
						),
						array(
							'label'           => esc_html__( 'Spent', 'gigneo' ),
							'data'            => array_values( $used_12 ),
							'backgroundColor' => $secondary_color,
							'borderRadius'    => 4,
						),
					),
				),
			);
			?>
			<canvas id="gn-credit-bar-chart-canvas" data-gn-chart="<?php echo esc_attr( wp_json_encode( $chart_data ) ); ?>"></canvas>
		</div>
	</div>
</div>
