<?php
/**
 * GCARGO_Actions sınıfını barındıran dosya.
 *
 * @package GurmeHub
 */

/**
 * Bu sınıf eklentinin kendi kancalarına tutunur.
 */
class GCARGO_Actions {


	/**
	 * Eklenti Prefix
	 *
	 * @var string $prefix
	 */
	protected $prefix = GCARGO_PREFIX;


	/**
	 * Gönderi adedinin tutulduğu meta key
	 *
	 * @var string $item_meta_key
	 */
	private $shipment_item_meta_key = '_gcargo_shipped_qty';

	/**
	 * İade adedinin tutulduğu meta key
	 *
	 * @var string $item_meta_key
	 */
	private $returned_item_meta_key = '_gcargo_returned_qty';

	/**
	 * Kurucu method
	 */
	public function __construct() {
		add_action( "{$this->prefix}_shipment_store_request_completed", array( $this, 'add_shipment' ) );
		add_action( "{$this->prefix}_returned_store_request_completed", array( $this, 'add_returned' ) );
		add_action( "{$this->prefix}_shipment_destroy_request_completed", array( $this, 'delete_shipment' ) );
		add_action( "{$this->prefix}_returned_destroy_request_completed", array( $this, 'delete_returned' ) );
		add_action( "{$this->prefix}_shipment_notification_request_completed", array( $this, 'update_shipment' ) );
		add_action( "{$this->prefix}_returned_notification_request_completed", array( $this, 'update_returned' ) );
		add_action( "{$this->prefix}_update_shipment", array( $this, 'update_wc_order_status' ), 10, 2 );
		add_action( "{$this->prefix}_migrate_shipment", array( $this, 'migrate_shipment' ) );
	}

	/**
	 * Gönderileri post_metadan kendi tablosuna taşır
	 *
	 * @param array $shipment Gönderi bilgisi.
	 */
	public function migrate_shipment( $shipment ) {
		$new_row              = gcargo_shipment()->load_data( $shipment );
		$new_row->shipment_id = $shipment['id'];
		$new_row->city        = $shipment['receiver']['city'];
		$new_row->full_json   = wp_json_encode( $shipment );
		$new_row->save();
		$order = wc_get_order( $shipment['platform_id'] );
		if ( $order ) {
			$order->delete_meta_data( 'gcargo_shipments' );
		}
	}

	/**
	 * Gönderi oluştuğunda sipariş verilerine gönderi bilgisini ekleme.
	 *
	 * @param array $response Gönderi bilgisi.
	 */
	public function add_shipment( $response ) {
		$order = wc_get_order( $response['platform_id'] );

		if ( $order ) {
			$shipment              = gcargo_shipment()->load_data( $response );
			$shipment->shipment_id = $response['id'];
			$shipment->city        = $response['receiver']['city'];
			$shipment->full_json   = wp_json_encode( $response );
			$shipment->save();

			foreach ( $response['lines'] as $line ) {
				$qty = (int) wc_get_order_item_meta( $line['platform_id'], $this->shipment_item_meta_key, true );
				wc_update_order_item_meta( $line['platform_id'], $this->shipment_item_meta_key, $qty + $line['quantity'] );
			}

			$order->save();

			$this->update_wc_order_status(
				$order,
				[
					'shipment_id' => $response['id'],
					'status'      => 'non_processed',
				]
			);
			do_action( $this->prefix . '_add_shipment', $order, $shipment );
		}
	}

	/**
	 * İade oluştuğunda sipariş verilerine iade bilgisini ekleme.
	 *
	 * @param array $response İade bilgisi.
	 */
	public function add_returned( $response ) {
		$order = wc_get_order( $response['platform_id'] );

		if ( $order ) {
			$returned              = gcargo_returned()->load_data( $response );
			$returned->returned_id = $response['id'];
			$returned->city        = $response['sender']['city'];
			$returned->full_json   = wp_json_encode( $response );
			$returned->save();

			foreach ( $response['lines'] as $line ) {
				$qty = (int) wc_get_order_item_meta( $line['platform_id'], $this->returned_item_meta_key, true );
				wc_update_order_item_meta( $line['platform_id'], $this->returned_item_meta_key, $qty + $line['quantity'] );
			}

			$order->save();
			do_action( $this->prefix . '_add_returned', $order, $returned );
		}
	}

	/**
	 * Gönderi iptal edildiğinde sipariş verilerinden gönderi bilgisini siler.
	 *
	 * @param array $response Gönderi bilgisi.
	 */
	public function delete_shipment( $response ) {

		$order = wc_get_order( $response['platform_id'] );

		if ( $order ) {
			gcargo_shipment( $response['id'] )->delete();

			$status = gcargo_other_settings()->get_setting_by_key( 'cancel_status' );
			$order->update_status( empty( $status ) ? 'wc-processing' : $status, '<b style="color: #4338ca;">Kargo Entegratör:</b>' );

			foreach ( $response['lines'] as $line ) {
				$qty = (int) wc_get_order_item_meta( $line['platform_id'], $this->shipment_item_meta_key, true );
				wc_update_order_item_meta( $line['platform_id'], $this->shipment_item_meta_key, $qty - $line['quantity'] );
			}

			$order->save();
		}
	}

	/**
	 * İade iptal edildiğinde sipariş verilerinden iade bilgisini siler.
	 *
	 * @param array $response İade bilgisi.
	 */
	public function delete_returned( $response ) {

		$order = wc_get_order( $response['platform_id'] );

		if ( $order ) {
			gcargo_returned( $response['id'] )->delete();

			foreach ( $response['lines'] as $line ) {
				$qty = (int) wc_get_order_item_meta( $line['platform_id'], $this->returned_item_meta_key, true );
				wc_update_order_item_meta( $line['platform_id'], $this->returned_item_meta_key, $qty - $line['quantity'] );
			}

			$order->save();
		}
	}


	/**
	 * SaaS tarafından gelen bildirimleri yorumlar
	 *
	 * @param array $post_data Bildirim verisi.
	 */
	public function update_shipment( $post_data ) {

		$shipment_data = gcargo_shipments_resource()->show( $post_data['shipment_id'] );

		$order = wc_get_order( $shipment_data['platform_id'] );

		if ( $order ) {

			$shipment            = gcargo_shipment( $shipment_data['id'] )->load_data( $shipment_data );
			$shipment->full_json = wp_json_encode( $shipment_data );
			$shipment->save();
			do_action( $this->prefix . '_update_shipment', $order, $shipment_data );
		}
	}

	/**
	 * SaaS tarafından gelen iade bildirimlerini yorumlar
	 *
	 * @param array $post_data Bildirim verisi.
	 */
	public function update_returned( $post_data ) {

		$returned_data = gcargo_returneds_resource()->show( $post_data['returned_id'] );

		$order = wc_get_order( $returned_data['platform_id'] );

		if ( $order ) {

			$returned            = gcargo_returned( $returned_data['id'] )->load_data( $returned_data );
			$returned->full_json = wp_json_encode( $returned_data );
			$returned->save();
			do_action( $this->prefix . '_update_returned', $order, $returned_data );
		}
	}

	/**
	 * SaaS tarafından gelen bildirimlere göre sipariş durumunu değiştiren fonksiyon.
	 *
	 * @param WC_Order $order Sipariş verisi.
	 * @param array    $shipment_data Bildirim verisi.
	 */
	public function update_wc_order_status( $order, $shipment_data ) {

		if ( $order ) {
			$settings = gcargo_wc_order_status_settings()->get_settings();

			foreach ( $settings as $setting ) {
				if ( $setting->active && $setting->key === $shipment_data['status'] ) {
					$order->update_status( $setting->status, '<b style="color: #4338ca;">Kargo Entegratör:</b>' );
					do_action( $this->prefix . '_shippment_status_update_' . $shipment_data['status'], $shipment_data, $order );
					break;
				}
			}

			$email = WC()->mailer()->emails[ $shipment_data['status'] ];
			$email->trigger( $order->get_id(), $shipment_data );
		}
	}
}
