<?php
/**
 * Log helper
 *
 * @package WooCommerce Points and Rewards
 * @version 1.0.0
 */

namespace DDWCPointsAndRewards\Helper\Log;

defined( 'ABSPATH' ) || exit();

if ( ! class_exists( 'DDWCPR_Log_Helper' ) ) {
	/**
	 * Log helper class
	 */
	class DDWCPR_Log_Helper {
		/**
		 * Database object
		 *
		 * @var object
		 */
		protected $wpdb;

		/**
		 * Configuration Variable
		 *
		 * @var array
		 */
		protected $ddwcpr_configuration;

		/**
		 * Construct
		 */
		public function __construct( $ddwcpr_configuration ) {
			global $wpdb;
			$this->wpdb                 = $wpdb;
			$this->ddwcpr_configuration = $ddwcpr_configuration;
		}

		/**
		 * Save log function
		 *
		 * @param array $data
		 * @return int
		 */
		public function ddwcpr_save_log( $data ) {
			$default_data = [
				'related_id'  => NULL,
				'user_id'     => get_current_user_id(),
				'points'      => 0,
				'description' => '',
				'date'        => current_time( 'Y-m-d H:i:s' ),
				'event'       => '',
			];

			$data = wp_parse_args( $data, $default_data );

			unset( $data['expiration_date'] );

			$this->wpdb->insert(
				$this->wpdb->ddwcpr_points_log,
				$data,
				[ '%d', '%d', '%d', '%s', '%s', '%s' ]
			);

			$user = get_userdata( $data['user_id'] );

			$manual_adjustment_description = '';

			if ( 'manual_adjustment' === $data['event'] ) {
				$email_heading = $this->ddwcpr_configuration['email_settings']['manual_adjustment']['heading'];
				$email_subject = $this->ddwcpr_configuration['email_settings']['manual_adjustment']['subject'];
				$email_message = $this->ddwcpr_configuration['email_settings']['manual_adjustment']['message'];

				$points_amount                 = $data['points'];
				$manual_adjustment_description = $data['description'];
			} else {
				if ( 'points_expired' !== $data['event'] ) {
					if ( $data['points'] > 0 ) {
						$email_heading = $this->ddwcpr_configuration['email_settings']['points_earned']['heading'];
						$email_subject = $this->ddwcpr_configuration['email_settings']['points_earned']['subject'];
						$email_message = $this->ddwcpr_configuration['email_settings']['points_earned']['message'];

						$points_amount = $data['points'];
					} else {
						$email_heading = $this->ddwcpr_configuration['email_settings']['points_redeemed']['heading'];
						$email_subject = $this->ddwcpr_configuration['email_settings']['points_redeemed']['subject'];
						$email_message = $this->ddwcpr_configuration['email_settings']['points_redeemed']['message'];

						$points_amount = -$data['points'];
					}
				}
			}

			if ( ! empty( $email_message ) ) {
				$email_data = [
					'user_id'                       => $data['user_id'],
					'related_id'                    => $data['related_id'],
					'email'                         => $user->user_email,
					'display_name'                  => $user->display_name,
					'event'                         => $data['event'],
					'heading'                       => $email_heading,
					'subject'                       => $email_subject,
					'message'                       => $email_message,
					'points_amount'                 => $points_amount,
					'manual_adjustment_description' => $manual_adjustment_description,
				];

				do_action( 'ddwcpr_mail', $email_data );
			}

			return $this->wpdb->insert_id;
		}

		/**
		 * Prepare where conditions for user logs function
		 *
		 * @param array $args
		 * @return string
		 */
		public function ddwcpr_prepare_where_conditions_for_logs( $args ) {
			extract( $args );
			$conditions = '';

			if ( ! empty( $event ) ) {
				$conditions .= $this->wpdb->prepare( " AND points_log.event=%s", $event );
			}
			if ( ( isset( $from_date ) || isset( $end_date ) ) && ( $from_date || $end_date ) ) {
				$end_date    = ! empty( $end_date ) ? $end_date : current_time( 'Y-m-d' );
				$conditions .= $this->wpdb->prepare( " AND DATE(points_log.date) BETWEEN %s AND %s", $from_date, $end_date );
			}
			if ( ! empty( $user_id ) ) {
				$conditions .= $this->wpdb->prepare( " AND points_log.user_id=%d", $user_id );
			}
			if ( ! empty( $search ) ) {
				$conditions .= $this->wpdb->prepare( " AND points_log.id LIKE %s", '%' . $search . '%' );
			}

			return $conditions;
		}

		/**
		 * Get logs function
		 *
		 * @param array $args
		 * @return array
		 */
		public function ddwcpr_get_logs( $args ) {
			extract( $args );

			$conditions = $this->ddwcpr_prepare_where_conditions_for_logs( $args );
			$response   = $this->wpdb->get_results(
				$this->wpdb->prepare(
					"
					SELECT DISTINCT points_log.*
					FROM {$this->wpdb->ddwcpr_points_log} AS points_log
					LEFT JOIN {$this->wpdb->users} AS users ON points_log.user_id = users.ID
					WHERE 1=1 $conditions
					GROUP BY points_log.id
					ORDER BY points_log.id DESC
					LIMIT %d OFFSET %d
					",
					$per_page,
					$offset
				),
				ARRAY_A
			);

			return apply_filters( 'ddwcpr_modify_logs_data', $response, $args );
		}

		/**
		 * Get logs count function
		 *
		 * @param array $args
		 * @return int
		 */
		public function ddwcpr_get_logs_count( $args ) {
			$conditions = $this->ddwcpr_prepare_where_conditions_for_logs( $args );
			$response   = intval( $this->wpdb->get_var( "SELECT count(DISTINCT points_log.id) FROM {$this->wpdb->ddwcpr_points_log} as points_log JOIN {$this->wpdb->users} as users ON points_log.user_id=users.ID WHERE 1=1 $conditions" ) );

			return apply_filters( 'ddwcpr_modify_total_logs_count', $response, $args );
		}

		/**
		 * Check order log exists function
		 *
		 * @param int $order_id
		 * @return int
		 */
		public function ddwcpr_check_order_log_exists( $order_id ) {
			return intval( $this->wpdb->get_var( $this->wpdb->prepare( "SELECT points_log.id FROM {$this->wpdb->ddwcpr_points_log} as points_log JOIN {$this->wpdb->users} as users ON points_log.user_id=users.ID WHERE related_id=%d", $order_id ) ) );
		}

		/**
		 * Check birthday log exists function
		 *
		 * @param int $user_id
		 * @param string $birth_year
		 * @return int
		 */
		public function ddwcpr_check_birthday_log_exists( $user_id, $birth_year ) {
			return intval( $this->wpdb->get_var( $this->wpdb->prepare( "SELECT points_log.id FROM {$this->wpdb->ddwcpr_points_log} as points_log JOIN {$this->wpdb->users} as users ON points_log.user_id=users.ID WHERE points_log.event=%s AND points_log.user_id=%d AND DATE_FORMAT(points_log.date, '%%Y')=%s", 'birthday', $user_id, $birth_year ) ) );
		}

		/**
		 * Check daily login log exists function
		 *
		 * @param int $user_id
		 * @param string $today_date
		 * @return int
		 */
		public function ddwcpr_check_daily_login_log_exists( $user_id, $today_date ) {
			return intval( $this->wpdb->get_var( $this->wpdb->prepare( "SELECT points_log.id FROM {$this->wpdb->ddwcpr_points_log} as points_log JOIN {$this->wpdb->users} as users ON points_log.user_id=users.ID WHERE points_log.event=%s AND points_log.user_id=%d AND DATE(points_log.date)=%s", 'daily_login', $user_id, $today_date ) ) );
		}

		/**
		 * Render logs table rows function
		 *
		 * @param array $logs
		 * @return void
		 */
		public function ddwcpr_render_logs_table_rows( $logs ) {
			if ( ! empty( $logs ) ) {
				foreach ( $logs as $result ) {
					$result_id       = $result['id'];
					$related_id      = $result['related_id'];
					$result_event    = $result['event'];
					$related_id_html = '-';

					if ( ! empty( $related_id ) ) {
						if ( 'review_submission' === $result_event ) {
							$product = wc_get_product( $related_id );

							if ( $product ) {
								$related_id_html = sprintf( esc_html__( 'Product: %s', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<a href=' . esc_url( $product->get_permalink() ) . ' target="_blank">' . esc_html( $product->get_name() ) . '</a>' );
							}
						} else {
							$order = wc_get_order( $related_id );
							if ( $order ) {
								$related_id_html = sprintf( esc_html__( 'Order: %s', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<a href=' . esc_url( $order->get_view_order_url() ) . ' target="_blank">#' . esc_html( $order->get_order_number() ) . '</a>' );
							} else {
								// For Coupon
								$coupon = new \WC_Coupon( $related_id );
								if ( $coupon->get_id() ) {
									$related_id_html = sprintf( esc_html__( 'Coupon: %s', 'loyaltyx-points-and-rewards-for-woocommerce' ), strtoupper( $coupon->get_code() ) );
								}
							}
						}
					}

					?>
					<tr>
						<td><?php echo esc_html( ddwcpr_get_translation( $result_event ) ); ?></td>
						<td>
							<?php
							if ( $result['points'] > 0 ) {
								?>
								<span class="ddwcpr-added">+<?php echo esc_html( $result['points'] ); ?></span>
								<?php
							} else if ( $result['points'] < 0 ) {
								?>
								<span class="ddwcpr-deducted"><?php echo esc_html( $result['points'] ); ?></span>
								<?php
							} else {
								?>
								<span class="ddwcpr-normal"><?php echo esc_html( $result['points'] ); ?></span>
								<?php
							}
							?>
						</td>
						<td><?php echo esc_html( $result['description'] ); ?></td>
						<td><?php echo wp_kses_post( $related_id_html ); ?></td>
						<td><?php echo esc_html( date_i18n( 'F d, Y g:i:s A', strtotime( $result['date'] ) ) ); ?></td>
					</tr>
					<?php
				}
			}
		}
	}
}
