<?php
class WPJ_Resolution_Center extends \stdClass {
	public function __construct() {
		add_action( 'init', [ $this, 'catch_ajax_posts' ] );
	}

	public static function init() {
		$class = __CLASS__; new $class;
	}

	public function getRowQuery( $filter = '', $rows_per_page = 10, $pageno = 1, $limited = false ) {
		global $wpdb;

		$user         = WPJ_Form::get( 'search_user' );
		$search_input = ctype_digit( $user ) || is_int( $user ) ? $user : '';

		if ( ! $search_input ) {
			$search_input = wpj_get_user( 'ID', ['user_login' => $user], 'var' );
		}

		$query = "SELECT DISTINCT *, joa.id AS arbitration_id FROM {$wpdb->prefix}job_orders_arbitration joa, {$wpdb->prefix}job_orders jo WHERE joa.order_id = jo.id";

		if ( $filter == 'active' ) {
			$query .= " AND joa.seller_arbitration = 0 AND joa.buyer_arbitration = 0 AND ( request_from_seller = 1 || request_from_buyer = 1 )";
		} elseif ( $filter == 'completed_buyer' ) {
			$query .= " AND joa.seller_arbitration = 0 AND joa.buyer_arbitration = 1";
		} elseif ( $filter == 'completed_seller' ) {
			$query .= " AND joa.seller_arbitration = 1 AND joa.buyer_arbitration = 0";
		} elseif ( $filter == 'completed' ) {
			$query .= " AND ( joa.seller_arbitration = 1 OR joa.buyer_arbitration = 1 )";
		} elseif ( $filter == 'aborted' ) {
			$query .= " AND request_from_seller = 0 AND request_from_buyer = 0";
		}

		if ( is_numeric( $search_input ) ) {
			$query .= " AND ( joa.request_from_buyer = {$search_input} OR joa.request_from_seller = {$search_input} OR joa.id = {$search_input} OR joa.order_id = {$search_input} )";
		}

		$query .= " ORDER BY joa.id DESC";

		if ( $limited ) $query .= " LIMIT " . ( $pageno - 1 ) * $rows_per_page . ',' . $rows_per_page;

		return $query;
	}

	public function getCountOfOrders( $filter = '' ) {
		global $wpdb;

		$query   = $this->getRowQuery( $filter );
		$results = $wpdb->get_results( $query );
		$count   = $results ? count( $results ) : 0;

		return $count;
	}

	public function getOrderRow( $filter = '' ) {
		$r = [ 'all' => '', 'limited' => '', 'lastpage' => '', 'pageno' => '' ];

		global $wpdb;

		$rows_per_page = 20;

		if ( isset( $_GET['pj'] ) ) $pageno = $_GET['pj'];
		else $pageno = 1;

		$s1 = $this->getRowQuery( $filter, $rows_per_page, $pageno, false );
		$s  = $this->getRowQuery( $filter, $rows_per_page, $pageno, true );

		$nr       = count( $wpdb->get_results( $s1 ) );
		$lastpage = ceil( $nr / $rows_per_page );

		$r = [
			'all'      => $wpdb->get_results( $s ),
			'limited'  => $wpdb->get_results( $s1 ),
			'lastpage' => $lastpage,
			'pageno'   => $pageno,
			'count'    => $nr
		];

		return $r;
	}

	public function catch_ajax_posts() {
		if ( ! is_demo_admin() ) {

			if ( isset( $_POST['arbitration_id'] ) ) {
				if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
					$id      = $_POST['arbitration_id'];
					$action  = $_POST['arbitration_for'];
					$message = $_POST['message'];
					$tm      = current_time( 'timestamp', 1 );

					if ( $action == 'completed_for_buyer' ) {
						$query_uid_buyer    = '-43';
						$query_uid_seller   = '-44';
						$buyer_arbitration  = 1;
						$seller_arbitration = 0;

					} elseif ( $action == 'completed_for_seller' ) {
						$query_uid_buyer    = '-42';
						$query_uid_seller   = '-41';
						$buyer_arbitration  = 0;
						$seller_arbitration = 1;

					}

					$current_arbitration_order = wpj_get_arbitration_order( 'id, order_id, buyer_arbitration, seller_arbitration', ['id' => $id], 'row' );

					if ( $current_arbitration_order ) {
						if ( $current_arbitration_order->buyer_arbitration == 0 && $current_arbitration_order->seller_arbitration == 0 ) {
							$order = wpj_get_job_order_by_id( $current_arbitration_order->order_id );

							$seller_id = wpj_get_seller_id( $order );
							$buyer_id  = $order->uid;

							$message_from_support = $message ? $message : __( 'None', 'wpjobster' );

							// Update arbitration
							wpj_update_arbitration_order(
								['buyer_arbitration' => $buyer_arbitration, 'seller_arbitration' => $seller_arbitration, 'message_from_support' => $message, 'date_arbitration' => $tm],
								['id' => $id]
							);

							// Insert notifications
							$this_notification_buyer = wpj_insert_order_notification( ['uid' => $query_uid_buyer, 'oid' => $current_arbitration_order->order_id, 'content' => $message], ['%d', '%d', '%s'] );

							if ( $this_notification_buyer > 0 ) {
								wpj_update_user_notifications( [
									'user1'       => $buyer_id,
									'user2'       => $seller_id,
									'type'        => 'notifications',
									'number'      => +1,
									'notify_id'   => $this_notification_buyer,
									'notify_type' => 'arb_request_answer',
									'order_id'    => $current_arbitration_order->order_id
								] );
							}

							$this_notification_seller = wpj_insert_order_notification( ['uid' => $query_uid_seller, 'oid' => $current_arbitration_order->order_id, 'content' => $message], ['%d', '%d', '%s'] );

							if ( $this_notification_seller > 0 ) {
								wpj_update_user_notifications( [
									'user1'       => $seller_id,
									'user2'       => $buyer_id,
									'type'        => 'notifications',
									'number'      => +1,
									'notify_id'   => $this_notification_seller,
									'notify_type' => 'arb_request_answer',
									'order_id'    => $current_arbitration_order->order_id
								] );
							}

							// Send emails
							if ( $action == 'completed_for_buyer' ) {
								// to seller
								wpj_notify_user_translated( 'arb_request_closed_buyer', $seller_id, [
									'##username##'              => wpj_get_user_display_type( $seller_id ),
									'##buyer_username##'        => wpj_get_user_display_type( $buyer_id ),
									'##job_name##'              => $order->job_title,
									'##job_link##'              => urldecode( get_permalink( $order->pid ) ),
									'##transaction_number##'    => wpj_camouflage_oid( $current_arbitration_order->order_id, $order->date_made ),
									'##transaction_page_link##' => wpj_get_order_link( $current_arbitration_order->order_id ),
									'##message_from_support##'  => $message_from_support
								] );

								// to buyer
								wpj_notify_user_translated( 'arb_request_closed_buyer', $buyer_id, [
									'##username##'              => wpj_get_user_display_type( $buyer_id ),
									'##buyer_username##'        => wpj_get_user_display_type( $buyer_id ),
									'##job_name##'              => $order->job_title,
									'##job_link##'              => urldecode( get_permalink( $order->pid ) ),
									'##transaction_number##'    => wpj_camouflage_oid( $current_arbitration_order->order_id, $order->date_made ),
									'##transaction_page_link##' => wpj_get_order_link( $current_arbitration_order->order_id ),
									'##message_from_support##'  => $message_from_support
								] );

							} elseif ( $action == 'completed_for_seller' ) {
								// to seller
								wpj_notify_user_translated( 'arb_request_closed_seller', $seller_id, [
									'##username##'              => wpj_get_user_display_type( $seller_id ),
									'##seller_username##'       => wpj_get_user_display_type( $seller_id ),
									'##job_name##'              => $order->job_title,
									'##job_link##'              => urldecode( get_permalink( $order->pid ) ),
									'##transaction_number##'    => wpj_camouflage_oid( $current_arbitration_order->order_id, $order->date_made ),
									'##transaction_page_link##' => wpj_get_order_link( $current_arbitration_order->order_id ),
									'##message_from_support##'  => $message_from_support
								] );

								// to buyer
								wpj_notify_user_translated( 'arb_request_closed_seller', $buyer_id, [
									'##username##'              => wpj_get_user_display_type( $buyer_id ),
									'##seller_username##'       => wpj_get_user_display_type( $seller_id ),
									'##job_name##'              => $order->job_title,
									'##job_link##'              => urldecode( get_permalink( $order->pid ) ),
									'##transaction_number##'    => wpj_camouflage_oid( $current_arbitration_order->order_id, $order->date_made ),
									'##transaction_page_link##' => wpj_get_order_link( $current_arbitration_order->order_id ),
									'##message_from_support##'  => $message_from_support
								] );

							}

							// Action after
							do_action( 'wpj_after_admin_order_arbitration', $order->id, 'job_purchase', $buyer_arbitration );

							// Refund if is in the favor of buyer
							if ( $buyer_arbitration == 1 ) {
								wpj_refund_payment( wpj_get_job_order_by_id( $current_arbitration_order->order_id ), $current_arbitration_order->order_id );

								// insert to order table
								if ( apply_filters( 'wpj_change_order_data_filter', true, $order->id, 'arbitration' ) ) {
									wpj_update_job_order(
										['closed' => 1, 'force_cancellation' => 4, 'date_closed' => $tm],
										['id' => $current_arbitration_order->order_id]
									);
								}
							}
						}
					}

					exit;
				}
			}
		}

	}
}

add_action( 'after_setup_theme', [ 'WPJ_Resolution_Center', 'init' ] );