<?php
/**
 * Payment Log Controller.
 *
 * @since 1.7.6
 *
 * @package  EverestForms/Classes
 */

defined( 'ABSPATH' ) || exit;

/**
 * EVFP_Payment_Log Class.
 */
class EVFP_Payment_Log {




	/**
	 * The namespace of this controller's route.
	 *
	 * @var string The namespace of this controller's route.
	 */
	protected $namespace = 'everest-forms-pro/v1';

	/**
	 * The base of this controller's route.
	 *
	 * @var string The base of this controller's route.
	 */
	protected $rest_base = 'payment_log';

	/**
	 * Register routes.
	 *
	 * @since 1.7.6
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/get-form-list',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( __CLASS__, 'get_form_list' ),
					'permission_callback' => array( __CLASS__, 'check_admin_permissions' ),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/get-payment-entry',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( __CLASS__, 'get_payment_entry' ),
					'permission_callback' => array( __CLASS__, 'check_admin_permissions' ),
				),
			)
		);
	}

	/**
	 * Get item.
	 *
	 * @param \WP_Rest_Request $request Full detail about the request.
	 * @return \WP_Error|\WP_REST_Response
	 */
	public static function get_form_list( $request ) {
		$forms = evf_get_all_forms();
		$data  = array();

		foreach ( $forms as $form_id => $form_title ) {
			$data[] = array(
				'value' => $form_id,
				'label' => $form_title
			);
		}

		return new \WP_REST_Response(
			array(
				'success'   => true,
				'form_list' => $data,
			),
			200
		);
	}

	/**
	 * Get payment entry.
	 *
	 * @since 1.7.6
	 */
	public static function get_payment_entry( $request ) {
		if ( ! isset( $request['request'] ) || empty( $request['request'] ) ) {

			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => esc_html__( 'Request data not found.', 'easy-mail-smtp' ),
				),
				200
			);
		}

		$requested_data = $request['request'];
		$page_size      = isset( $requested_data['page_size'] ) ? absint( $requested_data['page_size'] ) : 5;
		$offset         = isset( $requested_data['offset'] ) ? $requested_data['offset'] : 0;
		$form_id        = isset( $requested_data['form_id'] ) && ! empty( $requested_data['form_id'] ) ? absint( $requested_data['form_id'] ) : 0;
		$status         = isset( $requested_data['payment_status'] ) && ! empty( $requested_data['payment_status'] ) ? ucfirst( $requested_data['payment_status'] ) : '';
		$searchQuery    = isset( $requested_data['search_query'] ) && ! empty( $requested_data['search_query'] ) ? $requested_data['search_query'] : '';

		$data        = array();
		$payment_log = self::evf_get_payment_log( $page_size, $offset, $form_id, $status, $searchQuery );

		return new \WP_REST_Response(
			array(
				'success'     => true,
				'payment_log' => $payment_log,
			),
			200
		);
	}

	/**
	 * Get payment log.
	 *
	 * @since 1.7.6
	 *
	 * @param  array $entry Entry.
	 */
	public static function evf_get_payment_log( $page_size, $offset, $form_id, $status, $searchQuery ) {
		global $wpdb;

		$table_name = $wpdb->prefix . 'evf_entrymeta';
		$sql        = "SELECT entry_id FROM `$table_name` WHERE meta_key = 'type' AND meta_value = 'payment'";

		$entry_id = $wpdb->get_results( $sql, ARRAY_A );

		$data         = array();
		$payment_data = array();
		$data_to_send = array();
		$first_name   = '';
		$last_name    = '';

		if ( empty( $entry_id ) ) {
			return new \WP_REST_Response(
				array(
					'success'       => false,
					'type_of_error' => 'no_data',
					'message'       => 'No payment log available.'
				),
				200
			);
		}

		foreach ( $entry_id as $id ) {
			if ( '' === $searchQuery ) {
				$data[] = evf_get_entry( $id['entry_id'] );
			} else {
				$search_query     = '%' . $searchQuery . '%';
				$sql              = $wpdb->prepare( "SELECT entry_id FROM `$table_name` WHERE entry_id = %d AND meta_value LIKE %s", $id['entry_id'], $search_query );
				$search_entry_ids = $wpdb->get_results( $sql, ARRAY_A );
				foreach ( $search_entry_ids as $search_entry_id ) {
					$data[] = evf_get_entry( $search_entry_id['entry_id'] );
					break;
				}
			}
		}

		foreach ( $data as $value ) {
			$payment_data[] = array(
				'fields'   => $value->fields,
				'meta'     => $value->meta['meta'],
				'form_id'  => $value->form_id,
				'entry_id' => $value->entry_id
			);
		}

		foreach ( $payment_data as $payments ) {
			$decoded_fields = json_decode( $payments['fields'], true );
			$decoded_meta   = json_decode( $payments['meta'], true );
			$payment_status = self::get_payment_status( $payments['entry_id'] );
			$temp_form_id   = absint( $payments['form_id'] );
			$temp_data      = array();
			foreach ( $decoded_fields as $fields ) {
				if ( ( 0 != $form_id && '' != $status ) || ( 0 != $form_id && '' != $status && '' != $searchQuery ) ) {
					if ( $form_id === $temp_form_id && $status === $payment_status ) {
						$field_type = isset( $fields['type'] ) ? $fields['type'] : '';
						$temp_data  = self::append_temp_data( $field_type, $temp_data, $fields );
					}
				} elseif ( '' != $status || ( '' != $status && '' != $searchQuery ) ) {
					if ( $status === $payment_status ) {
						$field_type = isset( $fields['type'] ) ? $fields['type'] : '';
						$temp_data  = self::append_temp_data( $field_type, $temp_data, $fields );
					}
				} elseif ( 0 != $form_id ) {
					if ( $form_id === $temp_form_id ) {
						$field_type = isset( $fields['type'] ) ? $fields['type'] : '';
						$temp_data  = self::append_temp_data( $field_type, $temp_data, $fields );
					}
				} else {
					$field_type = isset( $fields['type'] ) ? $fields['type'] : '';
					$temp_data  = self::append_temp_data( $field_type, $temp_data, $fields );
				}
			}

			if ( ( 0 != $form_id && '' != $status ) || ( 0 != $form_id && '' != $status && '' != $searchQuery ) ) {
				if ( $form_id === $temp_form_id && $status === $payment_status ) {
					$data_to_send = self::append_extra_data_to_temp_data( $temp_data, $decoded_meta, $payments, $payment_status, $data_to_send );
				}
			} elseif ( '' != $status || ( '' != $status && '' != $searchQuery ) ) {
				if ( $status === $payment_status ) {
					$data_to_send = self::append_extra_data_to_temp_data( $temp_data, $decoded_meta, $payments, $payment_status, $data_to_send );
				}
			} elseif ( 0 != $form_id ) {
				if ( $form_id === $temp_form_id ) {
					$data_to_send = self::append_extra_data_to_temp_data( $temp_data, $decoded_meta, $payments, $payment_status, $data_to_send );
				}
			} else {
				$data_to_send = self::append_extra_data_to_temp_data( $temp_data, $decoded_meta, $payments, $payment_status, $data_to_send );
			}
		}

		$count = count( $data_to_send );
		return array(
			'total_count' => $count,
			'result'      => array_slice( $data_to_send, $offset, $page_size )
		);
	}

	/**
	 * Append data to temp.
	 *
	 * @since 1.7.6
	 *
	 * @param  string $field_type Field type.
	 * @param  array  $temp_data Temp data.
	 * @param  array  $fields Fields.
	 */
	protected static function append_temp_data( $field_type, $temp_data, $fields ) {
		switch ( $field_type ) {
			case 'first-name':
			case 'last-name':
				$temp_data[ $field_type ] = ! empty( $fields['value'] ) ? $fields['value'] : '';
				break;
			default:
				break;
		}
		return $temp_data;
	}

	/**
	 * Append extra data to temp_data.
	 *
	 * @since 1.7.6
	 *
	 * @param  array $temp_data Temp data.
	 * @param  array $decoded_meta Decoded meta data.
	 * @param  array $payments Payments data.
	 * @param  array $payment_status Payment status.
	 * @param  array $data_to_send Data to send.
	 */
	protected static function append_extra_data_to_temp_data( $temp_data, $decoded_meta, $payments, $payment_status, $data_to_send ) {
		$first_name          = isset( $temp_data['first-name'] ) ? ucfirst( $temp_data['first-name'] ) : '';
		$last_name           = isset( $temp_data['last-name'] ) ? ucfirst( $temp_data['last-name'] ) : '';
		$payment_transaction = isset( $decoded_meta['payment_transaction'] ) ? $decoded_meta['payment_transaction'] : '';

		$temp_data['customer']            = $first_name . ' ' . $last_name;
		$temp_data['total_amount']        = isset( $decoded_meta['payment_total'] ) ? $decoded_meta['payment_total'] : '';
		$temp_data['payment_gateway']     = isset( $decoded_meta['payment_gateway'] ) ? ucfirst( $decoded_meta['payment_gateway'] ) : '';
		$temp_data['payment_currency']    = isset( $decoded_meta['payment_currency'] ) ? $decoded_meta['payment_currency'] : '';
		$temp_data['submission_id']       = isset( $payments['entry_id'] ) ? $payments['entry_id'] : '';
		$temp_data['status']              = $payment_status;
		$temp_data['form']                = self::evf_get_form_title( $payments['form_id'] );
		$temp_data['payment_transaction'] = $payment_transaction;

		if ( ! isset( $decoded_meta['payment_gateway'] ) ) {
			$temp_data['receipt_url'] = '';
		} else {
			switch ( $decoded_meta['payment_gateway'] ) {
				case 'stripe':
					$temp_data['receipt_url'] = 'https://dashboard.stripe.com/payments/' . $payment_transaction;
					break;
				case 'paypal':
					$temp_data['receipt_url'] = 'https://www.paypal.com/receipt/?id=' . $payment_transaction;
					break;
				case 'square':
					$temp_data['receipt_url'] = isset( $decoded_meta['receipt_url'] ) ? $decoded_meta['receipt_url'] : '';
					break;
				case 'mollie':
					$temp_data['receipt_url'] = isset( $decoded_meta['payment_details_url'] ) ? $decoded_meta['payment_details_url'] : '';
					break;
				default:
					$temp_data['receipt_url'] = '';
					break;
			}
		}

		$data_to_send[] = $temp_data;
		return $data_to_send;
	}

	/**
	 * Get payment status.
	 *
	 * @since 1.7.6
	 *
	 * @param  int $entry_id Entry Id.
	 */
	public static function get_payment_status( $entry_id ) {
		global $wpdb;

		$table_name = $wpdb->prefix . 'evf_entrymeta';

		$sql = $wpdb->prepare(
			"SELECT meta_value FROM {$table_name} WHERE entry_id = %d AND meta_key = %s",
			$entry_id,
			'status'
		);

		$status = $wpdb->get_results( $sql, ARRAY_A );

		return ucfirst( $status[0]['meta_value'] );
	}

	/**
	 * Get form title.
	 *
	 * @since 1.7.6
	 *
	 * @param  int $form_id Form Id.
	 */
	protected static function evf_get_form_title( $form_id ) {
		if ( empty( $form_id ) ) {
			return;
		}

		return ucfirst( get_post( $form_id )->post_title );
	}

	/**
	 * Check if a given request has access to update a setting
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_Error|bool
	 */
	public static function check_admin_permissions( $request ) {
		return current_user_can( 'manage_options' );
	}
}
