<?php
/**
 * GurmeCargo SAAS daki tüm gönderiliri listeleyen sınıf
 *
 * @package GurmeHub
 */

/**
 * GurmeCargo gönderileri listeleme tablo sınıfı
 */
if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

/**
 * GurmeCargo gönderileri listeleme tablosu
 */
class GCARGO_Shipments_Table extends WP_List_Table {


	/**
	 * Gönderi durumları.
	 *
	 * @var array $statuses
	 */
	private $statuses;


	/**
	 * {@inheritdoc}
	 */
	public function __construct() {
		parent::__construct(
			[
				'singular' => 'shipment',
				'plural'   => 'shipments',
				'ajax'     => false,
			]
		);

		$gcargo_statuses = gcargo_get_shipment_statuses();
		$this->statuses  = array(
			'all'           => __( 'All', 'kargo-entegrator' ),
			'non_processed' => __( 'Non-Processed', 'kargo-entegrator' ),
		);
		foreach ( $gcargo_statuses as $key => $status ) {
			$this->statuses[ $key ] = $status;
		}
	}

	/**
	 * Gösterilecek gönderiler
	 *
	 * @param int $per_page Sayfa başına gönderi sayısı
	 * @param int $page_number Sayfa numarası
	 */
	public static function get_shipments( $per_page = 20, $page_number = 1 ) {
		global $wpdb;

		$request = gcargo_clean( $_REQUEST );

		$per_page = $request['per_page'] ?? $per_page;

		$limit = ( $page_number - 1 ) * $per_page;

		if ( isset( $request['s'] ) && ! empty( $request['s'] ) ) {

			$search = '%' . $wpdb->esc_like( $request['s'] ) . '%';

			return $wpdb->get_results(
				$wpdb->prepare(
					"SELECT * FROM {$wpdb->prefix}gcargo_shipments WHERE platform_id LIKE %s OR shipment_id LIKE %s OR status LIKE %s ORDER BY id DESC LIMIT %d, %d",
					$search,
					$search,
					$search,
					$limit,
					$per_page,
				),
				ARRAY_A
			);

		}

		if ( ! empty( $request['shipment_status'] ) && 'all' !== $request['shipment_status'] ) {
			return $wpdb->get_results(
				$wpdb->prepare(
					"SELECT * FROM {$wpdb->prefix}gcargo_shipments WHERE status = %s ORDER BY id DESC LIMIT %d, %d",
					$request['shipment_status'],
					$limit,
					$per_page
				),
				ARRAY_A
			);

		}

		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}gcargo_shipments ORDER BY id DESC LIMIT %d, %d",
				$limit,
				$per_page,
			),
			ARRAY_A
		);
	}

	/**
	 * {@inheritdoc}
	 */
	public static function record_count() {
		global $wpdb;
		$request = gcargo_clean( $_REQUEST );

		if ( isset( $request['s'] ) && ! empty( $request['s'] ) ) {
			$search = $request['s'];
			return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}gcargo_shipments WHERE platform_id LIKE %s OR shipment_id LIKE %s OR status LIKE %s", "%$search%", "%$search%", "%$search%" ) );
		}

		return $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}gcargo_shipments" );
	}

	/**
	 * Toplu işlem.
	 *
	 * @return array
	 */
	public function get_bulk_actions() {
		return array(
			'bulk_print' => __( 'Gönderi barkodlarını yazdır', 'kargo-entegrator' ),
		);
	}

	/**
	 * Duruma göre gönderi adedi.
	 *
	 * @param string $status Durum.
	 */
	public static function status_count( $status = 'all' ) {
		global $wpdb;

		if ( 'all' !== $status ) {
			return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}gcargo_shipments WHERE status = %s", $status ) );
		}

		return $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}gcargo_shipments" );
	}

	/**
	 * {@inheritdoc}
	 */
	public function no_items() {
		esc_html_e( 'No shipments available.', 'kargo-entegrator' );
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_columns() {
		return [
			'cb'              => '<input type="checkbox" />',
			'cargo'           => '',
			'platform_id'     => 'Sipariş No',
			'customer'        => 'Müşteri',
			'city'            => __( 'City', 'kargo-entegrator' ),
			'status'          => __( 'Status', 'kargo-entegrator' ),
			'payment_type'    => __( 'Payment Type', 'kargo-entegrator' ),
			'package_type'    => __( 'Package Type', 'kargo-entegrator' ),
			'desi'            => __( 'Desi', 'kargo-entegrator' ),
			'tracking_number' => __( 'Tracking No', 'kargo-entegrator' ),
			'shipping_cost'   => __( 'Shipping Cost', 'kargo-entegrator' ),
			'updated_at'      => __( 'Last Updated', 'kargo-entegrator' ),
		];
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_sortable_columns() {
		return [];
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_cb( $item ) {
		?>
		<input id="cb-select-<?php echo esc_attr( $item['shipment_id'] ); ?>" type="checkbox" name="id[]" value="<?php echo esc_attr( $item['platform_id'] ); ?>" />
		<label for="cb-select-<?php echo esc_attr( $item['shipment_id'] ); ?>">
			<span class="screen-reader-text"><?php esc_html_e( 'Select', 'kargo-entegrator' ); ?></span>
		</label>
		<?php
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_cargo( $item ) {
		?>
			<img width="24" src="<?php echo esc_url( $item['full_json']['cargo_company']['logo'] ); ?>" alt="cargo-company"/>
		<?php
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_status( $item ) {
		?>
		<div class="shipment-status-type <?php echo esc_attr( $item['status'] ); ?>">
			<span><?php echo esc_html( $this->statuses[ $item['status'] ] ); ?></span>
		</div>
		<?php
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed  $item Satır.
	 * @param string $column_name Kolon adı.
	 */
	protected function column_default( $item, $column_name ) {
		return $item[ $column_name ] ?? '';
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_platform_id( $item ) {
		$order = wc_get_order( $item['platform_id'] );
		if ( $order ) {
			return sprintf( '<a href="%s" target="_blank">%s</a>', esc_url( $order->get_edit_order_url() ), esc_html( $item['platform_id'] ) );
		}
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_customer( $item ) {
		$order = wc_get_order( $item['platform_id'] );
		if ( $order ) {
			$customer_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
			return esc_html( trim( $customer_name ) );
		}
		return '-';
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_updated_at( $item ) {

		$timestamp = strtotime( $item['updated_at'] );

		if ( ! $timestamp ) {
			echo '&ndash;';
			return;
		}

		if ( $timestamp > strtotime( '-1 day', time() ) && $timestamp <= time() ) {
			$show_date = sprintf(
			/* translators: %s: Saat farkı için kullanılan saat örn. 10 Dakika Önce */
				_x( '%s ago', '%s = human-readable time difference', 'kargo-entegrator' ),
				human_time_diff( $timestamp, time() )
			);
		} else {
			$show_date = date_i18n( __( 'j F Y', 'kargo-entegrator' ), $timestamp );
		}
		?>
		<time 
			datetime="<?php echo esc_attr( $item['updated_at'] ); ?>" 
			title="<?php echo esc_attr( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $timestamp ) ); ?>">
		<?php echo esc_html( $show_date ); ?>
		</time>

		<?php
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_tracking_number( $item ) {
		return sprintf( '<a href="%s" target="_blank">%s</a>', esc_url( $item['full_json']['tracking_link'] ), esc_html( $item['full_json']['tracking_number'] ) );
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_payment_type( $item ) {
		return 'cash_money' === $item['payment_type'] ? __( 'Cash Money', 'kargo-entegrator' ) : __( 'Credit Card', 'kargo-entegrator' );
	}

	/**
	 * Kolon içeriği.
	 *
	 * @param mixed $item Satır.
	 */
	protected function column_package_type( $item ) {
		return 'box' === $item['package_type'] ? __( 'Box', 'kargo-entegrator' ) : __( 'Document', 'kargo-entegrator' );
	}

	/**
	 * {@inheritdoc}
	 */
	public function prepare_items() {
		$per_page     = $this->get_items_per_page( 'shipments_per_page' );
		$current_page = $this->get_pagenum();
		$total_items  = self::record_count();

		$this->set_pagination_args(
			[
				'total_items' => $total_items,
				'per_page'    => $per_page,
			]
		);

		$columns               = $this->get_columns();
		$hidden                = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array( $columns, $hidden, $sortable );

		$this->items = array_map(
			function ( $item ) {
				$item['full_json'] = json_decode( $item['full_json'], true );
				return $item;
			},
			self::get_shipments( $per_page, $current_page )
		);
	}

	/**
	 * Filtreler.
	 */
	protected function get_views() {
		$link         = '';
		$status_links = array();

		$request = gcargo_clean( $_REQUEST );

		foreach ( $this->statuses as $status => $label ) {
			$count = $this->status_count( $status );

			if ( $count ) {

				$link = add_query_arg(
					array(
						'shipment_status' => $status,
						'page'            => 'gcargo-shipments',
					),
					admin_url( 'admin.php' )
				);

				$status_links[ $status ] = array(
					'url'     => esc_url( $link ),
					'label'   => sprintf( $label . ' <span class="count">(%s)</span>', $count ),
					'current' => isset($request['shipment_status']) && $request['shipment_status'] === $status, //phpcs:ignore
				);
			}
		}

		return $this->get_views_links( $status_links );
	}

	/**
	 * {@inheritdoc}
	 */
	public function render_shipments_page() {

		/**
		 * Nonce verification for admin pages.
		 */
		if ( ! current_user_can( gcargo_capability() ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'kargo-entegrator' ) );
		}

		$this->prepare_items();
		$request = gcargo_clean( $_REQUEST );
		?>
		<div class="wrap">
			<h1 class="wp-heading-inline">
				<?php esc_html_e( 'Shipments', 'kargo-entegrator' ); ?>
			</h1>
			<hr class="wp-header-end">
			<?php $this->views(); ?>
			<form id="gcargo-shipments" method="get">
				<?php $this->search_box( 'Search Shipments', 'shipment' ); ?>
				<input type="hidden" name="page" value="gcargo-shipments" />
				<input type="hidden" name="_total" value="<?php echo esc_attr( $this->get_pagination_arg( 'total_items' ) ); ?>" />
				<input type="hidden" name="_per_page" value="<?php echo esc_attr( $this->get_pagination_arg( 'per_page' ) ); ?>" />
				<input type="hidden" name="_page" value="<?php echo esc_attr( $this->get_pagination_arg( 'page' ) ); ?>" />
				<?php if ( isset( $request['paged'] ) ) : ?> 
				<input type="hidden" name="paged" value="<?php echo esc_attr( absint( $request['paged'] ) ); ?>" /> 
				<?php endif; ?>
				<?php $this->display(); ?>
			</form>
		</div>
		<?php
	}
}
