<?php
if ( ! function_exists( 'wpj_get_graph' ) ) {
	function wpj_get_graph( $uid = '', $disp_type = 'all', $select_year = '', $select_month = '', $graph_type = '' ) {
		if ( ! $uid )          $uid          = get_current_user_id();
		if ( ! $disp_type )    $disp_type    = WPJ_Form::request( 'disp_type' );
		if ( ! $select_year )  $select_year  = WPJ_Form::request( 'select_year' );
		if ( ! $select_month ) $select_month = WPJ_Form::request( 'select_month' );
		if ( ! $graph_type )   $graph_type   = WPJ_Form::request( 'graph_type' );
		if ( ! $graph_type )   $graph_type   = is_page( wpj_get_option( 'wpjobster_my_account_page_id' ) ) || is_page( wpj_get_option( 'wpjobster_my_account_sales_page_id' ) ) ? 'sales' : 'shopping';

		$type  = $disp_type    = ( $disp_type    == '' ? 'all'       : $disp_type );
		$year  = $select_year  = ( $select_year  == '' ? date( 'Y' ) : $select_year );
		$month = $select_month = ( $select_month == '' ? date( 'm' ) : $select_month );

		if ( $type == 'all' ) {
			if ( $uid ) {
				$user_registered = wpj_get_user( 'user_registered', ['ID' => $uid], 'var' );
				$from_number     = $user_registered ? date( 'Y', strtotime( $user_registered ) ) : date( 'Y' );
				$to_number       = date( 'Y' ) + 1;
			}

		} elseif ( $type == 'year' ) {
			$from_number = 01;

			if ( $select_year == date( 'Y' ) ) $to_number = date( 'm' );
			else $to_number = 12;

		} elseif ( $type == 'month' ) {
			$from_number = 01;
			$months_days = [1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31];

			if ( $select_month == date( 'm' ) && $select_year == date( 'Y' ) ) {
				$to_number = date( 'd' );

			} else {
				$to_number = $months_days[$month];

				if ( $year%4 == 0 && $month == 2 ) $to_number = 29;

			}

		} elseif ( $type == 'lastweek' ) {
			$from_number = 00;
			$to_number   = 07;

		}

		if ( ! empty( $from_number ) && ! empty( $to_number ) ) {
			for ( $i = $from_number; $i <= $to_number; $i++ ) {
				if ( $type == 'all' )
					$result_month[$i] = wpj_get_unix_timestamp( "$i-01-01" );

				if ( $type == 'year' )
					$result_month[$i] = wpj_get_unix_timestamp( "$year-$i-01" );

				if ( $type == 'month' )
					$result_month[$i] = wpj_get_unix_timestamp( "$year-$month-$i" );

				if ( $type == 'lastweek' ) {
					$todays_date = date_create( date( "Y-m-d" ) );

					date_add( $todays_date, date_interval_create_from_date_string( "-{$i} days" ) );

					$dt               = date_format( $todays_date, "Y-m-d" );
					$week_arr[$i]     = $dt;
					$result_month[$i] = wpj_get_unix_timestamp( $dt );
				}

				if ( $i == $from_number ) {
					if ( $type == 'lastweek' ) {
						$todays_date = date_create( date( 'Y-m-d' ) );

						date_add( $todays_date, date_interval_create_from_date_string( "-{$to_number} days" ) );

						$date_max = wpj_get_unix_timestamp( date_format( $todays_date, 'Y-m-d' ) );

					} else {
						$date_max = ! empty( $result_month[$i] ) ? $result_month[$i] : current_time( 'timestamp', 1 );

					}

					$query_fields  = sprintf( 'credit_balance AS sum_amount, from_unixtime(%d) AS fromdt', $date_max );
					$query_between = ['column' => 'datemade', 'date_min' => 0, 'date_max' => $date_max];

					$first_credit_balance = wpj_get_user_credit_log( $query_fields, ['uid' => $uid], 'row', $query_between );

				}

				if ( $i > $from_number && ! empty( $result_month ) ) {
					if ( $type == 'lastweek' ) {
						foreach ( wpj_get_transaction_amount_array( $i, $result_month[$i], $result_month[( $i - 1 )], $uid ) as $key => $value ) {
							$$key[$i] = $value;
						}

					} else {
						foreach ( wpj_get_transaction_amount_array( $i-1, $result_month[( $i - 1 )], $result_month[$i], $uid ) as $key => $value ) {
							$$key[$i-1] = $value;
						}

					}
				}
			}
		}

		if ( isset( $type ) && ( $type == 'month' || $type == 'year' ) ) {
			$result_month[$i] = wpj_get_unix_timestamp( ( $year + 1 ) . "-01-01" );

			foreach ( wpj_get_transaction_amount_array( $i-1, $result_month[( $i - 1 )], $result_month[$i], $uid ) as $key => $value ) {
				$$key[$i-1] = $value;
			}
		}

		$data_table       = '';
		$element_count    = 0;
		$data_table_arr[] = [
			$disp_type,
			__( 'Gross Earned', 'wpjobster' ),
			__( 'Net Earned', 'wpjobster' ),
			__( 'Active Orders', 'wpjobster' ),
			__( 'Completed Orders', 'wpjobster' ),
			__( 'Credit Balance', 'wpjobster' )
		];

		if ( $type == 'lastweek' ) {
			$todays_date = date_create( date( "Y-m-d" ) );

			date_add( $todays_date, date_interval_create_from_date_string( "+1 days" ) );

			$dt = date( 'Y-m-d' );

			$result_month[-1] = wpj_get_unix_timestamp( $dt );
			$week_arr[-1]     = $dt;

			foreach ( wpj_get_transaction_amount_array( '-1', $result_month[0], $result_month[-1], $uid ) as $key => $value ) {
				$$key[-1] = $value;
			}

			$from_number = -1;
			$key_count   =  0;

			$result_earned_gross2   = $result_earned_gross;
			$result_earned_net2     = $result_earned_net;
			$result_spent2          = $result_spent;
			$result_active2         = $result_active;
			$result_completed2      = $result_completed;
			$result_credit_balance2 = $result_credit_balance;

			$result_earned_gross   = [];
			$result_earned_net     = [];
			$result_spent          = [];
			$result_active         = [];
			$result_completed      = [];
			$result_credit_balance = [];

			for ( $i = $to_number; $i >= $from_number; $i-- ) {
				if ( isset( $result_earned_gross2[$i-1] ) ) {
					$result_earned_gross[]   = $result_earned_gross2[$i-1];
					$result_earned_net[]     = $result_earned_net2[$i-1];
					$result_spent[]          = $result_spent2[$i-1];
					$result_active[]         = $result_active2[$i-1];
					$result_completed[]      = $result_completed2[$i-1];
					$result_credit_balance[] = $result_credit_balance2[$i-1];
					$week_arr2[]             = $week_arr[$i-1];

					$key_count++;
				}
			}

			foreach ( $result_credit_balance as $key_c => $res_credit_bal ) {
				if ( isset( $res_credit_bal->sum_amount ) ) {
					$first_credit_balance = $res_credit_bal;

				} else {
					$result_credit_balance[$key_c] = $first_credit_balance;

				}
			}

			for ( $i = 0; $i < $key_count; $i++ ) {
				$key = $i; $element_count++;

				$data_table .= "['{$week_arr2[$key]}',";

				if ( $graph_type == 'sales' ) {
					$data_table .= ( ! empty( $result_earned_gross[$key]->sum_amount ) ? $result_earned_gross[$key]->sum_amount : '0' ) . ", ";
					$data_table .= ( ! empty( $result_earned_net[$key]->sum_amount ) ? $result_earned_net[$key]->sum_amount : '0' ) . ", ";
					$data_table .= ( ! empty( $result_withdraw[$key]->sum_amount ) ? $result_withdraw[$key]->sum_amount : '0' ) . ",";
					$data_table .= ( ! empty( $result_pending[$key]->sum_amount ) ? $result_pending[$key]->sum_amount : '0' ) . ",";

				} else {
					$data_table .= ( ! empty( $result_spent[$key]->sum_amount ) ? $result_spent[$key]->sum_amount : '0' ) . ", ";
					$data_table .= ( ! empty( $result_active[$key]->sum_amount ) ? $result_active[$key]->sum_amount : '0' ) . ",";
					$data_table .= ( ! empty( $result_completed[$key]->sum_amount ) ? $result_completed[$key]->sum_amount : '0' ) . ",";

				}

				$data_table .= ( ! empty( $result_credit_balance[$key]->sum_amount ) ? $result_credit_balance[$key]->sum_amount : '0' ) . "],";

				unset( $tmp_arr );

				$tmp_arr[] = $key;

				if ( $graph_type == 'sales' ) {
					$tmp_arr[] = ( ! empty( $result_earned_gross[$key]->sum_amount ) ? $result_earned_gross[$key]->sum_amount : '0' ) . ", ";
					$tmp_arr[] = ( ! empty( $result_earned_net[$key]->sum_amount ) ? $result_earned_net[$key]->sum_amount : '0' ) . ", ";
					$tmp_arr[] = ( ! empty( $result_withdraw[$key]->sum_amount ) ? $result_withdraw[$key]->sum_amount : '0' );
					$tmp_arr[] = ( ! empty( $result_pending[$key]->sum_amount ) ? $result_pending[$key]->sum_amount : '0' );

				} else {
					$tmp_arr[] = ( ! empty( $result_spent[$key]->sum_amount ) ? $result_spent[$key]->sum_amount : '0' );
					$tmp_arr[] = ( ! empty( $result_active[$key]->sum_amount ) ? $result_active[$key]->sum_amount : '0' );
					$tmp_arr[] = ( ! empty( $result_completed[$key]->sum_amount ) ? $result_completed[$key]->sum_amount : '0' );

				}

				$tmp_arr[] = ( ! empty( $result_credit_balance[$key]->sum_amount ) ? $result_credit_balance[$key]->sum_amount : '0' );

				$data_table_arr[] = $tmp_arr;
			}

		} else {
			foreach ( $result_credit_balance as $key_c => $res_credit_bal ) {
				if ( isset( $res_credit_bal->sum_amount ) ) {
					$first_credit_balance = $res_credit_bal;

				} else {
					$result_credit_balance[$key_c] = $first_credit_balance;

				}
			}

			for ( $i = $from_number; $i <= $to_number; $i++ ) {
				$key = $i;

				$element_count++;

				if ( $type != 'all' || $i != $to_number ) {
					$data_table .= "['$key',";

					if ( $graph_type == 'sales' ) {
						$data_table .= ( ! empty( $result_earned_gross[$key]->sum_amount ) ? $result_earned_gross[$key]->sum_amount : '0' ) . ", ";
						$data_table .= ( ! empty( $result_earned_net[$key]->sum_amount )   ? $result_earned_net[$key]->sum_amount   : '0' ) . ", ";
						$data_table .= ( ! empty( $result_withdraw[$key]->sum_amount )     ? $result_withdraw[$key]->sum_amount     : '0' ) . ",";
						$data_table .= ( ! empty( $result_pending[$key]->sum_amount )      ? $result_pending[$key]->sum_amount      : '0' ) . ",";

					} else {
						$data_table .= ( ! empty( $result_spent[$key]->sum_amount )     ? $result_spent[$key]->sum_amount     : '0' ) . ", ";
						$data_table .= ( ! empty( $result_active[$key]->sum_amount )    ? $result_active[$key]->sum_amount    : '0' ) . ",";
						$data_table .= ( ! empty( $result_completed[$key]->sum_amount ) ? $result_completed[$key]->sum_amount : '0' ) . ",";

					}

					$data_table .= ( ! empty( $result_credit_balance[$key]->sum_amount ) ? $result_credit_balance[$key]->sum_amount : '0' ) . "],";

					$tmp_arr[] = $key;

					if ( $graph_type == 'sales' ) {
						$tmp_arr[] = ( ! empty( $result_earned_gross[$key]->sum_amount ) ? $result_earned_gross[$key]->sum_amount : '0' ) . ", ";
						$tmp_arr[] = ( ! empty( $result_earned_net[$key]->sum_amount )   ? $result_earned_net[$key]->sum_amount   : '0' ) . ", ";
						$tmp_arr[] = ( ! empty( $result_withdraw[$key]->sum_amount )     ? $result_withdraw[$key]->sum_amount     : '0' );
						$tmp_arr[] = ( ! empty( $result_pending[$key]->sum_amount )      ? $result_pending[$key]->sum_amount      : '0' );

					} else {
						$tmp_arr[] = ( ! empty( $result_spent[$key]->sum_amount )     ? $result_spent[$key]->sum_amount     : '0' );
						$tmp_arr[] = ( ! empty( $result_active[$key]->sum_amount )    ? $result_active[$key]->sum_amount    : '0' );
						$tmp_arr[] = ( ! empty( $result_completed[$key]->sum_amount ) ? $result_completed[$key]->sum_amount : '0' );

					}

					$tmp_arr[] = ( ! empty( $result_credit_balance[$key]->sum_amount ) ? $result_credit_balance[$key]->sum_amount : '0' );

					$data_table_arr[] = $tmp_arr;
				}
			}
		}

		$data_table2 = $data_table;

		$data_table = "[";

		if ( $graph_type == 'shopping' ) {
			$data_table .= "['" . $disp_type . "', '" . __( 'Total spent', 'wpjobster' ) . "', '" . __( 'Active Orders', 'wpjobster' ) . "', '" . __( 'Completed Orders', 'wpjobster' ) . "', '" . __( 'Current Balance', 'wpjobster' ) . "'], " . trim( $data_table2, "," ) . "]";

		} elseif ( $graph_type == 'sales' ) {
			$data_table .= "['" . $disp_type . "', '" . __( 'Gross Earned', 'wpjobster' ) . "', '" . __( 'Net Earned', 'wpjobster' ) . "', '" . __( 'Withdrawal', 'wpjobster' ) . "', '" . __( 'Pending Clearance', 'wpjobster' ) . "', '" . __( 'Available Funds', 'wpjobster' ) . "'], " . trim( $data_table2, "," ) . "]";

		} else {
			$data_table .= "['" . $disp_type . "', '" . __( 'Gross Earned', 'wpjobster' ) . "', '" . __( 'Net Earned', 'wpjobster' ) . "', '" . __( 'Completed Orders', 'wpjobster' ) . "', '" . __( 'Withdrawal', 'wpjobster' ) . "', '" . __( 'Pending Clearance', 'wpjobster' ) . "', '" . __( 'Available Funds', 'wpjobster' ) . "'], " . trim( $data_table2, "," ) . "]";

		}

		$data_table_ajax = "['" . $disp_type . "', '" . __( 'Gross Earned', 'wpjobster' ) . "', '" . __( 'Net Earned', 'wpjobster' ) . "', '" . __( 'Active Orders', 'wpjobster' ) . "', '" . __( 'Completed Orders', 'wpjobster' ) . "', '" . __( 'Withdrawal', 'wpjobster' ) . "', '" . __( 'Credit Balance', 'wpjobster' ) . "'], " . trim( $data_table2, "," );

		$graph_data = [
			'data_table'      => $data_table,
			'type'            => $type,
			'disp_type'       => $disp_type,
			'select_month'    => $select_month,
			'select_year'     => $select_year,
			'total_elements'  => $element_count,
			'data_table_arr'  => $data_table_arr,
			'data_table_ajax' => $data_table_ajax
		];

		if ( wpj_is_ajax_call() ) {
			echo json_encode( $graph_data );

			wp_die();
		}

		return $graph_data;
	}
}

if ( ! function_exists( 'wpj_get_transaction_amount_by_date' ) ) {
	function wpj_get_transaction_amount_by_date( $fromtimestamp, $totimestamp, $uid, $action = 'earning' ) {
		if ( $action == 'gross_earning' || $action == 'net_earning' ) {
			$query_fields  = sprintf( '*, mc_gross AS sum_amount, from_unixtime(%d) AS fromdt, from_unixtime(%d)', $fromtimestamp, $totimestamp );
			$query_where   = ['p.post_author' => $uid, 'o.payment_status' => 'completed', 'o.seller_confirmation' => 1, 'o.clearing_period' => 1];
			$query_between = ['column' => 'o.date_made', 'date_min' => $fromtimestamp, 'date_max' => $totimestamp];

			$result_data = wpj_get_job_order_post( $query_fields, $query_where, 'results', $query_between );

		} elseif ( $action == 'spending' ) {
			$query_between = ['column' => 'date_made', 'date_min' => $fromtimestamp, 'date_max' => $totimestamp];

			$data             = new stdClass();
			$data->sum_amount = wpj_get_job_orders_total_spent_by_user( $uid, $query_between );
			$result_data      = [$data];

		} elseif ( $action == 'active' ) {
			$query_fields  = sprintf( 'SUM(mc_gross) AS sum_amount, from_unixtime(%d) AS fromdt, from_unixtime(%d)', $fromtimestamp, $totimestamp );
			$query_where   = ['uid' => $uid, 'done_seller' => 0, 'done_buyer' => 0, 'closed' => 0];
			$query_between = ['column' => 'date_made', 'date_min' => $fromtimestamp, 'date_max' => $totimestamp];

			$result_data = wpj_get_job_order( $query_fields, $query_where, 'results', $query_between );

		} elseif ( $action == 'completed' ) {
			$query_fields  = sprintf( 'SUM(mc_gross) AS sum_amount, from_unixtime(%d) AS fromdt, from_unixtime(%d) AS todt', $fromtimestamp, $totimestamp );
			$query_where   = ['uid' => $uid, 'done_seller' => 1, 'done_buyer' => 1, 'completed' => 1, 'clearing_period' => 1];
			$query_between = ['column' => 'date_made', 'date_min' => $fromtimestamp, 'date_max' => $totimestamp];

			$result_data = wpj_get_job_order( $query_fields, $query_where, 'results', $query_between );

		} elseif ( $action == 'credit_balance' ) {
			$query_fields  = sprintf( 'credit_balance AS sum_amount, from_unixtime(%d) AS fromdt, from_unixtime(%d) AS todt', $fromtimestamp, $totimestamp );
			$query_where   = ['uid' => $uid];
			$query_between = ['column' => 'datemade', 'date_min' => $fromtimestamp, 'date_max' => $totimestamp];

			$result_data = wpj_get_user_credit_log( $query_fields, $query_where, 'results', $query_between );

		} elseif ( $action == 'withdraw' ) {
			$query_fields  = sprintf( 'SUM(amount) AS sum_amount, from_unixtime(%d) AS fromdt, from_unixtime(%d) AS todt', $fromtimestamp, $totimestamp );
			$query_where   = ['uid' => $uid, 'done' => 1];
			$query_between = ['column' => 'datemade', 'date_min' => $fromtimestamp, 'date_max' => $totimestamp];

			$result_data = wpj_get_withdrawal_order( $query_fields, $query_where, 'results', $query_between );

		} elseif ( $action == 'pending_clearance' ) {
			$query_fields  = sprintf( 'SUM(mc_gross-site_fees) AS sum_amount, from_unixtime(%d) AS fromdt, from_unixtime(%d) AS todt', $fromtimestamp, $totimestamp );
			$query_where   = ['p.post_author' => $uid, 'o.done_seller' => 1, 'o.done_buyer' => 1, 'o.completed' => 1, 'o.closed' => 0, 'o.clearing_period' => 2];
			$query_between = ['column' => 'o.date_made', 'date_min' => $fromtimestamp, 'date_max' => $totimestamp];

			$result_data = wpj_get_job_order_post( $query_fields, $query_where, 'results', $query_between );

		}

		if ( empty( $result_data ) )
			return [0];

		$last_balance = 0;

		if ( $action == 'credit_balance' ) {
			foreach ( $result_data as $key => $result_row ) {
				if ( $result_row->sum_amount > 0 ) {
					$last_balance = $result_row->sum_amount;

				} else {
					$result_data[$key]->sum_amount = $last_balance ;

				}
			}
		}

		if ( $action == 'gross_earning' ) {
			$gross_value = 0;

			if ( $result_data ) {
				foreach ( $result_data as $key => $result_row ) {
					if ( $result_row->sum_amount > 0 ) {
						$gross_value += apply_filters( 'wpj_total_gross_sales_filter', wpj_get_order_total_price( $result_row )['amount'], $result_row, 'gross' );
					}
				}

				$result_data[0]->sum_amount = $gross_value;
			}

		} elseif ( $action == 'net_earning' ) {
			$net_value = 0;

			if ( $result_data ) {
				foreach ( $result_data as $key => $result_row ) {
					if ( $result_row->sum_amount > 0 ) {
						$net_value += apply_filters( 'wpj_total_net_sales_filter', wpj_get_order_total_price( $result_row )['seller_commission'], $result_row, 'net' );
					}
				}

				$result_data[0]->sum_amount = $net_value;
			}

		} else {
			foreach ( $result_data as $key => $result_row ) {
				if ( $result_row->sum_amount > 0 ) {
					$result_data[$key]->sum_amount = wpj_get_exchanged_value( $result_data[$key]->sum_amount, wpj_get_site_default_currency(), wpj_get_site_currency() );
				}
			}

		}

		if ( $result_data )
			return $result_data[0];

		return [0];
	}
}

if ( ! function_exists( 'wpj_get_transaction_amount_array' ) ) {
	function wpj_get_transaction_amount_array( $i, $j, $k, $uid ) {
		$result_earned_gross[$i]   = wpj_get_transaction_amount_by_date( $j, $k, $uid, 'gross_earning' );
		$result_earned_net[$i]     = wpj_get_transaction_amount_by_date( $j, $k, $uid, 'net_earning' );
		$result_spent[$i]          = wpj_get_transaction_amount_by_date( $j, $k, $uid, 'spending' );
		$result_active[$i]         = wpj_get_transaction_amount_by_date( $j, $k, $uid, 'active' );
		$result_completed[$i]      = wpj_get_transaction_amount_by_date( $j, $k, $uid, 'completed' );
		$result_withdraw[$i]       = wpj_get_transaction_amount_by_date( $j, $k, $uid, 'withdraw' );
		$result_pending[$i]        = wpj_get_transaction_amount_by_date( $j, $k, $uid, 'pending_clearance' );
		$result_credit_balance[$i] = wpj_get_transaction_amount_by_date( $j, $k, $uid, 'credit_balance' );

		return [
			'result_earned_gross'   => $result_earned_gross[$i],
			'result_earned_net'     => $result_earned_net[$i],
			'result_spent'          => $result_spent[$i],
			'result_active'         => $result_active[$i],
			'result_completed'      => $result_completed[$i],
			'result_withdraw'       => $result_withdraw[$i],
			'result_pending'        => $result_pending[$i],
			'result_credit_balance' => $result_credit_balance[$i]
		];

	}
}